lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 77a4c4c77e29453dbfe70bf300862388ef135b01 | 0 | normanbrobinson/brailleblaster.old,DynamicalSystem/brailleblaster.old,gkearney/brailleblaster.old,mazhen2009/brailleblaster.old,larsvoigt/brailleblaster.old,teambraison/brailleblaster.old,DynamicalSystem/brailleblaster.old,teambraison/brailleblaster.old,larsvoigt/brailleblaster.old,normanbrobinson/brailleblaster.old,normanbrobinson/brailleblaster.old,gkearney/brailleblaster.old,mazhen2009/brailleblaster.old,gkearney/brailleblaster.old,DynamicalSystem/brailleblaster.old,mazhen2009/brailleblaster.old,larsvoigt/brailleblaster.old,teambraison/brailleblaster.old | /* BrailleBlaster Braille Transcription Application
*
* Copyright (C) 2010, 2012
* ViewPlus Technologies, Inc. www.viewplus.com
* and
* Abilitiessoft, Inc. www.abilitiessoft.com
* and
* American Printing House for the Blind, Inc. www.aph.org
*
* All rights reserved
*
* This file may contain code borrowed from files produced by various
* Java development teams. These are gratefully acknoledged.
*
* This file is free software; you can redistribute it and/or modify it
* under the terms of the Apache 2.0 License, as given at
* http://www.apache.org/licenses/
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
* See the Apache 2.0 License for more details.
*
* You should have received a copy of the Apache 2.0 License along with
* this program; see the file LICENSE.
* If not, see
* http://www.apache.org/licenses/
*
* Maintained by John J. Boyer [email protected]
*/
package org.brailleblaster;
import org.brailleblaster.wordprocessor.WPManager;
import org.eclipse.swt.widgets.Display;
import org.liblouis.liblouisutdml;
/**
* This class contains the main method. If there are no arguments it
* passes control directly to the word processor. If there are arguments
* it passes them first to BBIni and then to Subcommands.
* It will do more processing as the project develops.
*/
public class Main {
public static void main (String[] args) {
BBIni.initialize(args);
BBIni.setVersion ("brailleblaster-2012.2");
BBIni.setReleaseDate ("December 11, 2012");
if (BBIni.haveSubcommands()) {
new Subcommands(args);
} else {
new WPManager (null);
}
Display display = BBIni.getDisplay();
if (display != null)
display.dispose();
if (BBIni.haveLiblouisutdml())
{
liblouisutdml louisutdml = liblouisutdml.getInstance ();
louisutdml.free();
}
}
}
| src/main/org/brailleblaster/Main.java | /* BrailleBlaster Braille Transcription Application
*
* Copyright (C) 2010, 2012
* ViewPlus Technologies, Inc. www.viewplus.com
* and
* Abilitiessoft, Inc. www.abilitiessoft.com
* and
* American Printing House for the Blind, Inc. www.aph.org
*
* All rights reserved
*
* This file may contain code borrowed from files produced by various
* Java development teams. These are gratefully acknoledged.
*
* This file is free software; you can redistribute it and/or modify it
* under the terms of the Apache 2.0 License, as given at
* http://www.apache.org/licenses/
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
* See the Apache 2.0 License for more details.
*
* You should have received a copy of the Apache 2.0 License along with
* this program; see the file LICENSE.
* If not, see
* http://www.apache.org/licenses/
*
* Maintained by John J. Boyer [email protected]
*/
package org.brailleblaster;
import org.brailleblaster.wordprocessor.WPManager;
import org.eclipse.swt.widgets.Display;
import org.liblouis.liblouisutdml;
/**
* This class contains the main method. If there are no arguments it
* passes control directly to the word processor. If there are arguments
* it passes them first to BBIni and then to Subcommands.
* It will do more processing as the project develops.
*/
public class Main {
public static void main (String[] args) {
BBIni.initialize(args);
BBIni.setVersion ("brailleblaster-1.4.0");
BBIni.setReleaseDate ("July 17, 2012");
if (BBIni.haveSubcommands()) {
new Subcommands(args);
} else {
new WPManager (null);
}
Display display = BBIni.getDisplay();
if (display != null)
display.dispose();
if (BBIni.haveLiblouisutdml())
{
liblouisutdml louisutdml = liblouisutdml.getInstance ();
louisutdml.free();
}
}
}
| Corrected version and release date
| src/main/org/brailleblaster/Main.java | Corrected version and release date | <ide><path>rc/main/org/brailleblaster/Main.java
<ide> public class Main {
<ide> public static void main (String[] args) {
<ide> BBIni.initialize(args);
<del>BBIni.setVersion ("brailleblaster-1.4.0");
<del>BBIni.setReleaseDate ("July 17, 2012");
<add>BBIni.setVersion ("brailleblaster-2012.2");
<add>BBIni.setReleaseDate ("December 11, 2012");
<ide> if (BBIni.haveSubcommands()) {
<ide> new Subcommands(args);
<ide> } else { |
|
Java | apache-2.0 | 8a10f9f15e4705142f8edeca4e78124010d21673 | 0 | akashche/disl-mirror,akashche/disl-mirror,akashche/disl-mirror,akashche/disl-mirror | package ch.usi.dag.disl.exclusion;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import ch.usi.dag.disl.cbloader.ManifestHelper;
import ch.usi.dag.disl.cbloader.ManifestHelper.ManifestInfo;
import ch.usi.dag.disl.exception.ExclusionPrepareException;
import ch.usi.dag.disl.exception.ManifestInfoException;
import ch.usi.dag.disl.exception.ScopeParserException;
import ch.usi.dag.disl.scope.Scope;
import ch.usi.dag.disl.scope.ScopeImpl;
import ch.usi.dag.disl.util.Constants;
public abstract class ExclusionSet {
private static final String PROP_EXCLIST = "disl.exclusionList";
private static final String excListPath =
System.getProperty(PROP_EXCLIST, null);
private static final String JAR_PATH_BEGIN = "/";
private static final String JAR_PATH_END = "!";
private static final char JAR_ENTRY_DELIM = '/';
private static final char CLASS_DELIM = '.';
private static final String ALL_METHODS = ".*";
public static Set<Scope> prepare() throws ScopeParserException,
ManifestInfoException, ExclusionPrepareException {
Set<Scope> exclSet = defaultExcludes();
exclSet.addAll(instrumentationJar());
exclSet.addAll(readExlusionList());
return exclSet;
}
private static Set<Scope> defaultExcludes() throws ScopeParserException {
// if appended to the package name (for scoping purposes),
// excludes all methods in all classes in the package and sub-packages
final String EXCLUDE_CLASSES = ".*.*";
Set<Scope> exclSet = new HashSet<Scope>();
// DiSL dynamic bypass classes
exclSet.add(new ScopeImpl(
"ch.usi.dag.disl.dynamicbypass" + EXCLUDE_CLASSES));
// DiSLRE classes
exclSet.add(new ScopeImpl(
"ch.usi.dag.dislre" + EXCLUDE_CLASSES));
return exclSet;
}
private static Set<Scope> instrumentationJar()
throws ManifestInfoException, ExclusionPrepareException,
ScopeParserException {
try {
// add classes from instrumentation jar
Set<Scope> exclSet = new HashSet<Scope>();
// get DiSL manifest info
ManifestInfo mi = ManifestHelper.getDiSLManifestInfo();
// no manifest found
if(mi == null) {
return exclSet;
}
// get URL of the instrumentation jar manifest
URL manifestURL =
ManifestHelper.getDiSLManifestInfo().getResource();
// manifest path contains "file:" + jar name + "!" + manifest path
String manifestPath = manifestURL.getPath();
// extract jar path
int jarPathBegin = manifestPath.indexOf(JAR_PATH_BEGIN);
int jarPathEnd = manifestPath.indexOf(JAR_PATH_END);
String jarPath = manifestPath.substring(jarPathBegin, jarPathEnd);
// open jar...
JarFile jarFile = new JarFile(jarPath);
// ... and iterate over items
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
// get entry name
String entryName = entry.getName();
// add all classes to the exclusion list
if (entryName.endsWith(Constants.CLASS_EXT)) {
String className =
entryName.replace(JAR_ENTRY_DELIM, CLASS_DELIM);
// remove class ext
int classNameEnd =
className.lastIndexOf(Constants.CLASS_EXT);
className = className.substring(0, classNameEnd);
// add exclusion for all methods
String classExcl = className + ALL_METHODS;
exclSet.add(new ScopeImpl(classExcl));
}
}
jarFile.close();
return exclSet;
} catch(IOException e) {
throw new ExclusionPrepareException(e);
}
}
private static Set<Scope> readExlusionList()
throws ExclusionPrepareException, ScopeParserException {
final String COMMENT_START = "#";
try {
Set<Scope> exclSet = new HashSet<Scope>();
// if exclusion list path exits
if(excListPath != null) {
// read exclusion list line by line
Scanner scanner = new Scanner(new FileInputStream(excListPath));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(! line.startsWith(COMMENT_START)) {
exclSet.add(new ScopeImpl(line));
}
}
scanner.close();
}
return exclSet;
} catch(FileNotFoundException e) {
throw new ExclusionPrepareException(e);
}
}
}
| src/ch/usi/dag/disl/exclusion/ExclusionSet.java | package ch.usi.dag.disl.exclusion;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import ch.usi.dag.disl.cbloader.ManifestHelper;
import ch.usi.dag.disl.cbloader.ManifestHelper.ManifestInfo;
import ch.usi.dag.disl.exception.ExclusionPrepareException;
import ch.usi.dag.disl.exception.ManifestInfoException;
import ch.usi.dag.disl.exception.ScopeParserException;
import ch.usi.dag.disl.scope.Scope;
import ch.usi.dag.disl.scope.ScopeImpl;
import ch.usi.dag.disl.util.Constants;
public abstract class ExclusionSet {
private static final String PROP_EXCLIST = "disl.exclusionList";
private static final String excListPath =
System.getProperty(PROP_EXCLIST, null);
private static final String JAR_PATH_BEGIN = "/";
private static final String JAR_PATH_END = "!";
private static final char JAR_ENTRY_DELIM = '/';
private static final char CLASS_DELIM = '.';
private static final String ALL_METHODS = ".*";
public static Set<Scope> prepare() throws ScopeParserException,
ManifestInfoException, ExclusionPrepareException {
Set<Scope> exclSet = defaultExcludes();
exclSet.addAll(instrumentationJar());
exclSet.addAll(readExlusionList());
return exclSet;
}
private static Set<Scope> defaultExcludes() throws ScopeParserException {
// if appended to the package name (for scoping purposes),
// excludes all methods in all classes in the package and sub-packages
final String EXCLUDE_CLASSES = ".*.*";
Set<Scope> exclSet = new HashSet<Scope>();
// DiSL classes
exclSet.add(new ScopeImpl(
"ch.usi.dag.disl" + EXCLUDE_CLASSES));
// DiSLRE classes
exclSet.add(new ScopeImpl(
"ch.usi.dag.dislre" + EXCLUDE_CLASSES));
return exclSet;
}
private static Set<Scope> instrumentationJar()
throws ManifestInfoException, ExclusionPrepareException,
ScopeParserException {
try {
// add classes from instrumentation jar
Set<Scope> exclSet = new HashSet<Scope>();
// get DiSL manifest info
ManifestInfo mi = ManifestHelper.getDiSLManifestInfo();
// no manifest found
if(mi == null) {
return exclSet;
}
// get URL of the instrumentation jar manifest
URL manifestURL =
ManifestHelper.getDiSLManifestInfo().getResource();
// manifest path contains "file:" + jar name + "!" + manifest path
String manifestPath = manifestURL.getPath();
// extract jar path
int jarPathBegin = manifestPath.indexOf(JAR_PATH_BEGIN);
int jarPathEnd = manifestPath.indexOf(JAR_PATH_END);
String jarPath = manifestPath.substring(jarPathBegin, jarPathEnd);
// open jar...
JarFile jarFile = new JarFile(jarPath);
// ... and iterate over items
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
// get entry name
String entryName = entry.getName();
// add all classes to the exclusion list
if (entryName.endsWith(Constants.CLASS_EXT)) {
String className =
entryName.replace(JAR_ENTRY_DELIM, CLASS_DELIM);
// remove class ext
int classNameEnd =
className.lastIndexOf(Constants.CLASS_EXT);
className = className.substring(0, classNameEnd);
// add exclusion for all methods
String classExcl = className + ALL_METHODS;
exclSet.add(new ScopeImpl(classExcl));
}
}
jarFile.close();
return exclSet;
} catch(IOException e) {
throw new ExclusionPrepareException(e);
}
}
private static Set<Scope> readExlusionList()
throws ExclusionPrepareException, ScopeParserException {
final String COMMENT_START = "#";
try {
Set<Scope> exclSet = new HashSet<Scope>();
// if exclusion list path exits
if(excListPath != null) {
// read exclusion list line by line
Scanner scanner = new Scanner(new FileInputStream(excListPath));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(! line.startsWith(COMMENT_START)) {
exclSet.add(new ScopeImpl(line));
}
}
scanner.close();
}
return exclSet;
} catch(FileNotFoundException e) {
throw new ExclusionPrepareException(e);
}
}
}
| fix for the exclusion of previous commit
git-svn-id: e5fd2e8d8a92bf80e4af81ae0fce2bac2f68298c@707 f1b219a8-1381-427d-9730-7f2851dc2a88
| src/ch/usi/dag/disl/exclusion/ExclusionSet.java | fix for the exclusion of previous commit | <ide><path>rc/ch/usi/dag/disl/exclusion/ExclusionSet.java
<ide>
<ide> Set<Scope> exclSet = new HashSet<Scope>();
<ide>
<del> // DiSL classes
<add> // DiSL dynamic bypass classes
<ide> exclSet.add(new ScopeImpl(
<del> "ch.usi.dag.disl" + EXCLUDE_CLASSES));
<add> "ch.usi.dag.disl.dynamicbypass" + EXCLUDE_CLASSES));
<ide>
<ide> // DiSLRE classes
<ide> exclSet.add(new ScopeImpl( |
|
Java | apache-2.0 | 84ea8bb9ff46cff05d7f0ce3b874f341289c73e2 | 0 | hbs/warp10-platform,hbs/warp10-platform,hbs/warp10-platform,hbs/warp10-platform | //
// Copyright 2018 SenX S.A.S.
//
// 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.warp10.continuum.ingress;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.regex.Matcher;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.warp10.ThrowableUtils;
import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;
import org.apache.hadoop.util.ShutdownHookManager;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TCompactProtocol;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.sort.SortConfig;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import io.warp10.SSLUtils;
import io.warp10.WarpConfig;
import io.warp10.WarpManager;
import io.warp10.continuum.Configuration;
import io.warp10.continuum.JettyUtil;
import io.warp10.continuum.KafkaProducerPool;
import io.warp10.continuum.KafkaSynchronizedConsumerPool;
import io.warp10.continuum.KafkaSynchronizedConsumerPool.ConsumerFactory;
import io.warp10.continuum.MetadataUtils;
import io.warp10.continuum.TextFileShuffler;
import io.warp10.continuum.ThrottlingManager;
import io.warp10.continuum.TimeSource;
import io.warp10.continuum.Tokens;
import io.warp10.continuum.WarpException;
import io.warp10.continuum.egress.CORSHandler;
import io.warp10.continuum.egress.EgressFetchHandler;
import io.warp10.continuum.egress.ThriftDirectoryClient;
import io.warp10.continuum.gts.GTSEncoder;
import io.warp10.continuum.gts.GTSHelper;
import io.warp10.continuum.sensision.SensisionConstants;
import io.warp10.continuum.store.Constants;
import io.warp10.continuum.store.DirectoryClient;
import io.warp10.continuum.store.MetadataIterator;
import io.warp10.continuum.store.thrift.data.DirectoryRequest;
import io.warp10.continuum.store.thrift.data.KafkaDataMessage;
import io.warp10.continuum.store.thrift.data.KafkaDataMessageType;
import io.warp10.continuum.store.thrift.data.Metadata;
import io.warp10.crypto.CryptoUtils;
import io.warp10.crypto.KeyStore;
import io.warp10.crypto.OrderPreservingBase64;
import io.warp10.crypto.SipHashInline;
import io.warp10.quasar.token.thrift.data.WriteToken;
import io.warp10.script.WarpScriptException;
import io.warp10.sensision.Sensision;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
// FIXME(hbs): handle archive
/**
* This is the class which ingests metrics.
*/
public class Ingress extends AbstractHandler implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Ingress.class);
private static final Long NO_LAST_ACTIVITY = Long.MIN_VALUE;
/**
* Set of required parameters, those MUST be set
*/
private static final String[] REQUIRED_PROPERTIES = new String[] {
Configuration.INGRESS_HOST,
Configuration.INGRESS_PORT,
Configuration.INGRESS_ACCEPTORS,
Configuration.INGRESS_SELECTORS,
Configuration.INGRESS_IDLE_TIMEOUT,
Configuration.INGRESS_JETTY_THREADPOOL,
Configuration.INGRESS_ZK_QUORUM,
Configuration.INGRESS_KAFKA_META_BROKERLIST,
Configuration.INGRESS_KAFKA_META_TOPIC,
Configuration.INGRESS_KAFKA_DATA_BROKERLIST,
Configuration.INGRESS_KAFKA_DATA_TOPIC,
Configuration.INGRESS_KAFKA_DATA_POOLSIZE,
Configuration.INGRESS_KAFKA_METADATA_POOLSIZE,
Configuration.INGRESS_KAFKA_DATA_MAXSIZE,
Configuration.INGRESS_KAFKA_METADATA_MAXSIZE,
Configuration.INGRESS_VALUE_MAXSIZE,
Configuration.INGRESS_DELETE_SHUFFLE,
Configuration.DIRECTORY_PSK,
};
private final String metaTopic;
private final String dataTopic;
private final DirectoryClient directoryClient;
final long maxValueSize;
final long ttl;
final boolean useDatapointTs;
private final String cacheDumpPath;
private DateTimeFormatter fmt = ISODateTimeFormat.dateTimeParser();
/**
* List of pending Kafka messages containing metadata (one per Thread)
*/
private final ThreadLocal<List<KeyedMessage<byte[], byte[]>>> metadataMessages = new ThreadLocal<List<KeyedMessage<byte[], byte[]>>>() {
protected java.util.List<kafka.producer.KeyedMessage<byte[],byte[]>> initialValue() {
return new ArrayList<KeyedMessage<byte[], byte[]>>();
};
};
/**
* Byte size of metadataMessages
*/
private ThreadLocal<AtomicLong> metadataMessagesSize = new ThreadLocal<AtomicLong>() {
protected AtomicLong initialValue() {
return new AtomicLong();
};
};
/**
* Size threshold after which we flush metadataMessages into Kafka
*/
private final long METADATA_MESSAGES_THRESHOLD;
/**
* List of pending Kafka messages containing data
*/
private final ThreadLocal<List<KeyedMessage<byte[], byte[]>>> dataMessages = new ThreadLocal<List<KeyedMessage<byte[], byte[]>>>() {
protected java.util.List<kafka.producer.KeyedMessage<byte[],byte[]>> initialValue() {
return new ArrayList<KeyedMessage<byte[], byte[]>>();
};
};
/**
* Byte size of dataMessages
*/
private ThreadLocal<AtomicLong> dataMessagesSize = new ThreadLocal<AtomicLong>() {
protected AtomicLong initialValue() {
return new AtomicLong();
};
};
/**
* Size threshold after which we flush dataMessages into Kafka
*
* This and METADATA_MESSAGES_THRESHOLD has to be lower than the configured Kafka max message size (message.max.bytes)
*/
final long DATA_MESSAGES_THRESHOLD;
/**
* Kafka producer for readings
*/
//private final Producer<byte[], byte[]> dataProducer;
/**
* Pool of producers for the 'data' topic
*/
private final Producer<byte[], byte[]>[] dataProducers;
private int dataProducersCurrentPoolSize = 0;
/**
* Pool of producers for the 'metadata' topic
*/
private final KafkaProducerPool metaProducerPool;
/**
* Number of classId/labelsId to remember (to avoid pushing their metadata to Kafka)
* Memory footprint is that of a BigInteger whose byte representation is 16 bytes, so probably
* around 40 bytes
* FIXME(hbs): need to compute exactly
*/
private int METADATA_CACHE_SIZE = 10000000;
/**
* Cache used to determine if we should push metadata into Kafka or if it was previously seen.
* Key is a BigInteger constructed from a byte array of classId+labelsId (we cannot use byte[] as map key)
*/
final Map<BigInteger, Long> metadataCache = new LinkedHashMap<BigInteger, Long>(100, 0.75F, true) {
@Override
protected boolean removeEldestEntry(java.util.Map.Entry<BigInteger, Long> eldest) {
return this.size() > METADATA_CACHE_SIZE;
}
};
final KeyStore keystore;
final Properties properties;
final long[] classKey;
final long[] labelsKey;
final byte[] AES_KAFKA_META;
final long[] SIPHASH_KAFKA_META;
private final byte[] aesDataKey;
private final long[] siphashDataKey;
private final boolean sendMetadataOnDelete;
private final boolean sendMetadataOnStore;
private final KafkaSynchronizedConsumerPool pool;
private final boolean doShuffle;
/**
* Flag indicating whether or not we reject delete requests
*/
private final boolean rejectDelete;
final boolean activityTracking;
final boolean updateActivity;
private final boolean metaActivity;
final long activityWindow;
public final boolean parseAttributes;
final Long maxpastDefault;
final Long maxfutureDefault;
final Long maxpastOverride;
final Long maxfutureOverride;
final boolean ignoreOutOfRange;
public Ingress(KeyStore keystore, Properties props) {
//
// Enable the ThrottlingManager
//
ThrottlingManager.enable();
this.keystore = keystore;
this.properties = props;
//
// Make sure all required configuration is present
//
for (String required: REQUIRED_PROPERTIES) {
Preconditions.checkNotNull(props.getProperty(required), "Missing configuration parameter '%s'.", required);
}
//
// Extract parameters from 'props'
//
this.ttl = Long.parseLong(props.getProperty(Configuration.INGRESS_HBASE_CELLTTL, "-1"));
this.useDatapointTs = "true".equals(props.getProperty(Configuration.INGRESS_HBASE_DPTS));
this.doShuffle = "true".equals(props.getProperty(Configuration.INGRESS_DELETE_SHUFFLE));
this.rejectDelete = "true".equals(props.getProperty(Configuration.INGRESS_DELETE_REJECT));
this.activityWindow = Long.parseLong(properties.getProperty(Configuration.INGRESS_ACTIVITY_WINDOW, "0"));
this.activityTracking = this.activityWindow > 0;
this.updateActivity = "true".equals(props.getProperty(Configuration.INGRESS_ACTIVITY_UPDATE));
this.metaActivity = "true".equals(props.getProperty(Configuration.INGRESS_ACTIVITY_META));
if (props.containsKey(Configuration.INGRESS_CACHE_DUMP_PATH)) {
this.cacheDumpPath = props.getProperty(Configuration.INGRESS_CACHE_DUMP_PATH);
} else {
this.cacheDumpPath = null;
}
if (null != props.getProperty(Configuration.INGRESS_METADATA_CACHE_SIZE)) {
this.METADATA_CACHE_SIZE = Integer.valueOf(props.getProperty(Configuration.INGRESS_METADATA_CACHE_SIZE));
}
this.metaTopic = props.getProperty(Configuration.INGRESS_KAFKA_META_TOPIC);
this.dataTopic = props.getProperty(Configuration.INGRESS_KAFKA_DATA_TOPIC);
this.DATA_MESSAGES_THRESHOLD = Long.parseLong(props.getProperty(Configuration.INGRESS_KAFKA_DATA_MAXSIZE));
this.METADATA_MESSAGES_THRESHOLD = Long.parseLong(props.getProperty(Configuration.INGRESS_KAFKA_METADATA_MAXSIZE));
this.maxValueSize = Long.parseLong(props.getProperty(Configuration.INGRESS_VALUE_MAXSIZE));
if (this.maxValueSize > (this.DATA_MESSAGES_THRESHOLD / 2) - 64) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_VALUE_MAXSIZE + "' cannot exceed that half of '" + Configuration.INGRESS_KAFKA_DATA_MAXSIZE + "' minus 64.");
}
extractKeys(this.keystore, props);
this.classKey = SipHashInline.getKey(this.keystore.getKey(KeyStore.SIPHASH_CLASS));
this.labelsKey = SipHashInline.getKey(this.keystore.getKey(KeyStore.SIPHASH_LABELS));
this.AES_KAFKA_META = this.keystore.getKey(KeyStore.AES_KAFKA_METADATA);
this.SIPHASH_KAFKA_META = SipHashInline.getKey(this.keystore.getKey(KeyStore.SIPHASH_KAFKA_METADATA));
this.aesDataKey = this.keystore.getKey(KeyStore.AES_KAFKA_DATA);
this.siphashDataKey = SipHashInline.getKey(this.keystore.getKey(KeyStore.SIPHASH_KAFKA_DATA));
this.sendMetadataOnDelete = Boolean.parseBoolean(props.getProperty(Configuration.INGRESS_DELETE_METADATA_INCLUDE, "false"));
this.sendMetadataOnStore = Boolean.parseBoolean(props.getProperty(Configuration.INGRESS_STORE_METADATA_INCLUDE, "false"));
this.parseAttributes = "true".equals(props.getProperty(Configuration.INGRESS_PARSE_ATTRIBUTES));
if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_DEFAULT)) {
maxpastDefault = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_DEFAULT));
if (maxpastDefault < 0) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXPAST_DEFAULT + "' MUST be positive.");
}
} else {
maxpastDefault = null;
}
if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_DEFAULT)) {
maxfutureDefault = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_DEFAULT));
if (maxfutureDefault < 0) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXFUTURE_DEFAULT + "' MUST be positive.");
}
} else {
maxfutureDefault = null;
}
if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_OVERRIDE)) {
maxpastOverride = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_OVERRIDE));
if (maxpastOverride < 0) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXPAST_OVERRIDE + "' MUST be positive.");
}
} else {
maxpastOverride = null;
}
if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_OVERRIDE)) {
maxfutureOverride = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_OVERRIDE));
if (maxfutureOverride < 0) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXFUTURE_OVERRIDE + "' MUST be positive.");
}
} else {
maxfutureOverride = null;
}
this.ignoreOutOfRange = "true".equals(WarpConfig.getProperty(Configuration.INGRESS_OUTOFRANGE_IGNORE));
//
// Prepare meta, data and delete producers
//
Properties metaProps = new Properties();
// @see http://kafka.apache.org/documentation.html#producerconfigs
metaProps.setProperty("metadata.broker.list", props.getProperty(Configuration.INGRESS_KAFKA_META_BROKERLIST));
if (null != props.getProperty(Configuration.INGRESS_KAFKA_META_PRODUCER_CLIENTID)) {
metaProps.setProperty("client.id", props.getProperty(Configuration.INGRESS_KAFKA_META_PRODUCER_CLIENTID));
}
metaProps.setProperty("request.required.acks", "-1");
// TODO(hbs): when we move to the new KafkaProducer API
//metaProps.setProperty(org.apache.kafka.clients.producer.ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1");
metaProps.setProperty("producer.type","sync");
metaProps.setProperty("serializer.class", "kafka.serializer.DefaultEncoder");
metaProps.setProperty("partitioner.class", io.warp10.continuum.KafkaPartitioner.class.getName());
//??? metaProps.setProperty("block.on.buffer.full", "true");
// FIXME(hbs): compression does not work
//metaProps.setProperty("compression.codec", "snappy");
//metaProps.setProperty("client.id","");
ProducerConfig metaConfig = new ProducerConfig(metaProps);
this.metaProducerPool = new KafkaProducerPool(metaConfig,
Integer.parseInt(props.getProperty(Configuration.INGRESS_KAFKA_METADATA_POOLSIZE)),
SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_METADATA_PRODUCER_POOL_GET,
SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_METADATA_PRODUCER_WAIT_NANO);
Properties dataProps = new Properties();
// @see http://kafka.apache.org/documentation.html#producerconfigs
dataProps.setProperty("metadata.broker.list", props.getProperty(Configuration.INGRESS_KAFKA_DATA_BROKERLIST));
if (null != props.getProperty(Configuration.INGRESS_KAFKA_DATA_PRODUCER_CLIENTID)) {
dataProps.setProperty("client.id", props.getProperty(Configuration.INGRESS_KAFKA_DATA_PRODUCER_CLIENTID));
}
dataProps.setProperty("request.required.acks", "-1");
dataProps.setProperty("producer.type","sync");
dataProps.setProperty("serializer.class", "kafka.serializer.DefaultEncoder");
dataProps.setProperty("partitioner.class", io.warp10.continuum.KafkaPartitioner.class.getName());
// TODO(hbs): when we move to the new KafkaProducer API
//dataProps.setProperty(org.apache.kafka.clients.producer.ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1");
if (null != props.getProperty(Configuration.INGRESS_KAFKA_DATA_REQUEST_TIMEOUT_MS)) {
dataProps.setProperty("request.timeout.ms", props.getProperty(Configuration.INGRESS_KAFKA_DATA_REQUEST_TIMEOUT_MS));
}
///???? dataProps.setProperty("block.on.buffer.full", "true");
// FIXME(hbs): compression does not work
//dataProps.setProperty("compression.codec", "snappy");
//dataProps.setProperty("client.id","");
ProducerConfig dataConfig = new ProducerConfig(dataProps);
//this.dataProducer = new Producer<byte[], byte[]>(dataConfig);
//
// Allocate producer pool
//
this.dataProducers = new Producer[Integer.parseInt(props.getProperty(Configuration.INGRESS_KAFKA_DATA_POOLSIZE))];
for (int i = 0; i < dataProducers.length; i++) {
this.dataProducers[i] = new Producer<byte[], byte[]>(dataConfig);
}
this.dataProducersCurrentPoolSize = this.dataProducers.length;
//
// Producer for the Delete topic
//
/*
Properties deleteProps = new Properties();
// @see http://kafka.apache.org/documentation.html#producerconfigs
deleteProps.setProperty("metadata.broker.list", props.getProperty(INGRESS_KAFKA_DELETE_BROKERLIST));
deleteProps.setProperty("request.required.acks", "-1");
deleteProps.setProperty("producer.type","sync");
deleteProps.setProperty("serializer.class", "kafka.serializer.DefaultEncoder");
deleteProps.setProperty("partitioner.class", io.warp10.continuum.KafkaPartitioner.class.getName());
ProducerConfig deleteConfig = new ProducerConfig(deleteProps);
this.deleteProducer = new Producer<byte[], byte[]>(deleteConfig);
*/
//
// Attempt to load the cache file (we do that prior to starting the Kafka consumer)
//
loadCache();
//
// Create Kafka consumer to handle Metadata deletions
//
ConsumerFactory metadataConsumerFactory = new IngressMetadataConsumerFactory(this);
if (props.containsKey(Configuration.INGRESS_KAFKA_META_GROUPID)) {
pool = new KafkaSynchronizedConsumerPool(props.getProperty(Configuration.INGRESS_KAFKA_META_ZKCONNECT),
props.getProperty(Configuration.INGRESS_KAFKA_META_TOPIC),
props.getProperty(Configuration.INGRESS_KAFKA_META_CONSUMER_CLIENTID),
props.getProperty(Configuration.INGRESS_KAFKA_META_GROUPID),
props.getProperty(Configuration.INGRESS_KAFKA_META_CONSUMER_PARTITION_ASSIGNMENT_STRATEGY),
props.getProperty(Configuration.INGRESS_KAFKA_META_CONSUMER_AUTO_OFFSET_RESET),
Integer.parseInt(props.getProperty(Configuration.INGRESS_KAFKA_META_NTHREADS)),
Long.parseLong(props.getProperty(Configuration.INGRESS_KAFKA_META_COMMITPERIOD)),
metadataConsumerFactory);
} else {
pool = null;
}
//
// Initialize ThriftDirectoryService
//
try {
this.directoryClient = new ThriftDirectoryClient(this.keystore, props);
} catch (Exception e) {
throw new RuntimeException(e);
}
//
// Register shutdown hook
//
final Ingress self = this;
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
//
// Make sure the Kakfa consumers are stopped so we don't miss deletions
// when restarting and using the cache we are about to store
//
if (null != self.pool) {
self.pool.shutdown();
LOG.info("Waiting for Ingress Kafka consumers to stop.");
while(!self.pool.isStopped()) {
LockSupport.parkNanos(250000000L);
}
LOG.info("Kafka consumers stopped, dumping GTS cache");
}
self.dumpCache();
}
});
//
// Make sure ShutdownHookManager is initialized, otherwise it will try to
// register a shutdown hook during the shutdown hook we just registered...
//
ShutdownHookManager.get();
//
// Start Jetty server
//
int maxThreads = Integer.parseInt(props.getProperty(Configuration.INGRESS_JETTY_THREADPOOL));
boolean enableStreamUpdate = !("true".equals(props.getProperty(Configuration.WARP_STREAMUPDATE_DISABLE)));
BlockingArrayQueue<Runnable> queue = null;
if (props.containsKey(Configuration.INGRESS_JETTY_MAXQUEUESIZE)) {
int queuesize = Integer.parseInt(props.getProperty(Configuration.INGRESS_JETTY_MAXQUEUESIZE));
queue = new BlockingArrayQueue<Runnable>(queuesize);
}
Server server = new Server(new QueuedThreadPool(maxThreads,8, 60000, queue));
List<Connector> connectors = new ArrayList<Connector>();
boolean useHttp = null != props.getProperty(Configuration.INGRESS_PORT);
boolean useHttps = null != props.getProperty(Configuration.INGRESS_PREFIX + Configuration._SSL_PORT);
if (useHttp) {
int port = Integer.valueOf(props.getProperty(Configuration.INGRESS_PORT));
String host = props.getProperty(Configuration.INGRESS_HOST);
int acceptors = Integer.valueOf(props.getProperty(Configuration.INGRESS_ACCEPTORS));
int selectors = Integer.valueOf(props.getProperty(Configuration.INGRESS_SELECTORS));
long idleTimeout = Long.parseLong(props.getProperty(Configuration.INGRESS_IDLE_TIMEOUT));
ServerConnector connector = new ServerConnector(server, acceptors, selectors);
connector.setIdleTimeout(idleTimeout);
connector.setPort(port);
connector.setHost(host);
connector.setName("Continuum Ingress HTTP");
connectors.add(connector);
}
if (useHttps) {
ServerConnector connector = SSLUtils.getConnector(server, Configuration.INGRESS_PREFIX);
connector.setName("Continuum Ingress HTTPS");
connectors.add(connector);
}
server.setConnectors(connectors.toArray(new Connector[connectors.size()]));
HandlerList handlers = new HandlerList();
Handler cors = new CORSHandler();
handlers.addHandler(cors);
handlers.addHandler(this);
if (enableStreamUpdate) {
IngressStreamUpdateHandler suHandler = new IngressStreamUpdateHandler(this);
handlers.addHandler(suHandler);
}
server.setHandler(handlers);
JettyUtil.setSendServerVersion(server, false);
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
Thread t = new Thread(this);
t.setDaemon(true);
t.setName("Continuum Ingress");
t.start();
}
@Override
public void run() {
//
// Register in ZK and watch parent znode.
// If the Ingress count exceeds the licensed number,
// exit if we are the first of the list.
//
while(true) {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException ie) {
}
}
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String token = null;
if (target.equals(Constants.API_ENDPOINT_UPDATE)) {
baseRequest.setHandled(true);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_REQUESTS, Sensision.EMPTY_LABELS, 1);
} else if (target.startsWith(Constants.API_ENDPOINT_UPDATE + "/")) {
baseRequest.setHandled(true);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_REQUESTS, Sensision.EMPTY_LABELS, 1);
token = target.substring(Constants.API_ENDPOINT_UPDATE.length() + 1);
} else if (target.equals(Constants.API_ENDPOINT_META)) {
handleMeta(target, baseRequest, request, response);
return;
} else if (target.equals(Constants.API_ENDPOINT_DELETE)) {
handleDelete(target, baseRequest, request, response);
} else if (Constants.API_ENDPOINT_CHECK.equals(target)) {
baseRequest.setHandled(true);
response.setStatus(HttpServletResponse.SC_OK);
return;
} else {
return;
}
if (null != WarpManager.getAttribute(WarpManager.UPDATE_DISABLED)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, String.valueOf(WarpManager.getAttribute(WarpManager.UPDATE_DISABLED)));
return;
}
long nowms = System.currentTimeMillis();
try {
//
// CORS header
//
response.setHeader("Access-Control-Allow-Origin", "*");
long nano = System.nanoTime();
//
// TODO(hbs): Extract producer/owner from token
//
if (null == token) {
token = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));
}
WriteToken writeToken;
try {
writeToken = Tokens.extractWriteToken(token);
if (writeToken.getAttributesSize() > 0 && writeToken.getAttributes().containsKey(Constants.TOKEN_ATTR_NOUPDATE)) {
throw new WarpScriptException("Token cannot be used for updating data.");
}
} catch (WarpScriptException ee) {
throw new IOException(ee);
}
String application = writeToken.getAppName();
String producer = Tokens.getUUID(writeToken.getProducerId());
String owner = Tokens.getUUID(writeToken.getOwnerId());
Map<String,String> sensisionLabels = new HashMap<String,String>();
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);
long count = 0;
//
// Extract KafkaDataMessage attributes
//
Map<String,String> kafkaDataMessageAttributes = null;
if (-1 != ttl || useDatapointTs) {
kafkaDataMessageAttributes = new HashMap<String,String>();
if (-1 != ttl) {
kafkaDataMessageAttributes.put(Constants.STORE_ATTR_TTL, Long.toString(ttl));
}
if (useDatapointTs) {
kafkaDataMessageAttributes.put(Constants.STORE_ATTR_USEDATAPOINTTS, "t");
}
}
if (writeToken.getAttributesSize() > 0) {
if (writeToken.getAttributes().containsKey(Constants.STORE_ATTR_TTL)
|| writeToken.getAttributes().containsKey(Constants.STORE_ATTR_USEDATAPOINTTS)) {
if (null == kafkaDataMessageAttributes) {
kafkaDataMessageAttributes = new HashMap<String,String>();
}
if (writeToken.getAttributes().containsKey(Constants.STORE_ATTR_TTL)) {
kafkaDataMessageAttributes.put(Constants.STORE_ATTR_TTL, writeToken.getAttributes().get(Constants.STORE_ATTR_TTL));
}
if (writeToken.getAttributes().containsKey(Constants.STORE_ATTR_USEDATAPOINTTS)) {
kafkaDataMessageAttributes.put(Constants.STORE_ATTR_USEDATAPOINTTS, writeToken.getAttributes().get(Constants.STORE_ATTR_USEDATAPOINTTS));
}
}
}
try {
if (null == producer || null == owner) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_INVALIDTOKEN, Sensision.EMPTY_LABELS, 1);
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
return;
}
//
// Build extra labels
//
Map<String,String> extraLabels = new HashMap<String,String>();
// Add labels from the WriteToken if they exist
if (writeToken.getLabelsSize() > 0) {
extraLabels.putAll(writeToken.getLabels());
}
// Force internal labels
extraLabels.put(Constants.PRODUCER_LABEL, producer);
extraLabels.put(Constants.OWNER_LABEL, owner);
// FIXME(hbs): remove me
if (null != application) {
extraLabels.put(Constants.APPLICATION_LABEL, application);
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
}
long maxsize = maxValueSize;
if (writeToken.getAttributesSize() > 0 && null != writeToken.getAttributes().get(Constants.TOKEN_ATTR_MAXSIZE)) {
maxsize = Long.parseLong(writeToken.getAttributes().get(Constants.TOKEN_ATTR_MAXSIZE));
if (maxsize > (DATA_MESSAGES_THRESHOLD / 2) - 64) {
maxsize = (DATA_MESSAGES_THRESHOLD / 2) - 64;
}
}
//
// Determine if content is gzipped
//
boolean gzipped = false;
if (null != request.getHeader("Content-Type") && "application/gzip".equals(request.getHeader("Content-Type"))) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_GZIPPED, sensisionLabels, 1);
gzipped = true;
}
BufferedReader br = null;
if (gzipped) {
GZIPInputStream is = new GZIPInputStream(request.getInputStream());
br = new BufferedReader(new InputStreamReader(is));
} else {
br = request.getReader();
}
Long now = TimeSource.getTime();
//
// Extract time limits
//
Long maxpast = null;
if (null != maxpastDefault) {
try {
maxpast = Math.subtractExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, maxpastDefault));
} catch (ArithmeticException ae) {
maxpast = null;
}
}
Long maxfuture = null;
if (null != maxfutureDefault) {
try {
maxfuture = Math.addExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, maxfutureDefault));
} catch (ArithmeticException ae) {
maxfuture = null;
}
}
Boolean ignoor = null;
if (writeToken.getAttributesSize() > 0) {
if (writeToken.getAttributes().containsKey(Constants.TOKEN_ATTR_IGNOOR)) {
String v = writeToken.getAttributes().get(Constants.TOKEN_ATTR_IGNOOR).toLowerCase();
if ("true".equals(v) || "t".equals(v)) {
ignoor = Boolean.TRUE;
} else if ("false".equals(v) || "f".equals(v)) {
ignoor = Boolean.FALSE;
}
}
String deltastr = writeToken.getAttributes().get(Constants.TOKEN_ATTR_MAXPAST);
if (null != deltastr) {
long delta = Long.parseLong(deltastr);
if (delta < 0) {
throw new WarpScriptException("Invalid '" + Constants.TOKEN_ATTR_MAXPAST + "' token attribute, MUST be positive.");
}
try {
maxpast = Math.subtractExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, delta));
} catch (ArithmeticException ae) {
maxpast = null;
}
}
deltastr = writeToken.getAttributes().get(Constants.TOKEN_ATTR_MAXFUTURE);
if (null != deltastr) {
long delta = Long.parseLong(deltastr);
if (delta < 0) {
throw new WarpScriptException("Invalid '" + Constants.TOKEN_ATTR_MAXFUTURE + "' token attribute, MUST be positive.");
}
try {
maxfuture = Math.addExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, delta));
} catch (ArithmeticException ae) {
maxfuture = null;
}
}
}
if (null != maxpastOverride) {
try {
maxpast = Math.subtractExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, maxpastOverride));
} catch (ArithmeticException ae) {
maxpast = null;
}
}
if (null != maxfutureOverride) {
try {
maxfuture = Math.addExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, maxfutureOverride));
} catch (ArithmeticException ae) {
maxfuture = null;
}
}
//
// Check the value of the 'now' header
//
// The following values are supported:
//
// A number, which will be interpreted as an absolute time reference,
// i.e. a number of time units since the Epoch.
//
// A number prefixed by '+' or '-' which will be interpreted as a
// delta from the present time.
//
// A '*' which will mean to not set 'now', and to recompute its value
// each time it's needed.
//
String nowstr = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_NOW_HEADERX));
if (null != nowstr) {
if ("*".equals(nowstr)) {
now = null;
} else if (nowstr.startsWith("+")) {
try {
long delta = Long.parseLong(nowstr.substring(1));
now = now + delta;
} catch (Exception e) {
throw new IOException("Invalid base timestamp.");
}
} else if (nowstr.startsWith("-")) {
try {
long delta = Long.parseLong(nowstr.substring(1));
now = now - delta;
} catch (Exception e) {
throw new IOException("Invalid base timestamp.");
}
} else {
try {
now = Long.parseLong(nowstr);
} catch (Exception e) {
throw new IOException("Invalid base timestamp.");
}
}
}
//
// Loop on all lines
//
GTSEncoder lastencoder = null;
GTSEncoder encoder = null;
byte[] bytes = new byte[16];
int idx = 0;
AtomicLong dms = this.dataMessagesSize.get();
// Atomic boolean to track if attributes were parsed
AtomicBoolean hadAttributes = parseAttributes ? new AtomicBoolean(false) : null;
boolean lastHadAttributes = false;
AtomicLong ignoredCount = null;
if ((this.ignoreOutOfRange && !Boolean.FALSE.equals(ignoor)) || Boolean.TRUE.equals(ignoor)) {
ignoredCount = new AtomicLong(0L);
}
do {
// We copy the current value of hadAttributes
if (parseAttributes) {
lastHadAttributes = lastHadAttributes || hadAttributes.get();
hadAttributes.set(false);
}
String line = br.readLine();
if (null == line) {
break;
}
if ("".equals(line)) {
continue;
}
// Skip lines which start with '#'
if ('#' == line.charAt(0)) {
continue;
}
try {
encoder = GTSHelper.parse(lastencoder, line, extraLabels, now, maxsize, hadAttributes, maxpast, maxfuture, ignoredCount);
count++;
} catch (ParseException pe) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_PARSEERRORS, sensisionLabels, 1);
throw new IOException("Parse error at '" + line + "'", pe);
}
if (encoder != lastencoder || dms.get() + 16 + lastencoder.size() > DATA_MESSAGES_THRESHOLD) {
//
// Determine if we should push the metadata or not
//
encoder.setClassId(GTSHelper.classId(this.classKey, encoder.getMetadata().getName()));
encoder.setLabelsId(GTSHelper.labelsId(this.labelsKey, encoder.getMetadata().getLabels()));
GTSHelper.fillGTSIds(bytes, 0, encoder.getClassId(), encoder.getLabelsId());
BigInteger metadataCacheKey = new BigInteger(bytes);
//
// Check throttling
//
if (null != lastencoder && lastencoder.size() > 0) {
ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application, lastencoder.getClassId(), lastencoder.getLabelsId());
ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application, (int) lastencoder.getCount());
}
boolean pushMeta = false;
Long val = this.metadataCache.getOrDefault(metadataCacheKey, NO_LAST_ACTIVITY);
if (NO_LAST_ACTIVITY.equals(val)) {
pushMeta = true;
} else if (activityTracking && updateActivity) {
Long lastActivity = val;
if (null == lastActivity) {
pushMeta = true;
} else if (nowms - lastActivity > activityWindow) {
pushMeta = true;
}
}
if (pushMeta) {
// Build metadata object to push
Metadata metadata = new Metadata();
// Set source to indicate we
metadata.setSource(Configuration.INGRESS_METADATA_SOURCE);
metadata.setName(encoder.getMetadata().getName());
metadata.setLabels(encoder.getMetadata().getLabels());
if (this.activityTracking && updateActivity) {
metadata.setLastActivity(nowms);
}
TSerializer serializer = new TSerializer(new TCompactProtocol.Factory());
try {
pushMetadataMessage(bytes, serializer.serialize(metadata));
// Update metadataCache with the current key
synchronized(metadataCache) {
this.metadataCache.put(metadataCacheKey, (activityTracking && updateActivity) ? nowms : null);
}
} catch (TException te) {
throw new IOException("Unable to push metadata.");
}
}
if (null != lastencoder) {
pushDataMessage(lastencoder, kafkaDataMessageAttributes);
if (parseAttributes && lastHadAttributes) {
// We need to push lastencoder's metadata update as they were updated since the last
// metadata update message sent
Metadata meta = new Metadata(lastencoder.getMetadata());
meta.setSource(Configuration.INGRESS_METADATA_UPDATE_ENDPOINT);
pushMetadataMessage(meta);
// Reset lastHadAttributes
lastHadAttributes = false;
}
}
if (encoder != lastencoder) {
// This is the case when we just parsed either the first input line or one for a different
// GTS than the previous one.
lastencoder = encoder;
} else {
// This is the case when lastencoder and encoder are identical, but lastencoder was too big and needed
// to be flushed
//lastencoder = null;
//
// Allocate a new GTSEncoder and reuse Metadata so we can
// correctly handle a continuation line if this is what occurs next
//
Metadata metadata = lastencoder.getMetadata();
lastencoder = new GTSEncoder(0L);
lastencoder.setMetadata(metadata);
}
}
if (0 == count % 1000) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_DATAPOINTS_RAW, sensisionLabels, count);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_DATAPOINTS_GLOBAL, Sensision.EMPTY_LABELS, count);
count = 0;
}
} while (true);
if (null != lastencoder && lastencoder.size() > 0) {
ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application, lastencoder.getClassId(), lastencoder.getLabelsId());
ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application, (int) lastencoder.getCount());
pushDataMessage(lastencoder, kafkaDataMessageAttributes);
if (parseAttributes && lastHadAttributes) {
// Push a metadata UPDATE message so attributes are stored
// Build metadata object to push
Metadata meta = new Metadata(lastencoder.getMetadata());
meta.setSource(Configuration.INGRESS_METADATA_UPDATE_ENDPOINT);
pushMetadataMessage(meta);
}
}
} catch (WarpException we) {
throw new IOException(we);
} finally {
//
// Flush message buffers into Kafka
//
pushMetadataMessage(null, null);
pushDataMessage(null, kafkaDataMessageAttributes);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_DATAPOINTS_RAW, sensisionLabels, count);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_DATAPOINTS_GLOBAL, Sensision.EMPTY_LABELS, count);
long micros = (System.nanoTime() - nano) / 1000L;
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_TIME_US, sensisionLabels, micros);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_TIME_US_GLOBAL, Sensision.EMPTY_LABELS, micros);
}
} catch (Throwable t) { // Catch everything else this handler could return 200 on a OOM exception
if (!response.isCommitted()) {
String msg = "Error when updating data: " + ThrowableUtils.getErrorMessage(t);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
return;
}
}
response.setStatus(HttpServletResponse.SC_OK);
}
/**
* Handle Metadata updating
*/
public void handleMeta(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (target.equals(Constants.API_ENDPOINT_META)) {
baseRequest.setHandled(true);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_REQUESTS, Sensision.EMPTY_LABELS, 1);
} else {
return;
}
if (null != WarpManager.getAttribute(WarpManager.META_DISABLED)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, String.valueOf(WarpManager.getAttribute(WarpManager.META_DISABLED)));
return;
}
//
// CORS header
//
response.setHeader("Access-Control-Allow-Origin", "*");
//
// Loop over the input lines.
// Each has the following format:
//
// class{labels}{attributes}
//
//
// TODO(hbs): Extract producer/owner from token
//
String token = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));
WriteToken writeToken;
try {
try {
writeToken = Tokens.extractWriteToken(token);
if (writeToken.getAttributesSize() > 0 && writeToken.getAttributes().containsKey(Constants.TOKEN_ATTR_NOMETA)) {
throw new WarpScriptException("Token cannot be used for updating metadata.");
}
} catch (WarpScriptException ee) {
throw new IOException(ee);
}
String application = writeToken.getAppName();
String producer = Tokens.getUUID(writeToken.getProducerId());
String owner = Tokens.getUUID(writeToken.getOwnerId());
if (null == producer || null == owner) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_INVALIDTOKEN, Sensision.EMPTY_LABELS, 1);
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
return;
}
Map<String,String> sensisionLabels = new HashMap<String,String>();
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);
if (null != application) {
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
}
long count = 0;
//
// Determine if content if gzipped
//
boolean gzipped = false;
if (null != request.getHeader("Content-Type") && "application/gzip".equals(request.getHeader("Content-Type"))) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_REQUESTS, Sensision.EMPTY_LABELS, 1);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_GZIPPED, sensisionLabels, 1);
gzipped = true;
}
BufferedReader br = null;
if (gzipped) {
GZIPInputStream is = new GZIPInputStream(request.getInputStream());
br = new BufferedReader(new InputStreamReader(is));
} else {
br = request.getReader();
}
long nowms = System.currentTimeMillis();
//
// Loop on all lines
//
while(true) {
String line = br.readLine();
if (null == line) {
break;
}
//
// Ignore blank lines
//
if ("".equals(line)) {
continue;
}
// Skip lines which start with '#'
if ('#' == line.charAt(0)) {
continue;
}
Metadata metadata = MetadataUtils.parseMetadata(line);
if (null == metadata) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_INVALID, sensisionLabels, 1);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid metadata " + line);
return;
}
// Add labels from the WriteToken if they exist
if (writeToken.getLabelsSize() > 0) {
metadata.getLabels().putAll(writeToken.getLabels());
}
//
// Force owner/producer
//
metadata.getLabels().put(Constants.PRODUCER_LABEL, producer);
metadata.getLabels().put(Constants.OWNER_LABEL, owner);
if (null != application) {
metadata.getLabels().put(Constants.APPLICATION_LABEL, application);
}
if (!MetadataUtils.validateMetadata(metadata)) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_INVALID, sensisionLabels, 1);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid metadata " + line);
return;
}
count++;
metadata.setSource(Configuration.INGRESS_METADATA_UPDATE_ENDPOINT);
try {
// We do not take into consideration this activity timestamp in the cache
// this way we do not allocate BigIntegers
if (activityTracking && metaActivity) {
metadata.setLastActivity(nowms);
}
pushMetadataMessage(metadata);
} catch (Exception e) {
throw new IOException("Unable to push metadata");
}
}
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_RECORDS, sensisionLabels, count);
} catch (Throwable t) { // Catch everything else this handler could return 200 on a OOM exception
if (!response.isCommitted()) {
String msg = "Error when updating meta: " + ThrowableUtils.getErrorMessage(t);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
return;
}
} finally {
//
// Flush message buffers into Kafka
//
pushMetadataMessage(null, null);
}
response.setStatus(HttpServletResponse.SC_OK);
}
public void handleDelete(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (target.equals(Constants.API_ENDPOINT_DELETE)) {
baseRequest.setHandled(true);
} else {
return;
}
if (this.rejectDelete) {
throw new IOException(Constants.API_ENDPOINT_DELETE + " endpoint is not activated.");
}
if (null != WarpManager.getAttribute(WarpManager.DELETE_DISABLED)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, String.valueOf(WarpManager.getAttribute(WarpManager.DELETE_DISABLED)));
return;
}
//
// CORS header
//
response.setHeader("Access-Control-Allow-Origin", "*");
long nano = System.nanoTime();
//
// Extract token infos
//
String token = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));
WriteToken writeToken;
try {
writeToken = Tokens.extractWriteToken(token);
if (writeToken.getAttributesSize() > 0 && writeToken.getAttributes().containsKey(Constants.TOKEN_ATTR_NODELETE)) {
throw new WarpScriptException("Token cannot be used for deletions.");
}
} catch (WarpScriptException ee) {
throw new IOException(ee);
}
String application = writeToken.getAppName();
String producer = Tokens.getUUID(writeToken.getProducerId());
String owner = Tokens.getUUID(writeToken.getOwnerId());
//
// For delete operations, producer and owner MUST be equal
//
if (!producer.equals(owner)) {
throw new IOException("Invalid write token for deletion.");
}
Map<String,String> sensisionLabels = new HashMap<String,String>();
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);
long count = 0;
long gts = 0;
boolean completeDeletion = false;
boolean dryrun = null != request.getParameter(Constants.HTTP_PARAM_DRYRUN);
boolean showErrors = null != request.getParameter(Constants.HTTP_PARAM_SHOW_ERRORS);
PrintWriter pw = null;
try {
if (null == producer || null == owner) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
return;
}
//
// Build extra labels
//
Map<String,String> extraLabels = new HashMap<String,String>();
// Add extra labels, remove producer,owner,app
if (writeToken.getLabelsSize() > 0) {
extraLabels.putAll(writeToken.getLabels());
extraLabels.remove(Constants.PRODUCER_LABEL);
extraLabels.remove(Constants.OWNER_LABEL);
extraLabels.remove(Constants.APPLICATION_LABEL);
}
//
// Only set owner and potentially app, producer may vary
//
extraLabels.put(Constants.OWNER_LABEL, owner);
if (null != application) {
extraLabels.put(Constants.APPLICATION_LABEL, application);
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
}
boolean hasRange = false;
//
// Extract start/end
//
String startstr = request.getParameter(Constants.HTTP_PARAM_START);
String endstr = request.getParameter(Constants.HTTP_PARAM_END);
String minagestr = request.getParameter(Constants.HTTP_PARAM_MINAGE);
long start = Long.MIN_VALUE;
long end = Long.MAX_VALUE;
long minage = 0L;
if (null != minagestr) {
minage = Long.parseLong(minagestr);
if (minage < 0) {
throw new IOException("Invalid value for '" + Constants.HTTP_PARAM_MINAGE + "', expected a number of ms >= 0");
}
}
if (null != startstr) {
if (null == endstr) {
throw new IOException("Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END + " should be defined.");
}
if (startstr.contains("T")) {
if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) {
start = io.warp10.script.unary.TOTIMESTAMP.parseTimestamp(startstr);
} else {
start = fmt.parseDateTime(startstr).getMillis() * Constants.TIME_UNITS_PER_MS;
}
} else {
start = Long.valueOf(startstr);
}
}
if (null != endstr) {
if (null == startstr) {
throw new IOException("Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END + " should be defined.");
}
if (endstr.contains("T")) {
if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) {
end = io.warp10.script.unary.TOTIMESTAMP.parseTimestamp(endstr);
} else {
end = fmt.parseDateTime(endstr).getMillis() * Constants.TIME_UNITS_PER_MS;
}
} else {
end = Long.valueOf(endstr);
}
}
if (Long.MIN_VALUE == start && Long.MAX_VALUE == end && null == request.getParameter(Constants.HTTP_PARAM_DELETEALL)) {
throw new IOException("Parameter " + Constants.HTTP_PARAM_DELETEALL + " should be set when deleting a full range.");
}
if (start > end) {
throw new IOException("Invalid time range specification.");
}
//
// Extract selector
//
String selector = request.getParameter(Constants.HTTP_PARAM_SELECTOR);
//
// Extract the class and labels selectors
// The class selector and label selectors are supposed to have
// values which use percent encoding, i.e. explicit percent encoding which
// might have been re-encoded using percent encoding when passed as parameter
//
//
Matcher m = EgressFetchHandler.SELECTOR_RE.matcher(selector);
if (!m.matches()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
String classSelector = URLDecoder.decode(m.group(1), StandardCharsets.UTF_8.name());
String labelsSelection = m.group(2);
Map<String,String> labelsSelectors;
try {
labelsSelectors = GTSHelper.parseLabelsSelectors(labelsSelection);
} catch (ParseException pe) {
throw new IOException(pe);
}
//
// Force 'owner'/'app' from token
//
labelsSelectors.putAll(extraLabels);
List<Metadata> metadatas = null;
List<String> clsSels = new ArrayList<String>();
List<Map<String,String>> lblsSels = new ArrayList<Map<String,String>>();
clsSels.add(classSelector);
lblsSels.add(labelsSelectors);
response.setStatus(HttpServletResponse.SC_OK);
pw = response.getWriter();
StringBuilder sb = new StringBuilder();
//
// Shuffle only if not in dryrun mode
//
if (!dryrun && doShuffle) {
//
// Loop over the iterators, storing the read metadata to a temporary file encrypted on disk
// Data is encrypted using a onetime pad
//
final byte[] onetimepad = new byte[(int) Math.max(65537, System.currentTimeMillis() % 100000)];
new Random().nextBytes(onetimepad);
final File cache = File.createTempFile(Long.toHexString(System.currentTimeMillis()) + "-" + Long.toHexString(System.nanoTime()), ".delete.dircache");
cache.deleteOnExit();
FileWriter writer = new FileWriter(cache);
TSerializer serializer = new TSerializer(new TCompactProtocol.Factory());
DirectoryRequest drequest = new DirectoryRequest();
drequest.setClassSelectors(clsSels);
drequest.setLabelsSelectors(lblsSels);
try (MetadataIterator iterator = directoryClient.iterator(drequest)) {
while(iterator.hasNext()) {
Metadata metadata = iterator.next();
try {
byte[] bytes = serializer.serialize(metadata);
// Apply onetimepad
// We pad each line separately since we will later shuffle them!
int padidx = 0;
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) (bytes[i] ^ onetimepad[padidx++]);
if (padidx >= onetimepad.length) {
padidx = 0;
}
}
OrderPreservingBase64.encodeToWriter(bytes, writer);
writer.write('\n');
} catch (TException te) {
throw new IOException(te);
}
}
} catch (Exception e) {
try { writer.close(); } catch(IOException ioe) {}
cache.delete();
throw new IOException(e);
}
writer.close();
//
// Shuffle the content of the file
//
final File shuffled = File.createTempFile(Long.toHexString(System.currentTimeMillis()) + "-" + Long.toHexString(System.nanoTime()), ".delete.shuffled");
shuffled.deleteOnExit();
TextFileShuffler shuffler = new TextFileShuffler(new SortConfig().withMaxMemoryUsage(1000000L));
InputStream in = new FileInputStream(cache);
OutputStream out = new FileOutputStream(shuffled);
try {
shuffler.sort(in, out);
} catch (Exception e) {
try { in.close(); } catch (IOException ioe) {}
try { out.close(); } catch (IOException ioe) {}
shuffler.close();
shuffled.delete();
cache.delete();
throw new IOException(e);
}
shuffler.close();
out.close();
in.close();
// Delete the unshuffled file
cache.delete();
//
// Create an iterator based on the shuffled cache
//
final AtomicReference<Throwable> error = new AtomicReference<Throwable>(null);
MetadataIterator shufflediterator = new MetadataIterator() {
BufferedReader reader = new BufferedReader(new FileReader(shuffled));
private Metadata current = null;
private boolean done = false;
private TDeserializer deserializer = new TDeserializer(new TCompactProtocol.Factory());
@Override
public boolean hasNext() {
if (done) {
return false;
}
if (null != current) {
return true;
}
try {
String line = reader.readLine();
if (null == line) {
done = true;
return false;
}
byte[] raw = OrderPreservingBase64.decode(line.getBytes(StandardCharsets.US_ASCII));
// Apply one time pad
int padidx = 0;
for (int i = 0; i < raw.length; i++) {
raw[i] = (byte) (raw[i] ^ onetimepad[padidx++]);
if (padidx >= onetimepad.length) {
padidx = 0;
}
}
Metadata metadata = new Metadata();
try {
deserializer.deserialize(metadata, raw);
this.current = metadata;
return true;
} catch (TException te) {
error.set(te);
LOG.error("", te);
}
} catch (IOException ioe) {
error.set(ioe);
LOG.error("", ioe);
}
return false;
}
@Override
public Metadata next() {
if (null != this.current) {
Metadata metadata = this.current;
this.current = null;
return metadata;
} else {
throw new NoSuchElementException();
}
}
@Override
public void close() throws Exception {
this.reader.close();
shuffled.delete();
}
};
try {
while(shufflediterator.hasNext()) {
Metadata metadata = shufflediterator.next();
if (!dryrun) {
pushDeleteMessage(start, end, minage, metadata);
if (Long.MAX_VALUE == end && Long.MIN_VALUE == start && 0 == minage) {
completeDeletion = true;
// We must also push the metadata deletion and remove the metadata from the cache
Metadata meta = new Metadata(metadata);
meta.setSource(Configuration.INGRESS_METADATA_DELETE_SOURCE);
pushMetadataMessage(meta);
byte[] bytes = new byte[16];
// We know class/labels Id were computed in pushMetadataMessage
GTSHelper.fillGTSIds(bytes, 0, meta.getClassId(), meta.getLabelsId());
BigInteger key = new BigInteger(bytes);
synchronized(this.metadataCache) {
this.metadataCache.remove(key);
}
}
}
sb.setLength(0);
GTSHelper.metadataToString(sb, metadata.getName(), metadata.getLabels());
if (metadata.getAttributesSize() > 0) {
GTSHelper.labelsToString(sb, metadata.getAttributes());
} else {
sb.append("{}");
}
pw.write(sb.toString());
pw.write("\r\n");
gts++;
}
if (null != error.get()) {
throw error.get();
}
} finally {
try { shufflediterator.close(); } catch (Exception e) {}
}
} else {
DirectoryRequest drequest = new DirectoryRequest();
drequest.setClassSelectors(clsSels);
drequest.setLabelsSelectors(lblsSels);
try (MetadataIterator iterator = directoryClient.iterator(drequest)) {
while(iterator.hasNext()) {
Metadata metadata = iterator.next();
if (!dryrun) {
pushDeleteMessage(start, end, minage, metadata);
if (Long.MAX_VALUE == end && Long.MIN_VALUE == start && 0 == minage) {
completeDeletion = true;
// We must also push the metadata deletion and remove the metadata from the cache
Metadata meta = new Metadata(metadata);
meta.setSource(Configuration.INGRESS_METADATA_DELETE_SOURCE);
pushMetadataMessage(meta);
byte[] bytes = new byte[16];
// We know class/labels Id were computed in pushMetadataMessage
GTSHelper.fillGTSIds(bytes, 0, meta.getClassId(), meta.getLabelsId());
BigInteger key = new BigInteger(bytes);
synchronized(this.metadataCache) {
this.metadataCache.remove(key);
}
}
}
sb.setLength(0);
GTSHelper.metadataToString(sb, metadata.getName(), metadata.getLabels());
if (metadata.getAttributesSize() > 0) {
GTSHelper.labelsToString(sb, metadata.getAttributes());
} else {
sb.append("{}");
}
pw.write(sb.toString());
pw.write("\r\n");
gts++;
}
} catch (Exception e) {
throw new IOException(e);
}
}
} catch (Throwable t) {
LOG.error("",t);
Sensision.update(SensisionConstants.CLASS_WARP_INGRESS_DELETE_ERRORS, Sensision.EMPTY_LABELS, 1);
if (showErrors && null != pw) {
pw.println();
StringWriter sw = new StringWriter();
PrintWriter pw2 = new PrintWriter(sw);
t.printStackTrace(pw2);
pw2.close();
sw.flush();
String error = URLEncoder.encode(sw.toString(), StandardCharsets.UTF_8.name());
pw.println(Constants.INGRESS_DELETE_ERROR_PREFIX + error);
}
if (!response.isCommitted()) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.getMessage());
}
return;
} finally {
// Flush delete messages
if (!dryrun) {
pushDeleteMessage(0L,0L,0L,null);
if (completeDeletion) {
pushMetadataMessage(null, null);
}
}
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_DELETE_REQUESTS, sensisionLabels, 1);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_DELETE_GTS, sensisionLabels, gts);
}
response.setStatus(HttpServletResponse.SC_OK);
}
/**
* Extract Ingress related keys and populate the KeyStore with them.
*
* @param props Properties from which to extract the key specs
*/
private void extractKeys(KeyStore keystore, Properties props) {
String keyspec = props.getProperty(Configuration.INGRESS_KAFKA_META_MAC);
if (null != keyspec) {
byte[] key = keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length, "Key " + Configuration.INGRESS_KAFKA_META_MAC + " MUST be 128 bits long.");
keystore.setKey(KeyStore.SIPHASH_KAFKA_METADATA, key);
}
keyspec = props.getProperty(Configuration.INGRESS_KAFKA_DATA_MAC);
if (null != keyspec) {
byte[] key = keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length, "Key " + Configuration.INGRESS_KAFKA_DATA_MAC + " MUST be 128 bits long.");
keystore.setKey(KeyStore.SIPHASH_KAFKA_DATA, key);
}
keyspec = props.getProperty(Configuration.INGRESS_KAFKA_META_AES);
if (null != keyspec) {
byte[] key = keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length || 24 == key.length || 32 == key.length, "Key " + Configuration.INGRESS_KAFKA_META_AES + " MUST be 128, 192 or 256 bits long.");
keystore.setKey(KeyStore.AES_KAFKA_METADATA, key);
}
keyspec = props.getProperty(Configuration.INGRESS_KAFKA_DATA_AES);
if (null != keyspec) {
byte[] key = keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length || 24 == key.length || 32 == key.length, "Key " + Configuration.INGRESS_KAFKA_DATA_AES + " MUST be 128, 192 or 256 bits long.");
keystore.setKey(KeyStore.AES_KAFKA_DATA, key);
}
keyspec = props.getProperty(Configuration.DIRECTORY_PSK);
if (null != keyspec) {
byte[] key = this.keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length, "Key " + Configuration.DIRECTORY_PSK + " MUST be 128 bits long.");
this.keystore.setKey(KeyStore.SIPHASH_DIRECTORY_PSK, key);
}
this.keystore.forget();
}
void pushMetadataMessage(Metadata metadata) throws IOException {
if (null == metadata) {
pushMetadataMessage(null, null);
return;
}
//
// Compute class/labels Id
//
// 128bits
metadata.setClassId(GTSHelper.classId(this.classKey, metadata.getName()));
metadata.setLabelsId(GTSHelper.labelsId(this.labelsKey, metadata.getLabels()));
TSerializer serializer = new TSerializer(new TCompactProtocol.Factory());
try {
byte[] bytes = new byte[16];
GTSHelper.fillGTSIds(bytes, 0, metadata.getClassId(), metadata.getLabelsId());
pushMetadataMessage(bytes, serializer.serialize(metadata));
} catch (TException te) {
throw new IOException("Unable to push metadata.");
}
}
/**
* Push a metadata message onto the buffered list of Kafka messages
* and flush the list to Kafka if it has reached a threshold.
*
* @param key Key of the message to queue
* @param value Value of the message to queue
*/
private void pushMetadataMessage(byte[] key, byte[] value) throws IOException {
AtomicLong mms = this.metadataMessagesSize.get();
List<KeyedMessage<byte[], byte[]>> msglist = this.metadataMessages.get();
if (null != key && null != value) {
//
// Add key as a prefix of value
//
byte[] kv = Arrays.copyOf(key, key.length + value.length);
System.arraycopy(value, 0, kv, key.length, value.length);
value = kv;
//
// Encrypt value if the AES key is defined
//
if (null != this.AES_KAFKA_META) {
value = CryptoUtils.wrap(this.AES_KAFKA_META, value);
}
//
// Compute MAC if the SipHash key is defined
//
if (null != this.SIPHASH_KAFKA_META) {
value = CryptoUtils.addMAC(this.SIPHASH_KAFKA_META, value);
}
KeyedMessage<byte[], byte[]> message = new KeyedMessage<byte[], byte[]>(this.metaTopic, Arrays.copyOf(key, key.length), value);
msglist.add(message);
mms.addAndGet(key.length + value.length);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_META_MESSAGES, Sensision.EMPTY_LABELS, 1);
}
if (msglist.size() > 0 && (null == key || null == value || mms.get() > METADATA_MESSAGES_THRESHOLD)) {
Producer<byte[],byte[]> producer = this.metaProducerPool.getProducer();
try {
//
// How long it takes to send messages to Kafka
//
long nano = System.nanoTime();
producer.send(msglist);
nano = System.nanoTime() - nano;
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_METADATA_PRODUCER_SEND, Sensision.EMPTY_LABELS, nano);
} catch (Throwable t) {
//
// We need to remove the IDs of Metadata in 'msglist' from the cache so they get a chance to be
// pushed later
//
for (KeyedMessage<byte[],byte[]> msg: msglist) {
synchronized(this.metadataCache) {
this.metadataCache.remove(new BigInteger(msg.key()));
}
}
throw t;
} finally {
this.metaProducerPool.recycleProducer(producer);
}
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_META_SEND, Sensision.EMPTY_LABELS, 1);
msglist.clear();
mms.set(0L);
// Update sensision metric with size of metadata cache
Sensision.set(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_METADATA_CACHED, Sensision.EMPTY_LABELS, this.metadataCache.size());
}
}
/**
* Push a metadata message onto the buffered list of Kafka messages
* and flush the list to Kafka if it has reached a threshold.
*
* @param encoder GTSEncoder to push to Kafka. It MUST have classId/labelsId set.
*/
void pushDataMessage(GTSEncoder encoder, Map<String,String> attributes) throws IOException {
if (null != encoder) {
KafkaDataMessage msg = new KafkaDataMessage();
msg.setType(KafkaDataMessageType.STORE);
msg.setData(encoder.getBytes());
msg.setClassId(encoder.getClassId());
msg.setLabelsId(encoder.getLabelsId());
if (this.sendMetadataOnStore) {
msg.setMetadata(encoder.getMetadata());
}
if (null != attributes && !attributes.isEmpty()) {
msg.setAttributes(new HashMap<String,String>(attributes));
}
sendDataMessage(msg);
} else {
sendDataMessage(null);
}
}
private void sendDataMessage(KafkaDataMessage msg) throws IOException {
AtomicLong dms = this.dataMessagesSize.get();
List<KeyedMessage<byte[], byte[]>> msglist = this.dataMessages.get();
if (null != msg) {
//
// Build key
//
byte[] bytes = new byte[16];
GTSHelper.fillGTSIds(bytes, 0, msg.getClassId(), msg.getLabelsId());
//ByteBuffer bb = ByteBuffer.wrap(new byte[16]).order(ByteOrder.BIG_ENDIAN);
//bb.putLong(encoder.getClassId());
//bb.putLong(encoder.getLabelsId());
TSerializer serializer = new TSerializer(new TCompactProtocol.Factory());
byte[] msgbytes = null;
try {
msgbytes = serializer.serialize(msg);
} catch (TException te) {
throw new IOException(te);
}
//
// Encrypt value if the AES key is defined
//
if (null != this.aesDataKey) {
msgbytes = CryptoUtils.wrap(this.aesDataKey, msgbytes);
}
//
// Compute MAC if the SipHash key is defined
//
if (null != this.siphashDataKey) {
msgbytes = CryptoUtils.addMAC(this.siphashDataKey, msgbytes);
}
//KeyedMessage<byte[], byte[]> message = new KeyedMessage<byte[], byte[]>(this.dataTopic, bb.array(), msgbytes);
KeyedMessage<byte[], byte[]> message = new KeyedMessage<byte[], byte[]>(this.dataTopic, bytes, msgbytes);
msglist.add(message);
//this.dataMessagesSize.get().addAndGet(bb.array().length + msgbytes.length);
dms.addAndGet(bytes.length + msgbytes.length);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_MESSAGES, Sensision.EMPTY_LABELS, 1);
}
if (msglist.size() > 0 && (null == msg || dms.get() > DATA_MESSAGES_THRESHOLD)) {
Producer<byte[],byte[]> producer = getDataProducer();
//this.dataProducer.send(msglist);
try {
//
// How long it takes to send messages to Kafka
//
long nano = System.nanoTime();
producer.send(msglist);
nano = System.nanoTime() - nano;
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_PRODUCER_SEND, Sensision.EMPTY_LABELS, nano);
} catch (Throwable t) {
throw t;
} finally {
recycleDataProducer(producer);
}
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_SEND, Sensision.EMPTY_LABELS, 1);
msglist.clear();
dms.set(0L);
}
}
private Producer<byte[],byte[]> getDataProducer() {
//
// We will count how long we wait for a producer
//
long nano = System.nanoTime();
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_PRODUCER_POOL_GET, Sensision.EMPTY_LABELS, 1);
while(true) {
synchronized (this.dataProducers) {
if (this.dataProducersCurrentPoolSize > 0) {
//
// hand out the producer at index 0
//
Producer<byte[],byte[]> producer = this.dataProducers[0];
//
// Decrement current pool size
//
this.dataProducersCurrentPoolSize--;
//
// Move the last element of the array at index 0
//
this.dataProducers[0] = this.dataProducers[this.dataProducersCurrentPoolSize];
this.dataProducers[this.dataProducersCurrentPoolSize] = null;
//
// Log waiting time
//
nano = System.nanoTime() - nano;
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_PRODUCER_WAIT_NANO, Sensision.EMPTY_LABELS, nano);
return producer;
}
}
LockSupport.parkNanos(500000L);
}
}
private void recycleDataProducer(Producer<byte[],byte[]> producer) {
if (this.dataProducersCurrentPoolSize == this.dataProducers.length) {
throw new RuntimeException("Invalid call to recycleProducer, pool already full!");
}
synchronized (this.dataProducers) {
//
// Add the recycled producer at the end of the pool
//
this.dataProducers[this.dataProducersCurrentPoolSize++] = producer;
}
}
/**
* Push a deletion message onto the buffered list of Kafka messages
* and flush the list to Kafka if it has reached a threshold.
*
* Deletion messages MUST be pushed onto the data topic, otherwise the
* ordering won't be respected and you risk deleting a GTS which has been
* since repopulated with data.
*
* @param start Start timestamp for deletion
* @param end End timestamp for deletion
* @param metadata Metadata of the GTS to delete
*/
private void pushDeleteMessage(long start, long end, long minage, Metadata metadata) throws IOException {
if (null != metadata) {
KafkaDataMessage msg = new KafkaDataMessage();
msg.setType(KafkaDataMessageType.DELETE);
msg.setDeletionStartTimestamp(start);
msg.setDeletionEndTimestamp(end);
msg.setDeletionMinAge(minage);
msg.setClassId(metadata.getClassId());
msg.setLabelsId(metadata.getLabelsId());
if (this.sendMetadataOnDelete) {
msg.setMetadata(metadata);
}
sendDataMessage(msg);
} else {
sendDataMessage(null);
}
}
private void dumpCache() {
if (null == this.cacheDumpPath) {
return;
}
OutputStream out = null;
long nano = System.nanoTime();
long count = 0;
try {
out = new GZIPOutputStream(new FileOutputStream(this.cacheDumpPath));
Set<BigInteger> bis = new HashSet<BigInteger>();
synchronized(this.metadataCache) {
boolean error = false;
do {
try {
error = false;
bis.addAll(this.metadataCache.keySet());
} catch (ConcurrentModificationException cme) {
error = true;
}
} while (error);
}
Iterator<BigInteger> iter = bis.iterator();
//
// 128bits
//
byte[] allzeroes = new byte[16];
Arrays.fill(allzeroes, (byte) 0);
byte[] allones = new byte[16];
Arrays.fill(allones, (byte) 0xff);
while (true) {
try {
if (!iter.hasNext()) {
break;
}
BigInteger bi = iter.next();
byte[] raw = bi.toByteArray();
//
// 128bits
//
if (raw.length != 16) {
if (bi.signum() < 0) {
out.write(allones, 0, 16 - raw.length);
} else {
out.write(allzeroes, 0, 16 - raw.length);
}
}
out.write(raw);
if (this.activityTracking) {
Long lastActivity = this.metadataCache.get(bi);
byte[] bytes;
if (null != lastActivity) {
bytes = Longs.toByteArray(lastActivity);
} else {
bytes = new byte[8];
}
out.write(bytes);
}
count++;
} catch (ConcurrentModificationException cme) {
}
}
} catch (IOException ioe) {
} finally {
if (null != out) {
try { out.close(); } catch (Exception e) {}
}
}
nano = System.nanoTime() - nano;
LOG.info("Dumped " + count + " cache entries in " + (nano / 1000000.0D) + " ms.");
}
private void loadCache() {
if (null == this.cacheDumpPath) {
return;
}
InputStream in = null;
byte[] buf = new byte[8192];
long nano = System.nanoTime();
long count = 0;
try {
in = new GZIPInputStream(new FileInputStream(this.cacheDumpPath));
int offset = 0;
// 128 bits
int reclen = this.activityTracking ? 24 : 16;
byte[] raw = new byte[16];
while(true) {
int len = in.read(buf, offset, buf.length - offset);
offset += len;
int idx = 0;
while(idx < offset && offset - idx >= reclen) {
System.arraycopy(buf, idx, raw, 0, 16);
BigInteger id = new BigInteger(raw);
if (this.activityTracking) {
long lastActivity = 0L;
for (int i = 0; i < 8; i++) {
lastActivity <<= 8;
lastActivity |= ((long) buf[idx + 16 + i]) & 0xFFL;
}
synchronized(this.metadataCache) {
this.metadataCache.put(id, lastActivity);
}
} else {
synchronized(this.metadataCache) {
this.metadataCache.put(id, null);
}
}
count++;
idx += reclen;
}
if (idx < offset) {
for (int i = idx; i < offset; i++) {
buf[i - idx] = buf[i];
}
offset = offset - idx;
} else {
offset = 0;
}
if (len < 0) {
break;
}
}
} catch (IOException ioe) {
} finally {
if (null != in) {
try { in.close(); } catch (Exception e) {}
}
}
nano = System.nanoTime() - nano;
LOG.info("Loaded " + count + " cache entries in " + (nano / 1000000.0D) + " ms.");
}
}
| warp10/src/main/java/io/warp10/continuum/ingress/Ingress.java | //
// Copyright 2018 SenX S.A.S.
//
// 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.warp10.continuum.ingress;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.regex.Matcher;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.warp10.ThrowableUtils;
import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;
import org.apache.hadoop.util.ShutdownHookManager;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TCompactProtocol;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.sort.SortConfig;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import io.warp10.SSLUtils;
import io.warp10.WarpConfig;
import io.warp10.WarpManager;
import io.warp10.continuum.Configuration;
import io.warp10.continuum.JettyUtil;
import io.warp10.continuum.KafkaProducerPool;
import io.warp10.continuum.KafkaSynchronizedConsumerPool;
import io.warp10.continuum.KafkaSynchronizedConsumerPool.ConsumerFactory;
import io.warp10.continuum.MetadataUtils;
import io.warp10.continuum.TextFileShuffler;
import io.warp10.continuum.ThrottlingManager;
import io.warp10.continuum.TimeSource;
import io.warp10.continuum.Tokens;
import io.warp10.continuum.WarpException;
import io.warp10.continuum.egress.CORSHandler;
import io.warp10.continuum.egress.EgressFetchHandler;
import io.warp10.continuum.egress.ThriftDirectoryClient;
import io.warp10.continuum.gts.GTSEncoder;
import io.warp10.continuum.gts.GTSHelper;
import io.warp10.continuum.sensision.SensisionConstants;
import io.warp10.continuum.store.Constants;
import io.warp10.continuum.store.DirectoryClient;
import io.warp10.continuum.store.MetadataIterator;
import io.warp10.continuum.store.thrift.data.DirectoryRequest;
import io.warp10.continuum.store.thrift.data.KafkaDataMessage;
import io.warp10.continuum.store.thrift.data.KafkaDataMessageType;
import io.warp10.continuum.store.thrift.data.Metadata;
import io.warp10.crypto.CryptoUtils;
import io.warp10.crypto.KeyStore;
import io.warp10.crypto.OrderPreservingBase64;
import io.warp10.crypto.SipHashInline;
import io.warp10.quasar.token.thrift.data.WriteToken;
import io.warp10.script.WarpScriptException;
import io.warp10.sensision.Sensision;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
// FIXME(hbs): handle archive
/**
* This is the class which ingests metrics.
*/
public class Ingress extends AbstractHandler implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Ingress.class);
private static final Long NO_LAST_ACTIVITY = Long.MIN_VALUE;
/**
* Set of required parameters, those MUST be set
*/
private static final String[] REQUIRED_PROPERTIES = new String[] {
Configuration.INGRESS_HOST,
Configuration.INGRESS_PORT,
Configuration.INGRESS_ACCEPTORS,
Configuration.INGRESS_SELECTORS,
Configuration.INGRESS_IDLE_TIMEOUT,
Configuration.INGRESS_JETTY_THREADPOOL,
Configuration.INGRESS_ZK_QUORUM,
Configuration.INGRESS_KAFKA_META_BROKERLIST,
Configuration.INGRESS_KAFKA_META_TOPIC,
Configuration.INGRESS_KAFKA_DATA_BROKERLIST,
Configuration.INGRESS_KAFKA_DATA_TOPIC,
Configuration.INGRESS_KAFKA_DATA_POOLSIZE,
Configuration.INGRESS_KAFKA_METADATA_POOLSIZE,
Configuration.INGRESS_KAFKA_DATA_MAXSIZE,
Configuration.INGRESS_KAFKA_METADATA_MAXSIZE,
Configuration.INGRESS_VALUE_MAXSIZE,
Configuration.INGRESS_DELETE_SHUFFLE,
Configuration.DIRECTORY_PSK,
};
private final String metaTopic;
private final String dataTopic;
private final DirectoryClient directoryClient;
final long maxValueSize;
final long ttl;
final boolean useDatapointTs;
private final String cacheDumpPath;
private DateTimeFormatter fmt = ISODateTimeFormat.dateTimeParser();
/**
* List of pending Kafka messages containing metadata (one per Thread)
*/
private final ThreadLocal<List<KeyedMessage<byte[], byte[]>>> metadataMessages = new ThreadLocal<List<KeyedMessage<byte[], byte[]>>>() {
protected java.util.List<kafka.producer.KeyedMessage<byte[],byte[]>> initialValue() {
return new ArrayList<KeyedMessage<byte[], byte[]>>();
};
};
/**
* Byte size of metadataMessages
*/
private ThreadLocal<AtomicLong> metadataMessagesSize = new ThreadLocal<AtomicLong>() {
protected AtomicLong initialValue() {
return new AtomicLong();
};
};
/**
* Size threshold after which we flush metadataMessages into Kafka
*/
private final long METADATA_MESSAGES_THRESHOLD;
/**
* List of pending Kafka messages containing data
*/
private final ThreadLocal<List<KeyedMessage<byte[], byte[]>>> dataMessages = new ThreadLocal<List<KeyedMessage<byte[], byte[]>>>() {
protected java.util.List<kafka.producer.KeyedMessage<byte[],byte[]>> initialValue() {
return new ArrayList<KeyedMessage<byte[], byte[]>>();
};
};
/**
* Byte size of dataMessages
*/
private ThreadLocal<AtomicLong> dataMessagesSize = new ThreadLocal<AtomicLong>() {
protected AtomicLong initialValue() {
return new AtomicLong();
};
};
/**
* Size threshold after which we flush dataMessages into Kafka
*
* This and METADATA_MESSAGES_THRESHOLD has to be lower than the configured Kafka max message size (message.max.bytes)
*/
final long DATA_MESSAGES_THRESHOLD;
/**
* Kafka producer for readings
*/
//private final Producer<byte[], byte[]> dataProducer;
/**
* Pool of producers for the 'data' topic
*/
private final Producer<byte[], byte[]>[] dataProducers;
private int dataProducersCurrentPoolSize = 0;
/**
* Pool of producers for the 'metadata' topic
*/
private final KafkaProducerPool metaProducerPool;
/**
* Number of classId/labelsId to remember (to avoid pushing their metadata to Kafka)
* Memory footprint is that of a BigInteger whose byte representation is 16 bytes, so probably
* around 40 bytes
* FIXME(hbs): need to compute exactly
*/
private int METADATA_CACHE_SIZE = 10000000;
/**
* Cache used to determine if we should push metadata into Kafka or if it was previously seen.
* Key is a BigInteger constructed from a byte array of classId+labelsId (we cannot use byte[] as map key)
*/
final Map<BigInteger, Long> metadataCache = new LinkedHashMap<BigInteger, Long>(100, 0.75F, true) {
@Override
protected boolean removeEldestEntry(java.util.Map.Entry<BigInteger, Long> eldest) {
return this.size() > METADATA_CACHE_SIZE;
}
};
final KeyStore keystore;
final Properties properties;
final long[] classKey;
final long[] labelsKey;
final byte[] AES_KAFKA_META;
final long[] SIPHASH_KAFKA_META;
private final byte[] aesDataKey;
private final long[] siphashDataKey;
private final boolean sendMetadataOnDelete;
private final boolean sendMetadataOnStore;
private final KafkaSynchronizedConsumerPool pool;
private final boolean doShuffle;
/**
* Flag indicating whether or not we reject delete requests
*/
private final boolean rejectDelete;
final boolean activityTracking;
final boolean updateActivity;
private final boolean metaActivity;
final long activityWindow;
public final boolean parseAttributes;
final Long maxpastDefault;
final Long maxfutureDefault;
final Long maxpastOverride;
final Long maxfutureOverride;
final boolean ignoreOutOfRange;
public Ingress(KeyStore keystore, Properties props) {
//
// Enable the ThrottlingManager
//
ThrottlingManager.enable();
this.keystore = keystore;
this.properties = props;
//
// Make sure all required configuration is present
//
for (String required: REQUIRED_PROPERTIES) {
Preconditions.checkNotNull(props.getProperty(required), "Missing configuration parameter '%s'.", required);
}
//
// Extract parameters from 'props'
//
this.ttl = Long.parseLong(props.getProperty(Configuration.INGRESS_HBASE_CELLTTL, "-1"));
this.useDatapointTs = "true".equals(props.getProperty(Configuration.INGRESS_HBASE_DPTS));
this.doShuffle = "true".equals(props.getProperty(Configuration.INGRESS_DELETE_SHUFFLE));
this.rejectDelete = "true".equals(props.getProperty(Configuration.INGRESS_DELETE_REJECT));
this.activityWindow = Long.parseLong(properties.getProperty(Configuration.INGRESS_ACTIVITY_WINDOW, "0"));
this.activityTracking = this.activityWindow > 0;
this.updateActivity = "true".equals(props.getProperty(Configuration.INGRESS_ACTIVITY_UPDATE));
this.metaActivity = "true".equals(props.getProperty(Configuration.INGRESS_ACTIVITY_META));
if (props.containsKey(Configuration.INGRESS_CACHE_DUMP_PATH)) {
this.cacheDumpPath = props.getProperty(Configuration.INGRESS_CACHE_DUMP_PATH);
} else {
this.cacheDumpPath = null;
}
if (null != props.getProperty(Configuration.INGRESS_METADATA_CACHE_SIZE)) {
this.METADATA_CACHE_SIZE = Integer.valueOf(props.getProperty(Configuration.INGRESS_METADATA_CACHE_SIZE));
}
this.metaTopic = props.getProperty(Configuration.INGRESS_KAFKA_META_TOPIC);
this.dataTopic = props.getProperty(Configuration.INGRESS_KAFKA_DATA_TOPIC);
this.DATA_MESSAGES_THRESHOLD = Long.parseLong(props.getProperty(Configuration.INGRESS_KAFKA_DATA_MAXSIZE));
this.METADATA_MESSAGES_THRESHOLD = Long.parseLong(props.getProperty(Configuration.INGRESS_KAFKA_METADATA_MAXSIZE));
this.maxValueSize = Long.parseLong(props.getProperty(Configuration.INGRESS_VALUE_MAXSIZE));
if (this.maxValueSize > (this.DATA_MESSAGES_THRESHOLD / 2) - 64) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_VALUE_MAXSIZE + "' cannot exceed that half of '" + Configuration.INGRESS_KAFKA_DATA_MAXSIZE + "' minus 64.");
}
extractKeys(this.keystore, props);
this.classKey = SipHashInline.getKey(this.keystore.getKey(KeyStore.SIPHASH_CLASS));
this.labelsKey = SipHashInline.getKey(this.keystore.getKey(KeyStore.SIPHASH_LABELS));
this.AES_KAFKA_META = this.keystore.getKey(KeyStore.AES_KAFKA_METADATA);
this.SIPHASH_KAFKA_META = SipHashInline.getKey(this.keystore.getKey(KeyStore.SIPHASH_KAFKA_METADATA));
this.aesDataKey = this.keystore.getKey(KeyStore.AES_KAFKA_DATA);
this.siphashDataKey = SipHashInline.getKey(this.keystore.getKey(KeyStore.SIPHASH_KAFKA_DATA));
this.sendMetadataOnDelete = Boolean.parseBoolean(props.getProperty(Configuration.INGRESS_DELETE_METADATA_INCLUDE, "false"));
this.sendMetadataOnStore = Boolean.parseBoolean(props.getProperty(Configuration.INGRESS_STORE_METADATA_INCLUDE, "false"));
this.parseAttributes = "true".equals(props.getProperty(Configuration.INGRESS_PARSE_ATTRIBUTES));
if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_DEFAULT)) {
maxpastDefault = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_DEFAULT));
if (maxpastDefault < 0) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXPAST_DEFAULT + "' MUST be positive.");
}
} else {
maxpastDefault = null;
}
if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_DEFAULT)) {
maxfutureDefault = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_DEFAULT));
if (maxfutureDefault < 0) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXFUTURE_DEFAULT + "' MUST be positive.");
}
} else {
maxfutureDefault = null;
}
if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_OVERRIDE)) {
maxpastOverride = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_OVERRIDE));
if (maxpastOverride < 0) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXPAST_OVERRIDE + "' MUST be positive.");
}
} else {
maxpastOverride = null;
}
if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_OVERRIDE)) {
maxfutureOverride = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_OVERRIDE));
if (maxfutureOverride < 0) {
throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXFUTURE_OVERRIDE + "' MUST be positive.");
}
} else {
maxfutureOverride = null;
}
this.ignoreOutOfRange = "true".equals(WarpConfig.getProperty(Configuration.INGRESS_OUTOFRANGE_IGNORE));
//
// Prepare meta, data and delete producers
//
Properties metaProps = new Properties();
// @see http://kafka.apache.org/documentation.html#producerconfigs
metaProps.setProperty("metadata.broker.list", props.getProperty(Configuration.INGRESS_KAFKA_META_BROKERLIST));
if (null != props.getProperty(Configuration.INGRESS_KAFKA_META_PRODUCER_CLIENTID)) {
metaProps.setProperty("client.id", props.getProperty(Configuration.INGRESS_KAFKA_META_PRODUCER_CLIENTID));
}
metaProps.setProperty("request.required.acks", "-1");
// TODO(hbs): when we move to the new KafkaProducer API
//metaProps.setProperty(org.apache.kafka.clients.producer.ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1");
metaProps.setProperty("producer.type","sync");
metaProps.setProperty("serializer.class", "kafka.serializer.DefaultEncoder");
metaProps.setProperty("partitioner.class", io.warp10.continuum.KafkaPartitioner.class.getName());
//??? metaProps.setProperty("block.on.buffer.full", "true");
// FIXME(hbs): compression does not work
//metaProps.setProperty("compression.codec", "snappy");
//metaProps.setProperty("client.id","");
ProducerConfig metaConfig = new ProducerConfig(metaProps);
this.metaProducerPool = new KafkaProducerPool(metaConfig,
Integer.parseInt(props.getProperty(Configuration.INGRESS_KAFKA_METADATA_POOLSIZE)),
SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_METADATA_PRODUCER_POOL_GET,
SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_METADATA_PRODUCER_WAIT_NANO);
Properties dataProps = new Properties();
// @see http://kafka.apache.org/documentation.html#producerconfigs
dataProps.setProperty("metadata.broker.list", props.getProperty(Configuration.INGRESS_KAFKA_DATA_BROKERLIST));
if (null != props.getProperty(Configuration.INGRESS_KAFKA_DATA_PRODUCER_CLIENTID)) {
dataProps.setProperty("client.id", props.getProperty(Configuration.INGRESS_KAFKA_DATA_PRODUCER_CLIENTID));
}
dataProps.setProperty("request.required.acks", "-1");
dataProps.setProperty("producer.type","sync");
dataProps.setProperty("serializer.class", "kafka.serializer.DefaultEncoder");
dataProps.setProperty("partitioner.class", io.warp10.continuum.KafkaPartitioner.class.getName());
// TODO(hbs): when we move to the new KafkaProducer API
//dataProps.setProperty(org.apache.kafka.clients.producer.ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1");
if (null != props.getProperty(Configuration.INGRESS_KAFKA_DATA_REQUEST_TIMEOUT_MS)) {
dataProps.setProperty("request.timeout.ms", props.getProperty(Configuration.INGRESS_KAFKA_DATA_REQUEST_TIMEOUT_MS));
}
///???? dataProps.setProperty("block.on.buffer.full", "true");
// FIXME(hbs): compression does not work
//dataProps.setProperty("compression.codec", "snappy");
//dataProps.setProperty("client.id","");
ProducerConfig dataConfig = new ProducerConfig(dataProps);
//this.dataProducer = new Producer<byte[], byte[]>(dataConfig);
//
// Allocate producer pool
//
this.dataProducers = new Producer[Integer.parseInt(props.getProperty(Configuration.INGRESS_KAFKA_DATA_POOLSIZE))];
for (int i = 0; i < dataProducers.length; i++) {
this.dataProducers[i] = new Producer<byte[], byte[]>(dataConfig);
}
this.dataProducersCurrentPoolSize = this.dataProducers.length;
//
// Producer for the Delete topic
//
/*
Properties deleteProps = new Properties();
// @see http://kafka.apache.org/documentation.html#producerconfigs
deleteProps.setProperty("metadata.broker.list", props.getProperty(INGRESS_KAFKA_DELETE_BROKERLIST));
deleteProps.setProperty("request.required.acks", "-1");
deleteProps.setProperty("producer.type","sync");
deleteProps.setProperty("serializer.class", "kafka.serializer.DefaultEncoder");
deleteProps.setProperty("partitioner.class", io.warp10.continuum.KafkaPartitioner.class.getName());
ProducerConfig deleteConfig = new ProducerConfig(deleteProps);
this.deleteProducer = new Producer<byte[], byte[]>(deleteConfig);
*/
//
// Attempt to load the cache file (we do that prior to starting the Kafka consumer)
//
loadCache();
//
// Create Kafka consumer to handle Metadata deletions
//
ConsumerFactory metadataConsumerFactory = new IngressMetadataConsumerFactory(this);
if (props.containsKey(Configuration.INGRESS_KAFKA_META_GROUPID)) {
pool = new KafkaSynchronizedConsumerPool(props.getProperty(Configuration.INGRESS_KAFKA_META_ZKCONNECT),
props.getProperty(Configuration.INGRESS_KAFKA_META_TOPIC),
props.getProperty(Configuration.INGRESS_KAFKA_META_CONSUMER_CLIENTID),
props.getProperty(Configuration.INGRESS_KAFKA_META_GROUPID),
props.getProperty(Configuration.INGRESS_KAFKA_META_CONSUMER_PARTITION_ASSIGNMENT_STRATEGY),
props.getProperty(Configuration.INGRESS_KAFKA_META_CONSUMER_AUTO_OFFSET_RESET),
Integer.parseInt(props.getProperty(Configuration.INGRESS_KAFKA_META_NTHREADS)),
Long.parseLong(props.getProperty(Configuration.INGRESS_KAFKA_META_COMMITPERIOD)),
metadataConsumerFactory);
} else {
pool = null;
}
//
// Initialize ThriftDirectoryService
//
try {
this.directoryClient = new ThriftDirectoryClient(this.keystore, props);
} catch (Exception e) {
throw new RuntimeException(e);
}
//
// Register shutdown hook
//
final Ingress self = this;
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
//
// Make sure the Kakfa consumers are stopped so we don't miss deletions
// when restarting and using the cache we are about to store
//
if (null != self.pool) {
self.pool.shutdown();
LOG.info("Waiting for Ingress Kafka consumers to stop.");
while(!self.pool.isStopped()) {
LockSupport.parkNanos(250000000L);
}
LOG.info("Kafka consumers stopped, dumping GTS cache");
}
self.dumpCache();
}
});
//
// Make sure ShutdownHookManager is initialized, otherwise it will try to
// register a shutdown hook during the shutdown hook we just registered...
//
ShutdownHookManager.get();
//
// Start Jetty server
//
int maxThreads = Integer.parseInt(props.getProperty(Configuration.INGRESS_JETTY_THREADPOOL));
boolean enableStreamUpdate = !("true".equals(props.getProperty(Configuration.WARP_STREAMUPDATE_DISABLE)));
BlockingArrayQueue<Runnable> queue = null;
if (props.containsKey(Configuration.INGRESS_JETTY_MAXQUEUESIZE)) {
int queuesize = Integer.parseInt(props.getProperty(Configuration.INGRESS_JETTY_MAXQUEUESIZE));
queue = new BlockingArrayQueue<Runnable>(queuesize);
}
Server server = new Server(new QueuedThreadPool(maxThreads,8, 60000, queue));
List<Connector> connectors = new ArrayList<Connector>();
boolean useHttp = null != props.getProperty(Configuration.INGRESS_PORT);
boolean useHttps = null != props.getProperty(Configuration.INGRESS_PREFIX + Configuration._SSL_PORT);
if (useHttp) {
int port = Integer.valueOf(props.getProperty(Configuration.INGRESS_PORT));
String host = props.getProperty(Configuration.INGRESS_HOST);
int acceptors = Integer.valueOf(props.getProperty(Configuration.INGRESS_ACCEPTORS));
int selectors = Integer.valueOf(props.getProperty(Configuration.INGRESS_SELECTORS));
long idleTimeout = Long.parseLong(props.getProperty(Configuration.INGRESS_IDLE_TIMEOUT));
ServerConnector connector = new ServerConnector(server, acceptors, selectors);
connector.setIdleTimeout(idleTimeout);
connector.setPort(port);
connector.setHost(host);
connector.setName("Continuum Ingress HTTP");
connectors.add(connector);
}
if (useHttps) {
ServerConnector connector = SSLUtils.getConnector(server, Configuration.INGRESS_PREFIX);
connector.setName("Continuum Ingress HTTPS");
connectors.add(connector);
}
server.setConnectors(connectors.toArray(new Connector[connectors.size()]));
HandlerList handlers = new HandlerList();
Handler cors = new CORSHandler();
handlers.addHandler(cors);
handlers.addHandler(this);
if (enableStreamUpdate) {
IngressStreamUpdateHandler suHandler = new IngressStreamUpdateHandler(this);
handlers.addHandler(suHandler);
}
server.setHandler(handlers);
JettyUtil.setSendServerVersion(server, false);
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
Thread t = new Thread(this);
t.setDaemon(true);
t.setName("Continuum Ingress");
t.start();
}
@Override
public void run() {
//
// Register in ZK and watch parent znode.
// If the Ingress count exceeds the licensed number,
// exit if we are the first of the list.
//
while(true) {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException ie) {
}
}
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String token = null;
if (target.equals(Constants.API_ENDPOINT_UPDATE)) {
baseRequest.setHandled(true);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_REQUESTS, Sensision.EMPTY_LABELS, 1);
} else if (target.startsWith(Constants.API_ENDPOINT_UPDATE + "/")) {
baseRequest.setHandled(true);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_REQUESTS, Sensision.EMPTY_LABELS, 1);
token = target.substring(Constants.API_ENDPOINT_UPDATE.length() + 1);
} else if (target.equals(Constants.API_ENDPOINT_META)) {
handleMeta(target, baseRequest, request, response);
return;
} else if (target.equals(Constants.API_ENDPOINT_DELETE)) {
handleDelete(target, baseRequest, request, response);
} else if (Constants.API_ENDPOINT_CHECK.equals(target)) {
baseRequest.setHandled(true);
response.setStatus(HttpServletResponse.SC_OK);
return;
} else {
return;
}
if (null != WarpManager.getAttribute(WarpManager.UPDATE_DISABLED)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, String.valueOf(WarpManager.getAttribute(WarpManager.UPDATE_DISABLED)));
return;
}
long nowms = System.currentTimeMillis();
try {
//
// CORS header
//
response.setHeader("Access-Control-Allow-Origin", "*");
long nano = System.nanoTime();
//
// TODO(hbs): Extract producer/owner from token
//
if (null == token) {
token = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));
}
WriteToken writeToken;
try {
writeToken = Tokens.extractWriteToken(token);
if (writeToken.getAttributesSize() > 0 && writeToken.getAttributes().containsKey(Constants.TOKEN_ATTR_NOUPDATE)) {
throw new WarpScriptException("Token cannot be used for updating data.");
}
} catch (WarpScriptException ee) {
throw new IOException(ee);
}
String application = writeToken.getAppName();
String producer = Tokens.getUUID(writeToken.getProducerId());
String owner = Tokens.getUUID(writeToken.getOwnerId());
Map<String,String> sensisionLabels = new HashMap<String,String>();
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);
long count = 0;
//
// Extract KafkaDataMessage attributes
//
Map<String,String> kafkaDataMessageAttributes = null;
if (-1 != ttl || useDatapointTs) {
kafkaDataMessageAttributes = new HashMap<String,String>();
if (-1 != ttl) {
kafkaDataMessageAttributes.put(Constants.STORE_ATTR_TTL, Long.toString(ttl));
}
if (useDatapointTs) {
kafkaDataMessageAttributes.put(Constants.STORE_ATTR_USEDATAPOINTTS, "t");
}
}
if (writeToken.getAttributesSize() > 0) {
if (writeToken.getAttributes().containsKey(Constants.STORE_ATTR_TTL)
|| writeToken.getAttributes().containsKey(Constants.STORE_ATTR_USEDATAPOINTTS)) {
if (null == kafkaDataMessageAttributes) {
kafkaDataMessageAttributes = new HashMap<String,String>();
}
if (writeToken.getAttributes().containsKey(Constants.STORE_ATTR_TTL)) {
kafkaDataMessageAttributes.put(Constants.STORE_ATTR_TTL, writeToken.getAttributes().get(Constants.STORE_ATTR_TTL));
}
if (writeToken.getAttributes().containsKey(Constants.STORE_ATTR_USEDATAPOINTTS)) {
kafkaDataMessageAttributes.put(Constants.STORE_ATTR_USEDATAPOINTTS, writeToken.getAttributes().get(Constants.STORE_ATTR_USEDATAPOINTTS));
}
}
}
try {
if (null == producer || null == owner) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_INVALIDTOKEN, Sensision.EMPTY_LABELS, 1);
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
return;
}
//
// Build extra labels
//
Map<String,String> extraLabels = new HashMap<String,String>();
// Add labels from the WriteToken if they exist
if (writeToken.getLabelsSize() > 0) {
extraLabels.putAll(writeToken.getLabels());
}
// Force internal labels
extraLabels.put(Constants.PRODUCER_LABEL, producer);
extraLabels.put(Constants.OWNER_LABEL, owner);
// FIXME(hbs): remove me
if (null != application) {
extraLabels.put(Constants.APPLICATION_LABEL, application);
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
}
long maxsize = maxValueSize;
if (writeToken.getAttributesSize() > 0 && null != writeToken.getAttributes().get(Constants.TOKEN_ATTR_MAXSIZE)) {
maxsize = Long.parseLong(writeToken.getAttributes().get(Constants.TOKEN_ATTR_MAXSIZE));
if (maxsize > (DATA_MESSAGES_THRESHOLD / 2) - 64) {
maxsize = (DATA_MESSAGES_THRESHOLD / 2) - 64;
}
}
//
// Determine if content is gzipped
//
boolean gzipped = false;
if (null != request.getHeader("Content-Type") && "application/gzip".equals(request.getHeader("Content-Type"))) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_GZIPPED, sensisionLabels, 1);
gzipped = true;
}
BufferedReader br = null;
if (gzipped) {
GZIPInputStream is = new GZIPInputStream(request.getInputStream());
br = new BufferedReader(new InputStreamReader(is));
} else {
br = request.getReader();
}
Long now = TimeSource.getTime();
//
// Extract time limits
//
Long maxpast = null;
if (null != maxpastDefault) {
try {
maxpast = Math.subtractExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, maxpastDefault));
} catch (ArithmeticException ae) {
maxpast = null;
}
}
Long maxfuture = null;
if (null != maxfutureDefault) {
try {
maxfuture = Math.addExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, maxfutureDefault));
} catch (ArithmeticException ae) {
maxfuture = null;
}
}
Boolean ignoor = null;
if (writeToken.getAttributesSize() > 0) {
if (writeToken.getAttributes().containsKey(Constants.TOKEN_ATTR_IGNOOR)) {
String v = writeToken.getAttributes().get(Constants.TOKEN_ATTR_IGNOOR).toLowerCase();
if ("true".equals(v) || "t".equals(v)) {
ignoor = Boolean.TRUE;
} else if ("false".equals(v) || "f".equals(v)) {
ignoor = Boolean.FALSE;
}
}
String deltastr = writeToken.getAttributes().get(Constants.TOKEN_ATTR_MAXPAST);
if (null != deltastr) {
long delta = Long.parseLong(deltastr);
if (delta < 0) {
throw new WarpScriptException("Invalid '" + Constants.TOKEN_ATTR_MAXPAST + "' token attribute, MUST be positive.");
}
try {
maxpast = Math.subtractExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, delta));
} catch (ArithmeticException ae) {
maxpast = null;
}
}
deltastr = writeToken.getAttributes().get(Constants.TOKEN_ATTR_MAXFUTURE);
if (null != deltastr) {
long delta = Long.parseLong(deltastr);
if (delta < 0) {
throw new WarpScriptException("Invalid '" + Constants.TOKEN_ATTR_MAXFUTURE + "' token attribute, MUST be positive.");
}
try {
maxfuture = Math.addExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, delta));
} catch (ArithmeticException ae) {
maxfuture = null;
}
}
}
if (null != maxpastOverride) {
try {
maxpast = Math.subtractExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, maxpastOverride));
} catch (ArithmeticException ae) {
maxpast = null;
}
}
if (null != maxfutureOverride) {
try {
maxfuture = Math.addExact(now, Math.multiplyExact(Constants.TIME_UNITS_PER_MS, maxfutureOverride));
} catch (ArithmeticException ae) {
maxfuture = null;
}
}
//
// Check the value of the 'now' header
//
// The following values are supported:
//
// A number, which will be interpreted as an absolute time reference,
// i.e. a number of time units since the Epoch.
//
// A number prefixed by '+' or '-' which will be interpreted as a
// delta from the present time.
//
// A '*' which will mean to not set 'now', and to recompute its value
// each time it's needed.
//
String nowstr = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_NOW_HEADERX));
if (null != nowstr) {
if ("*".equals(nowstr)) {
now = null;
} else if (nowstr.startsWith("+")) {
try {
long delta = Long.parseLong(nowstr.substring(1));
now = now + delta;
} catch (Exception e) {
throw new IOException("Invalid base timestamp.");
}
} else if (nowstr.startsWith("-")) {
try {
long delta = Long.parseLong(nowstr.substring(1));
now = now - delta;
} catch (Exception e) {
throw new IOException("Invalid base timestamp.");
}
} else {
try {
now = Long.parseLong(nowstr);
} catch (Exception e) {
throw new IOException("Invalid base timestamp.");
}
}
}
//
// Loop on all lines
//
GTSEncoder lastencoder = null;
GTSEncoder encoder = null;
byte[] bytes = new byte[16];
int idx = 0;
AtomicLong dms = this.dataMessagesSize.get();
// Atomic boolean to track if attributes were parsed
AtomicBoolean hadAttributes = parseAttributes ? new AtomicBoolean(false) : null;
boolean lastHadAttributes = false;
AtomicLong ignoredCount = null;
if ((this.ignoreOutOfRange && !Boolean.FALSE.equals(ignoor)) || Boolean.TRUE.equals(ignoor)) {
ignoredCount = new AtomicLong(0L);
}
do {
// We copy the current value of hadAttributes
if (parseAttributes) {
lastHadAttributes = lastHadAttributes || hadAttributes.get();
hadAttributes.set(false);
}
String line = br.readLine();
if (null == line) {
break;
}
if ("".equals(line)) {
continue;
}
// Skip lines which start with '#'
if ('#' == line.charAt(0)) {
continue;
}
try {
encoder = GTSHelper.parse(lastencoder, line, extraLabels, now, maxsize, hadAttributes, maxpast, maxfuture, ignoredCount);
count++;
} catch (ParseException pe) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_PARSEERRORS, sensisionLabels, 1);
throw new IOException("Parse error at '" + line + "'", pe);
}
if (encoder != lastencoder || dms.get() + 16 + lastencoder.size() > DATA_MESSAGES_THRESHOLD) {
//
// Determine if we should push the metadata or not
//
encoder.setClassId(GTSHelper.classId(this.classKey, encoder.getMetadata().getName()));
encoder.setLabelsId(GTSHelper.labelsId(this.labelsKey, encoder.getMetadata().getLabels()));
GTSHelper.fillGTSIds(bytes, 0, encoder.getClassId(), encoder.getLabelsId());
BigInteger metadataCacheKey = new BigInteger(bytes);
//
// Check throttling
//
if (null != lastencoder && lastencoder.size() > 0) {
ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application, lastencoder.getClassId(), lastencoder.getLabelsId());
ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application, (int) lastencoder.getCount());
}
boolean pushMeta = false;
Long val = this.metadataCache.getOrDefault(metadataCacheKey, NO_LAST_ACTIVITY);
if (NO_LAST_ACTIVITY.equals(val)) {
pushMeta = true;
} else if (activityTracking && updateActivity) {
Long lastActivity = val;
if (null == lastActivity) {
pushMeta = true;
} else if (nowms - lastActivity > activityWindow) {
pushMeta = true;
}
}
if (pushMeta) {
// Build metadata object to push
Metadata metadata = new Metadata();
// Set source to indicate we
metadata.setSource(Configuration.INGRESS_METADATA_SOURCE);
metadata.setName(encoder.getMetadata().getName());
metadata.setLabels(encoder.getMetadata().getLabels());
if (this.activityTracking && updateActivity) {
metadata.setLastActivity(nowms);
}
TSerializer serializer = new TSerializer(new TCompactProtocol.Factory());
try {
pushMetadataMessage(bytes, serializer.serialize(metadata));
// Update metadataCache with the current key
synchronized(metadataCache) {
this.metadataCache.put(metadataCacheKey, (activityTracking && updateActivity) ? nowms : null);
}
} catch (TException te) {
throw new IOException("Unable to push metadata.");
}
}
if (null != lastencoder) {
pushDataMessage(lastencoder, kafkaDataMessageAttributes);
if (parseAttributes && lastHadAttributes) {
// We need to push lastencoder's metadata update as they were updated since the last
// metadata update message sent
Metadata meta = new Metadata(lastencoder.getMetadata());
meta.setSource(Configuration.INGRESS_METADATA_UPDATE_ENDPOINT);
pushMetadataMessage(meta);
// Reset lastHadAttributes
lastHadAttributes = false;
}
}
if (encoder != lastencoder) {
// This is the case when we just parsed either the first input line or one for a different
// GTS than the previous one.
lastencoder = encoder;
} else {
// This is the case when lastencoder and encoder are identical, but lastencoder was too big and needed
// to be flushed
//lastencoder = null;
//
// Allocate a new GTSEncoder and reuse Metadata so we can
// correctly handle a continuation line if this is what occurs next
//
Metadata metadata = lastencoder.getMetadata();
lastencoder = new GTSEncoder(0L);
lastencoder.setMetadata(metadata);
}
}
if (0 == count % 1000) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_DATAPOINTS_RAW, sensisionLabels, count);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_DATAPOINTS_GLOBAL, Sensision.EMPTY_LABELS, count);
count = 0;
}
} while (true);
if (null != lastencoder && lastencoder.size() > 0) {
ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application, lastencoder.getClassId(), lastencoder.getLabelsId());
ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application, (int) lastencoder.getCount());
pushDataMessage(lastencoder, kafkaDataMessageAttributes);
if (parseAttributes && lastHadAttributes) {
// Push a metadata UPDATE message so attributes are stored
// Build metadata object to push
Metadata meta = new Metadata(lastencoder.getMetadata());
meta.setSource(Configuration.INGRESS_METADATA_UPDATE_ENDPOINT);
pushMetadataMessage(meta);
}
}
} catch (WarpException we) {
throw new IOException(we);
} finally {
//
// Flush message buffers into Kafka
//
pushMetadataMessage(null, null);
pushDataMessage(null, kafkaDataMessageAttributes);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_DATAPOINTS_RAW, sensisionLabels, count);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_DATAPOINTS_GLOBAL, Sensision.EMPTY_LABELS, count);
long micros = (System.nanoTime() - nano) / 1000L;
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_TIME_US, sensisionLabels, micros);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_UPDATE_TIME_US_GLOBAL, Sensision.EMPTY_LABELS, micros);
}
} catch (Throwable t) { // Catch everything else this handler could return 200 on a OOM exception
if (!response.isCommitted()) {
String msg = "Error when updating data: " + ThrowableUtils.getErrorMessage(t);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
return;
}
}
response.setStatus(HttpServletResponse.SC_OK);
}
/**
* Handle Metadata updating
*/
public void handleMeta(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (target.equals(Constants.API_ENDPOINT_META)) {
baseRequest.setHandled(true);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_REQUESTS, Sensision.EMPTY_LABELS, 1);
} else {
return;
}
if (null != WarpManager.getAttribute(WarpManager.META_DISABLED)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, String.valueOf(WarpManager.getAttribute(WarpManager.META_DISABLED)));
return;
}
//
// CORS header
//
response.setHeader("Access-Control-Allow-Origin", "*");
//
// Loop over the input lines.
// Each has the following format:
//
// class{labels}{attributes}
//
//
// TODO(hbs): Extract producer/owner from token
//
String token = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));
WriteToken writeToken;
try {
try {
writeToken = Tokens.extractWriteToken(token);
if (writeToken.getAttributesSize() > 0 && writeToken.getAttributes().containsKey(Constants.TOKEN_ATTR_NOMETA)) {
throw new WarpScriptException("Token cannot be used for updating metadata.");
}
} catch (WarpScriptException ee) {
throw new IOException(ee);
}
String application = writeToken.getAppName();
String producer = Tokens.getUUID(writeToken.getProducerId());
String owner = Tokens.getUUID(writeToken.getOwnerId());
if (null == producer || null == owner) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_INVALIDTOKEN, Sensision.EMPTY_LABELS, 1);
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
return;
}
Map<String,String> sensisionLabels = new HashMap<String,String>();
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);
if (null != application) {
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
}
long count = 0;
//
// Determine if content if gzipped
//
boolean gzipped = false;
if (null != request.getHeader("Content-Type") && "application/gzip".equals(request.getHeader("Content-Type"))) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_REQUESTS, Sensision.EMPTY_LABELS, 1);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_GZIPPED, sensisionLabels, 1);
gzipped = true;
}
BufferedReader br = null;
if (gzipped) {
GZIPInputStream is = new GZIPInputStream(request.getInputStream());
br = new BufferedReader(new InputStreamReader(is));
} else {
br = request.getReader();
}
long nowms = System.currentTimeMillis();
//
// Loop on all lines
//
while(true) {
String line = br.readLine();
if (null == line) {
break;
}
//
// Ignore blank lines
//
if ("".equals(line)) {
continue;
}
// Skip lines which start with '#'
if ('#' == line.charAt(0)) {
continue;
}
Metadata metadata = MetadataUtils.parseMetadata(line);
if (null == metadata) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_INVALID, sensisionLabels, 1);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid metadata " + line);
return;
}
// Add labels from the WriteToken if they exist
if (writeToken.getLabelsSize() > 0) {
metadata.getLabels().putAll(writeToken.getLabels());
}
//
// Force owner/producer
//
metadata.getLabels().put(Constants.PRODUCER_LABEL, producer);
metadata.getLabels().put(Constants.OWNER_LABEL, owner);
if (null != application) {
metadata.getLabels().put(Constants.APPLICATION_LABEL, application);
}
if (!MetadataUtils.validateMetadata(metadata)) {
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_INVALID, sensisionLabels, 1);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid metadata " + line);
return;
}
count++;
metadata.setSource(Configuration.INGRESS_METADATA_UPDATE_ENDPOINT);
try {
// We do not take into consideration this activity timestamp in the cache
// this way we do not allocate BigIntegers
if (activityTracking && metaActivity) {
metadata.setLastActivity(nowms);
}
pushMetadataMessage(metadata);
} catch (Exception e) {
throw new IOException("Unable to push metadata");
}
}
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_META_RECORDS, sensisionLabels, count);
} catch (Throwable t) { // Catch everything else this handler could return 200 on a OOM exception
if (!response.isCommitted()) {
String msg = "Error when updating meta: " + ThrowableUtils.getErrorMessage(t);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
return;
}
} finally {
//
// Flush message buffers into Kafka
//
pushMetadataMessage(null, null);
}
response.setStatus(HttpServletResponse.SC_OK);
}
public void handleDelete(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (target.equals(Constants.API_ENDPOINT_DELETE)) {
baseRequest.setHandled(true);
} else {
return;
}
if (this.rejectDelete) {
throw new IOException(Constants.API_ENDPOINT_DELETE + " endpoint is not activated.");
}
if (null != WarpManager.getAttribute(WarpManager.DELETE_DISABLED)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, String.valueOf(WarpManager.getAttribute(WarpManager.DELETE_DISABLED)));
return;
}
//
// CORS header
//
response.setHeader("Access-Control-Allow-Origin", "*");
long nano = System.nanoTime();
//
// Extract token infos
//
String token = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));
WriteToken writeToken;
try {
writeToken = Tokens.extractWriteToken(token);
if (writeToken.getAttributesSize() > 0 && writeToken.getAttributes().containsKey(Constants.TOKEN_ATTR_NODELETE)) {
throw new WarpScriptException("Token cannot be used for deletions.");
}
} catch (WarpScriptException ee) {
throw new IOException(ee);
}
String application = writeToken.getAppName();
String producer = Tokens.getUUID(writeToken.getProducerId());
String owner = Tokens.getUUID(writeToken.getOwnerId());
//
// For delete operations, producer and owner MUST be equal
//
if (!producer.equals(owner)) {
throw new IOException("Invalid write token for deletion.");
}
Map<String,String> sensisionLabels = new HashMap<String,String>();
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);
long count = 0;
long gts = 0;
boolean completeDeletion = false;
boolean dryrun = null != request.getParameter(Constants.HTTP_PARAM_DRYRUN);
boolean showErrors = null != request.getParameter(Constants.HTTP_PARAM_SHOW_ERRORS);
PrintWriter pw = null;
try {
if (null == producer || null == owner) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
return;
}
//
// Build extra labels
//
Map<String,String> extraLabels = new HashMap<String,String>();
// Add extra labels, remove producer,owner,app
if (writeToken.getLabelsSize() > 0) {
extraLabels.putAll(writeToken.getLabels());
extraLabels.remove(Constants.PRODUCER_LABEL);
extraLabels.remove(Constants.OWNER_LABEL);
extraLabels.remove(Constants.APPLICATION_LABEL);
}
//
// Only set owner and potentially app, producer may vary
//
extraLabels.put(Constants.OWNER_LABEL, owner);
if (null != application) {
extraLabels.put(Constants.APPLICATION_LABEL, application);
sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
}
boolean hasRange = false;
//
// Extract start/end
//
String startstr = request.getParameter(Constants.HTTP_PARAM_START);
String endstr = request.getParameter(Constants.HTTP_PARAM_END);
String minagestr = request.getParameter(Constants.HTTP_PARAM_MINAGE);
long start = Long.MIN_VALUE;
long end = Long.MAX_VALUE;
long minage = 0L;
if (null != minagestr) {
minage = Long.parseLong(minagestr);
if (minage < 0) {
throw new IOException("Invalid value for '" + Constants.HTTP_PARAM_MINAGE + "', expected a number of ms >= 0");
}
}
if (null != startstr) {
if (null == endstr) {
throw new IOException("Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END + " should be defined.");
}
if (startstr.contains("T")) {
if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) {
start = io.warp10.script.unary.TOTIMESTAMP.parseTimestamp(startstr);
} else {
start = fmt.parseDateTime(startstr).getMillis() * Constants.TIME_UNITS_PER_MS;
}
} else {
start = Long.valueOf(startstr);
}
}
if (null != endstr) {
if (null == startstr) {
throw new IOException("Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END + " should be defined.");
}
if (endstr.contains("T")) {
if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) {
end = io.warp10.script.unary.TOTIMESTAMP.parseTimestamp(endstr);
} else {
end = fmt.parseDateTime(endstr).getMillis() * Constants.TIME_UNITS_PER_MS;
}
} else {
end = Long.valueOf(endstr);
}
}
if (Long.MIN_VALUE == start && Long.MAX_VALUE == end && null == request.getParameter(Constants.HTTP_PARAM_DELETEALL)) {
throw new IOException("Parameter " + Constants.HTTP_PARAM_DELETEALL + " should be set when deleting a full range.");
}
if (start > end) {
throw new IOException("Invalid time range specification.");
}
//
// Extract selector
//
String selector = request.getParameter(Constants.HTTP_PARAM_SELECTOR);
//
// Extract the class and labels selectors
// The class selector and label selectors are supposed to have
// values which use percent encoding, i.e. explicit percent encoding which
// might have been re-encoded using percent encoding when passed as parameter
//
//
Matcher m = EgressFetchHandler.SELECTOR_RE.matcher(selector);
if (!m.matches()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
String classSelector = URLDecoder.decode(m.group(1), StandardCharsets.UTF_8.name());
String labelsSelection = m.group(2);
Map<String,String> labelsSelectors;
try {
labelsSelectors = GTSHelper.parseLabelsSelectors(labelsSelection);
} catch (ParseException pe) {
throw new IOException(pe);
}
//
// Force 'owner'/'app' from token
//
labelsSelectors.putAll(extraLabels);
List<Metadata> metadatas = null;
List<String> clsSels = new ArrayList<String>();
List<Map<String,String>> lblsSels = new ArrayList<Map<String,String>>();
clsSels.add(classSelector);
lblsSels.add(labelsSelectors);
response.setStatus(HttpServletResponse.SC_OK);
pw = response.getWriter();
StringBuilder sb = new StringBuilder();
//
// Shuffle only if not in dryrun mode
//
if (!dryrun && doShuffle) {
//
// Loop over the iterators, storing the read metadata to a temporary file encrypted on disk
// Data is encrypted using a onetime pad
//
final byte[] onetimepad = new byte[(int) Math.max(65537, System.currentTimeMillis() % 100000)];
new Random().nextBytes(onetimepad);
final File cache = File.createTempFile(Long.toHexString(System.currentTimeMillis()) + "-" + Long.toHexString(System.nanoTime()), ".delete.dircache");
cache.deleteOnExit();
FileWriter writer = new FileWriter(cache);
TSerializer serializer = new TSerializer(new TCompactProtocol.Factory());
DirectoryRequest drequest = new DirectoryRequest();
drequest.setClassSelectors(clsSels);
drequest.setLabelsSelectors(lblsSels);
try (MetadataIterator iterator = directoryClient.iterator(drequest)) {
while(iterator.hasNext()) {
Metadata metadata = iterator.next();
try {
byte[] bytes = serializer.serialize(metadata);
// Apply onetimepad
// We pad each line separately since we will later shuffle them!
int padidx = 0;
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) (bytes[i] ^ onetimepad[padidx++]);
if (padidx >= onetimepad.length) {
padidx = 0;
}
}
OrderPreservingBase64.encodeToWriter(bytes, writer);
writer.write('\n');
} catch (TException te) {
throw new IOException(te);
}
}
} catch (Exception e) {
try { writer.close(); } catch(IOException ioe) {}
cache.delete();
throw new IOException(e);
}
writer.close();
//
// Shuffle the content of the file
//
final File shuffled = File.createTempFile(Long.toHexString(System.currentTimeMillis()) + "-" + Long.toHexString(System.nanoTime()), ".delete.shuffled");
shuffled.deleteOnExit();
TextFileShuffler shuffler = new TextFileShuffler(new SortConfig().withMaxMemoryUsage(1000000L));
InputStream in = new FileInputStream(cache);
OutputStream out = new FileOutputStream(shuffled);
try {
shuffler.sort(in, out);
} catch (Exception e) {
try { in.close(); } catch (IOException ioe) {}
try { out.close(); } catch (IOException ioe) {}
shuffler.close();
shuffled.delete();
cache.delete();
throw new IOException(e);
}
shuffler.close();
out.close();
in.close();
// Delete the unshuffled file
cache.delete();
//
// Create an iterator based on the shuffled cache
//
final AtomicReference<Throwable> error = new AtomicReference<Throwable>(null);
MetadataIterator shufflediterator = new MetadataIterator() {
BufferedReader reader = new BufferedReader(new FileReader(shuffled));
private Metadata current = null;
private boolean done = false;
private TDeserializer deserializer = new TDeserializer(new TCompactProtocol.Factory());
@Override
public boolean hasNext() {
if (done) {
return false;
}
if (null != current) {
return true;
}
try {
String line = reader.readLine();
if (null == line) {
done = true;
return false;
}
byte[] raw = OrderPreservingBase64.decode(line.getBytes(StandardCharsets.US_ASCII));
// Apply one time pad
int padidx = 0;
for (int i = 0; i < raw.length; i++) {
raw[i] = (byte) (raw[i] ^ onetimepad[padidx++]);
if (padidx >= onetimepad.length) {
padidx = 0;
}
}
Metadata metadata = new Metadata();
try {
deserializer.deserialize(metadata, raw);
this.current = metadata;
return true;
} catch (TException te) {
error.set(te);
LOG.error("", te);
}
} catch (IOException ioe) {
error.set(ioe);
LOG.error("", ioe);
}
return false;
}
@Override
public Metadata next() {
if (null != this.current) {
Metadata metadata = this.current;
this.current = null;
return metadata;
} else {
throw new NoSuchElementException();
}
}
@Override
public void close() throws Exception {
this.reader.close();
shuffled.delete();
}
};
try {
while(shufflediterator.hasNext()) {
Metadata metadata = shufflediterator.next();
if (!dryrun) {
pushDeleteMessage(start, end, minage, metadata);
if (Long.MAX_VALUE == end && Long.MIN_VALUE == start && 0 == minage) {
completeDeletion = true;
// We must also push the metadata deletion and remove the metadata from the cache
Metadata meta = new Metadata(metadata);
meta.setSource(Configuration.INGRESS_METADATA_DELETE_SOURCE);
pushMetadataMessage(meta);
byte[] bytes = new byte[16];
// We know class/labels Id were computed in pushMetadataMessage
GTSHelper.fillGTSIds(bytes, 0, meta.getClassId(), meta.getLabelsId());
BigInteger key = new BigInteger(bytes);
synchronized(this.metadataCache) {
this.metadataCache.remove(key);
}
}
}
sb.setLength(0);
GTSHelper.metadataToString(sb, metadata.getName(), metadata.getLabels());
if (metadata.getAttributesSize() > 0) {
GTSHelper.labelsToString(sb, metadata.getAttributes());
} else {
sb.append("{}");
}
pw.write(sb.toString());
pw.write("\r\n");
gts++;
}
if (null != error.get()) {
throw error.get();
}
} finally {
try { shufflediterator.close(); } catch (Exception e) {}
}
} else {
DirectoryRequest drequest = new DirectoryRequest();
drequest.setClassSelectors(clsSels);
drequest.setLabelsSelectors(lblsSels);
try (MetadataIterator iterator = directoryClient.iterator(drequest)) {
while(iterator.hasNext()) {
Metadata metadata = iterator.next();
if (!dryrun) {
pushDeleteMessage(start, end, minage, metadata);
if (Long.MAX_VALUE == end && Long.MIN_VALUE == start && 0 == minage) {
completeDeletion = true;
// We must also push the metadata deletion and remove the metadata from the cache
Metadata meta = new Metadata(metadata);
meta.setSource(Configuration.INGRESS_METADATA_DELETE_SOURCE);
pushMetadataMessage(meta);
byte[] bytes = new byte[16];
// We know class/labels Id were computed in pushMetadataMessage
GTSHelper.fillGTSIds(bytes, 0, meta.getClassId(), meta.getLabelsId());
BigInteger key = new BigInteger(bytes);
synchronized(this.metadataCache) {
this.metadataCache.remove(key);
}
}
}
sb.setLength(0);
GTSHelper.metadataToString(sb, metadata.getName(), metadata.getLabels());
if (metadata.getAttributesSize() > 0) {
GTSHelper.labelsToString(sb, metadata.getAttributes());
} else {
sb.append("{}");
}
pw.write(sb.toString());
pw.write("\r\n");
gts++;
}
} catch (Exception e) {
throw new IOException(e);
}
}
} catch (Throwable t) {
LOG.error("",t);
Sensision.update(SensisionConstants.CLASS_WARP_INGRESS_DELETE_ERRORS, Sensision.EMPTY_LABELS, 1);
if (showErrors && null != pw) {
pw.println();
StringWriter sw = new StringWriter();
PrintWriter pw2 = new PrintWriter(sw);
t.printStackTrace(pw2);
pw2.close();
sw.flush();
String error = URLEncoder.encode(sw.toString(), StandardCharsets.UTF_8.name());
pw.println(Constants.INGRESS_DELETE_ERROR_PREFIX + error);
}
if (!response.isCommitted()) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.getMessage());
}
return;
} finally {
// Flush delete messages
if (!dryrun) {
pushDeleteMessage(0L,0L,0L,null);
if (completeDeletion) {
pushMetadataMessage(null, null);
}
}
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_DELETE_REQUESTS, sensisionLabels, 1);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_DELETE_GTS, sensisionLabels, gts);
}
response.setStatus(HttpServletResponse.SC_OK);
}
/**
* Extract Ingress related keys and populate the KeyStore with them.
*
* @param props Properties from which to extract the key specs
*/
private void extractKeys(KeyStore keystore, Properties props) {
String keyspec = props.getProperty(Configuration.INGRESS_KAFKA_META_MAC);
if (null != keyspec) {
byte[] key = keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length, "Key " + Configuration.INGRESS_KAFKA_META_MAC + " MUST be 128 bits long.");
keystore.setKey(KeyStore.SIPHASH_KAFKA_METADATA, key);
}
keyspec = props.getProperty(Configuration.INGRESS_KAFKA_DATA_MAC);
if (null != keyspec) {
byte[] key = keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length, "Key " + Configuration.INGRESS_KAFKA_DATA_MAC + " MUST be 128 bits long.");
keystore.setKey(KeyStore.SIPHASH_KAFKA_DATA, key);
}
keyspec = props.getProperty(Configuration.INGRESS_KAFKA_META_AES);
if (null != keyspec) {
byte[] key = keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length || 24 == key.length || 32 == key.length, "Key " + Configuration.INGRESS_KAFKA_META_AES + " MUST be 128, 192 or 256 bits long.");
keystore.setKey(KeyStore.AES_KAFKA_METADATA, key);
}
keyspec = props.getProperty(Configuration.INGRESS_KAFKA_DATA_AES);
if (null != keyspec) {
byte[] key = keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length || 24 == key.length || 32 == key.length, "Key " + Configuration.INGRESS_KAFKA_DATA_AES + " MUST be 128, 192 or 256 bits long.");
keystore.setKey(KeyStore.AES_KAFKA_DATA, key);
}
keyspec = props.getProperty(Configuration.DIRECTORY_PSK);
if (null != keyspec) {
byte[] key = this.keystore.decodeKey(keyspec);
Preconditions.checkArgument(16 == key.length, "Key " + Configuration.DIRECTORY_PSK + " MUST be 128 bits long.");
this.keystore.setKey(KeyStore.SIPHASH_DIRECTORY_PSK, key);
}
this.keystore.forget();
}
void pushMetadataMessage(Metadata metadata) throws IOException {
if (null == metadata) {
pushMetadataMessage(null, null);
return;
}
//
// Compute class/labels Id
//
// 128bits
metadata.setClassId(GTSHelper.classId(this.classKey, metadata.getName()));
metadata.setLabelsId(GTSHelper.labelsId(this.labelsKey, metadata.getLabels()));
TSerializer serializer = new TSerializer(new TCompactProtocol.Factory());
try {
byte[] bytes = new byte[16];
GTSHelper.fillGTSIds(bytes, 0, metadata.getClassId(), metadata.getLabelsId());
pushMetadataMessage(bytes, serializer.serialize(metadata));
} catch (TException te) {
throw new IOException("Unable to push metadata.");
}
}
/**
* Push a metadata message onto the buffered list of Kafka messages
* and flush the list to Kafka if it has reached a threshold.
*
* @param key Key of the message to queue
* @param value Value of the message to queue
*/
private void pushMetadataMessage(byte[] key, byte[] value) throws IOException {
AtomicLong mms = this.metadataMessagesSize.get();
List<KeyedMessage<byte[], byte[]>> msglist = this.metadataMessages.get();
if (null != key && null != value) {
//
// Add key as a prefix of value
//
byte[] kv = Arrays.copyOf(key, key.length + value.length);
System.arraycopy(value, 0, kv, key.length, value.length);
value = kv;
//
// Encrypt value if the AES key is defined
//
if (null != this.AES_KAFKA_META) {
value = CryptoUtils.wrap(this.AES_KAFKA_META, value);
}
//
// Compute MAC if the SipHash key is defined
//
if (null != this.SIPHASH_KAFKA_META) {
value = CryptoUtils.addMAC(this.SIPHASH_KAFKA_META, value);
}
KeyedMessage<byte[], byte[]> message = new KeyedMessage<byte[], byte[]>(this.metaTopic, Arrays.copyOf(key, key.length), value);
msglist.add(message);
mms.addAndGet(key.length + value.length);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_META_MESSAGES, Sensision.EMPTY_LABELS, 1);
}
if (msglist.size() > 0 && (null == key || null == value || mms.get() > METADATA_MESSAGES_THRESHOLD)) {
Producer<byte[],byte[]> producer = this.metaProducerPool.getProducer();
try {
//
// How long it takes to send messages to Kafka
//
long nano = System.nanoTime();
producer.send(msglist);
nano = System.nanoTime() - nano;
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_METADATA_PRODUCER_SEND, Sensision.EMPTY_LABELS, nano);
} catch (Throwable t) {
//
// We need to remove the IDs of Metadata in 'msglist' from the cache so they get a chance to be
// pushed later
//
for (KeyedMessage<byte[],byte[]> msg: msglist) {
synchronized(this.metadataCache) {
this.metadataCache.remove(new BigInteger(msg.key()));
}
}
throw t;
} finally {
this.metaProducerPool.recycleProducer(producer);
}
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_META_SEND, Sensision.EMPTY_LABELS, 1);
msglist.clear();
mms.set(0L);
// Update sensision metric with size of metadata cache
Sensision.set(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_METADATA_CACHED, Sensision.EMPTY_LABELS, this.metadataCache.size());
}
}
/**
* Push a metadata message onto the buffered list of Kafka messages
* and flush the list to Kafka if it has reached a threshold.
*
* @param encoder GTSEncoder to push to Kafka. It MUST have classId/labelsId set.
*/
void pushDataMessage(GTSEncoder encoder, Map<String,String> attributes) throws IOException {
if (null != encoder) {
KafkaDataMessage msg = new KafkaDataMessage();
msg.setType(KafkaDataMessageType.STORE);
msg.setData(encoder.getBytes());
msg.setClassId(encoder.getClassId());
msg.setLabelsId(encoder.getLabelsId());
if (this.sendMetadataOnStore) {
msg.setMetadata(encoder.getMetadata());
}
if (null != attributes && !attributes.isEmpty()) {
msg.setAttributes(new HashMap<String,String>(attributes));
}
sendDataMessage(msg);
} else {
sendDataMessage(null);
}
}
private void sendDataMessage(KafkaDataMessage msg) throws IOException {
AtomicLong dms = this.dataMessagesSize.get();
List<KeyedMessage<byte[], byte[]>> msglist = this.dataMessages.get();
if (null != msg) {
//
// Build key
//
byte[] bytes = new byte[16];
GTSHelper.fillGTSIds(bytes, 0, msg.getClassId(), msg.getLabelsId());
//ByteBuffer bb = ByteBuffer.wrap(new byte[16]).order(ByteOrder.BIG_ENDIAN);
//bb.putLong(encoder.getClassId());
//bb.putLong(encoder.getLabelsId());
TSerializer serializer = new TSerializer(new TCompactProtocol.Factory());
byte[] msgbytes = null;
try {
msgbytes = serializer.serialize(msg);
} catch (TException te) {
throw new IOException(te);
}
//
// Encrypt value if the AES key is defined
//
if (null != this.aesDataKey) {
msgbytes = CryptoUtils.wrap(this.aesDataKey, msgbytes);
}
//
// Compute MAC if the SipHash key is defined
//
if (null != this.siphashDataKey) {
msgbytes = CryptoUtils.addMAC(this.siphashDataKey, msgbytes);
}
//KeyedMessage<byte[], byte[]> message = new KeyedMessage<byte[], byte[]>(this.dataTopic, bb.array(), msgbytes);
KeyedMessage<byte[], byte[]> message = new KeyedMessage<byte[], byte[]>(this.dataTopic, bytes, msgbytes);
msglist.add(message);
//this.dataMessagesSize.get().addAndGet(bb.array().length + msgbytes.length);
dms.addAndGet(bytes.length + msgbytes.length);
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_MESSAGES, Sensision.EMPTY_LABELS, 1);
}
if (msglist.size() > 0 && (null == msg || dms.get() > DATA_MESSAGES_THRESHOLD)) {
Producer<byte[],byte[]> producer = getDataProducer();
//this.dataProducer.send(msglist);
try {
//
// How long it takes to send messages to Kafka
//
long nano = System.nanoTime();
producer.send(msglist);
nano = System.nanoTime() - nano;
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_PRODUCER_SEND, Sensision.EMPTY_LABELS, nano);
} catch (Throwable t) {
throw t;
} finally {
recycleDataProducer(producer);
}
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_SEND, Sensision.EMPTY_LABELS, 1);
msglist.clear();
dms.set(0L);
}
}
private Producer<byte[],byte[]> getDataProducer() {
//
// We will count how long we wait for a producer
//
long nano = System.nanoTime();
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_PRODUCER_POOL_GET, Sensision.EMPTY_LABELS, 1);
while(true) {
synchronized (this.dataProducers) {
if (this.dataProducersCurrentPoolSize > 0) {
//
// hand out the producer at index 0
//
Producer<byte[],byte[]> producer = this.dataProducers[0];
//
// Decrement current pool size
//
this.dataProducersCurrentPoolSize--;
//
// Move the last element of the array at index 0
//
this.dataProducers[0] = this.dataProducers[this.dataProducersCurrentPoolSize];
this.dataProducers[this.dataProducersCurrentPoolSize] = null;
//
// Log waiting time
//
nano = System.nanoTime() - nano;
Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_INGRESS_KAFKA_DATA_PRODUCER_WAIT_NANO, Sensision.EMPTY_LABELS, nano);
return producer;
}
}
LockSupport.parkNanos(500000L);
}
}
private void recycleDataProducer(Producer<byte[],byte[]> producer) {
if (this.dataProducersCurrentPoolSize == this.dataProducers.length) {
throw new RuntimeException("Invalid call to recycleProducer, pool already full!");
}
synchronized (this.dataProducers) {
//
// Add the recycled producer at the end of the pool
//
this.dataProducers[this.dataProducersCurrentPoolSize++] = producer;
}
}
/**
* Push a deletion message onto the buffered list of Kafka messages
* and flush the list to Kafka if it has reached a threshold.
*
* Deletion messages MUST be pushed onto the data topic, otherwise the
* ordering won't be respected and you risk deleting a GTS which has been
* since repopulated with data.
*
* @param start Start timestamp for deletion
* @param end End timestamp for deletion
* @param metadata Metadata of the GTS to delete
*/
private void pushDeleteMessage(long start, long end, long minage, Metadata metadata) throws IOException {
if (null != metadata) {
KafkaDataMessage msg = new KafkaDataMessage();
msg.setType(KafkaDataMessageType.DELETE);
msg.setDeletionStartTimestamp(start);
msg.setDeletionEndTimestamp(end);
msg.setDeletionMinAge(minage);
msg.setClassId(metadata.getClassId());
msg.setLabelsId(metadata.getLabelsId());
if (this.sendMetadataOnDelete) {
msg.setMetadata(metadata);
}
sendDataMessage(msg);
} else {
sendDataMessage(null);
}
}
private void dumpCache() {
if (null == this.cacheDumpPath) {
return;
}
OutputStream out = null;
long nano = System.nanoTime();
long count = 0;
try {
out = new GZIPOutputStream(new FileOutputStream(this.cacheDumpPath));
Set<BigInteger> bis = new HashSet<BigInteger>();
synchronized(this.metadataCache) {
bis.addAll(this.metadataCache.keySet());
}
Iterator<BigInteger> iter = bis.iterator();
//
// 128bits
//
byte[] allzeroes = new byte[16];
Arrays.fill(allzeroes, (byte) 0);
byte[] allones = new byte[16];
Arrays.fill(allones, (byte) 0xff);
while (true) {
try {
if (!iter.hasNext()) {
break;
}
BigInteger bi = iter.next();
byte[] raw = bi.toByteArray();
//
// 128bits
//
if (raw.length != 16) {
if (bi.signum() < 0) {
out.write(allones, 0, 16 - raw.length);
} else {
out.write(allzeroes, 0, 16 - raw.length);
}
}
out.write(raw);
if (this.activityTracking) {
Long lastActivity = this.metadataCache.get(bi);
byte[] bytes;
if (null != lastActivity) {
bytes = Longs.toByteArray(lastActivity);
} else {
bytes = new byte[8];
}
out.write(bytes);
}
count++;
} catch (ConcurrentModificationException cme) {
}
}
} catch (IOException ioe) {
} finally {
if (null != out) {
try { out.close(); } catch (Exception e) {}
}
}
nano = System.nanoTime() - nano;
LOG.info("Dumped " + count + " cache entries in " + (nano / 1000000.0D) + " ms.");
}
private void loadCache() {
if (null == this.cacheDumpPath) {
return;
}
InputStream in = null;
byte[] buf = new byte[8192];
long nano = System.nanoTime();
long count = 0;
try {
in = new GZIPInputStream(new FileInputStream(this.cacheDumpPath));
int offset = 0;
// 128 bits
int reclen = this.activityTracking ? 24 : 16;
byte[] raw = new byte[16];
while(true) {
int len = in.read(buf, offset, buf.length - offset);
offset += len;
int idx = 0;
while(idx < offset && offset - idx >= reclen) {
System.arraycopy(buf, idx, raw, 0, 16);
BigInteger id = new BigInteger(raw);
if (this.activityTracking) {
long lastActivity = 0L;
for (int i = 0; i < 8; i++) {
lastActivity <<= 8;
lastActivity |= ((long) buf[idx + 16 + i]) & 0xFFL;
}
synchronized(this.metadataCache) {
this.metadataCache.put(id, lastActivity);
}
} else {
synchronized(this.metadataCache) {
this.metadataCache.put(id, null);
}
}
count++;
idx += reclen;
}
if (idx < offset) {
for (int i = idx; i < offset; i++) {
buf[i - idx] = buf[i];
}
offset = offset - idx;
} else {
offset = 0;
}
if (len < 0) {
break;
}
}
} catch (IOException ioe) {
} finally {
if (null != in) {
try { in.close(); } catch (Exception e) {}
}
}
nano = System.nanoTime() - nano;
LOG.info("Loaded " + count + " cache entries in " + (nano / 1000000.0D) + " ms.");
}
}
| Added safety net around cache dump
| warp10/src/main/java/io/warp10/continuum/ingress/Ingress.java | Added safety net around cache dump | <ide><path>arp10/src/main/java/io/warp10/continuum/ingress/Ingress.java
<ide> Set<BigInteger> bis = new HashSet<BigInteger>();
<ide>
<ide> synchronized(this.metadataCache) {
<del> bis.addAll(this.metadataCache.keySet());
<add> boolean error = false;
<add> do {
<add> try {
<add> error = false;
<add> bis.addAll(this.metadataCache.keySet());
<add> } catch (ConcurrentModificationException cme) {
<add> error = true;
<add> }
<add> } while (error);
<ide> }
<ide>
<ide> Iterator<BigInteger> iter = bis.iterator(); |
|
Java | unlicense | 96681f63efb008f1df961f36b1a3fdd0210fd8a0 | 0 | Ghostkeeper/hattusa | /**
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or distribute
* this software, either in source code form or as a compiled binary, for any
* purpose, commercial or non-commercial, and by any means.
*
* In jurisdictions that recognize copyright laws, the author or authors of this
* software dedicate any and all copyright interest in the software to the
* public domain. We make this dedication for the benefit of the public at large
* and to the detriment of our heirs and successors. We intend this dedication
* to be an overt act of relinquishment in perpetuity of all present and future
* rights to this software under copyright law.
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.dulek.collections;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.*;
/**
* This class represents a set of elements, implemented using a hash table. A
* set is an unordered collection of elements, containing no duplicate elements.
* Being unordered, the set makes no guarantees as to the order of its elements.
* This set is unsynchronised, and permits the {@code null} element.
* <p>This implementation is heavily based on the default
* {@link java.util.HashMap HashMap} implementation of Java 7, but some
* improvements were made to better facilitate sets rather than key-value
* mappings, since the default implementation of {@link HashSet} maintains a
* heavy-weight {@code HashMap} to implement the set. Additionally, the default
* implementation provides two ways of hashing its keys: the standard
* {@code hashCode()} method of the keys or a cryptographically more secure
* variant for {@code String}s that uses a random seed. This implementation
* foregoes the latter hashing method, making it potentially more vulnerable to
* collision attacks. Lastly, the default implementation uses the separate
* chaining method for preventing collisions. In an effort to rid the
* implementation from additional "entry" instances, separate chaining is
* infeasable. Instead, open addressing with quadratic probing was chosen.
* Quadratic probing avoids the clustering problem better than linear probing
* and in Java the locality of reference makes no difference. It was chosen over
* more complex collision resolution techniques for how it requires less memory
* overhead.</p>
* <p>This implementation provides expected constant-time performance for all
* basic operations of the set: {@link #add(E)}, {@link #remove(Object)} and
* {@link #contains(Object)}. This expected performance expects that the hash
* function disperses the elements properly among the buckets. Iteration over
* the set requires time proportional to the "capacity" of the hash table (the
* number of buckets) plus its size (the number of elements). Thus, it's very
* important not to set the initial capacity too high (or the load factor too
* low) if iteration performance is important.</p>
* <p>An instance of {@code HashSet} has two parameters that affect its
* performance: the initial capacity and the load factor. The capacity is the
* number of buckets in the hash table, and the initial capacity is simply the
* capacity at the time the hash table is created. The load factor is a measure
* of how full the hash table is allowed to get before its capacity is
* automatically increased. When the number of entries in the hash table exceeds
* the product of the load factor and the current capacity, the hash table is
* rehashed, meaning all elements will be distributed over a new table. The new
* table will be approximately twice the size of the old table.</p>
* <p>As a general rule, the default load factor offers a good tradeoff between
* time and space costs. Higher values reduce the space overhead but increase
* the time cost of the basic operations. Lower values increase the memory
* requirement but reduce the time cost. The expected number of entries in the
* set and its load factor should be taken into account when setting its initial
* capacity, so as to minimise the number of rehash operations. If the initial
* capacity is greater than the maximum number of entries divided by the load
* factor, no rehash operations will ever occur. The load factor cannot exceed
* {@code 1} in this implementation, since there can be only one element in each
* bucket.</p>
* <p>If many elements are to be stored in a {@code HashSet} instance, creating
* it with a sufficiently large capacity will allow the elements to be stored
* more efficiently than letting it perform automatic rehashing as needed to
* grow the table.</p>
* <p>Note that this implementation is not synchronised. If multiple threads
* access the {@code HashSet} concurrently, and at least one of these threads
* modifies the map structurally, it must be synchronised externally. A
* structural modification is any operation that adds or removes one or more
* elements. This is typically accomplished by synchronising on some object that
* naturally encapsulates the set. If no such object exists, the set should be
* "wrapped" using the
* {@link java.util.Collections#synchronizedSet Collections.synchronizedSet}
* methods. This is best done at creation time, to prevent accidental
* unsynchronised access to the set:
* {@code Set<...> s = Collections.synchronizedSet(new HashSet<>(...));}</p>
* <p>The iterators returned by this class's {@link #iterator()} method are
* fail-fast: if the set is structurally modified at any time after the iterator
* is created, in any way except through the iterator's own
* {@link Iterator#remove()} method, the {@code Iterator} throws a
* {@link ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behaviour at an undetermined time in the future.
* </p>
* <p>Note that the fail-fast behaviour of an iterator cannot be guaranteed as
* it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronised concurrent modification. Fail-fast iterators throw
* {@code ConcurrentModificationException}s on a best-effort basis. Therefore,
* it would be wrong to write a program that depended on this exception for its
* correctness: the fail-fast behaviour of iterators should only be used to
* detect bugs.</p>
* @author Ruben Dulek
* @param <E> The types of elements stored in this set.
* @see Collection
* @see java.util.HashMap
* @see Set
* @version 1.0
*/
public class HashSet<E> implements Set<E>,Cloneable,Serializable {
/**
* The default initial capacity of the hash table. This will be the initial
* capacity of the hash table if no initial capacity is specified in the
* constructing of the set. It must be a power of two, so keep the bitshift
* operator in this value, please.
*/
protected static final int defaultInitialCapacity = 1 << 4;
/**
* The default load factor. This will be the load factor if none is
* specified in the constructing of the set. A value of 0.7 is a good
* trade-off between memory usage and time cost. Must be between {@code 0}
* and {@code 1}.
*/
protected static final float defaultLoadFactor = 0.7f;
/**
* The load factor for the hash table. This indicates the maximum fraction
* of buckets that can be filled before the table is rehashed to a bigger
* table.
* @serial The factor is converted to a {@code String} via
* {@code Float.toString(loadFactor)}.
*/
protected float loadFactor;
/**
* The maximum capacity of the table. This is used if a higher value is
* implicity specified by either of the constructors with arguments. It must
* be a power of two, so keep the bitshift operator in this value, please.
*/
protected static final int maximumCapacity = 1 << 30;
/**
* The number of times this {@code HashSet} has been structurally modified.
* Structural modifications are those that change the number of elements in
* the set or otherwise modify its internal structure (e.g. a rehash). This
* field is used to make iterators over the set fail-fast.
*/
protected transient int modCount;
/**
* This object represents the {@code null}-element. If it is in the set, the
* set contains the {@code null}-element. Methods that allow access to the
* actual elements of the set (such as {@link Iterator#next()}) should mind
* not to return this object, but return {@code null} instead.
*/
protected static final Object nullElement = new Object();
/**
* The version of the serialised format of the set. This identifies a
* serialisation as being the serialised format of this class.
*/
private static final long serialVersionUID = 4882436748081726100L;
/**
* The number of elements in this set.
*/
protected transient int size;
/**
* The actual hash table. Its length must always be a power of two. The
* table will be resized as necessary, rehashing every element in it.
*/
protected transient Object[] table;
/**
* When an element is removed, it will be replaced by a tombstone, marking
* that the bucket used to contain an element, and that there might still be
* elements after the tombstone belonging to buckets before the tombstone.
*/
protected static final Object tombstone = new Object();
/**
* The next size value at which to resize and rehash the table. It will be
* kept at {@code table.length * loadFactor}.
*/
protected int treshold;
/**
* Constructs an empty {@code HashSet} with the default initial capacity
* (16) and the default load factor (0.7). Note that it is good practice to
* always specify an initial capacity if there is any idea of approximately
* how many elements the set will hold.
*/
public HashSet() {
loadFactor = defaultLoadFactor;
treshold = (int)(defaultInitialCapacity * defaultLoadFactor); //Pre-compute the treshold.
table = new Object[defaultInitialCapacity]; //Reserve the actual table.
}
/**
* Constructs an empty {@code HashSet} with the specified initial capacity
* and the default load factor (0.7).
* @param initialCapacity The initial capacity of the hash table.
* @throws IllegalArgumentException The initial capacity is negative.
*/
public HashSet(int initialCapacity) {
if(initialCapacity <= 0) {
throw new IllegalArgumentException("The initial capacity of " + initialCapacity + " is negative.");
}
if(initialCapacity > maximumCapacity) {
initialCapacity = maximumCapacity;
}
initialCapacity = net.dulek.math.Math.roundUpPower2(initialCapacity); //Find the next power of 2 greater than or equal to initialCapacity.
loadFactor = defaultLoadFactor;
treshold = Math.min((int)(initialCapacity * loadFactor),maximumCapacity + 1); //Pre-compute the treshold.
table = new Object[initialCapacity]; //Reserve the actual table.
}
/**
* Constructs an empty {@code HashSet} with the specified initial capacity
* and load factor.
* @param initialCapacity The initial capacity of the hash table.
* @param loadFactor The load factor.
* @throws IllegalArgumentException The initial capacity is negative or the
* load factor is not positive.
*/
public HashSet(int initialCapacity,final float loadFactor) {
if(initialCapacity < 0) {
throw new IllegalArgumentException("The initial capacity of " + initialCapacity + " is negative.");
}
if(initialCapacity > maximumCapacity) {
initialCapacity = maximumCapacity;
}
if(loadFactor <= 0 || Float.isNaN(loadFactor)) {
throw new IllegalArgumentException("The load factor of " + loadFactor + " is not positive.");
}
if(loadFactor >= 1) {
throw new IllegalArgumentException("The load factor of " + loadFactor + " is too high.");
}
initialCapacity = net.dulek.math.Math.roundUpPower2(initialCapacity); //Find the next power of 2 greater than or equal to initialCapacity.
this.loadFactor = loadFactor;
treshold = Math.min((int)(initialCapacity * loadFactor),maximumCapacity + 1); //Pre-compute the treshold.
table = new Object[initialCapacity]; //Reserve the actual table.
}
/**
* Constructs a new set containing the elements in the specified collection.
* The set is created with a default load factor (0.7) and an initial
* capacity sufficient to contain the elements in the specified collection.
* @param c The collection whose elements are to be placed into this set.
* @throws NullPointerException The specified collection is {@code null}.
*/
public HashSet(final Collection<? extends E> c) {
if(c == null) {
throw new NullPointerException("The specified collection to initialise the set with is null.");
}
loadFactor = defaultLoadFactor;
final int initialCapacity = net.dulek.math.Math.roundUpPower2(Math.max((int)(c.size() / defaultLoadFactor),defaultInitialCapacity)); //Make the capacity enough for all elements but no lower than the default initial capacity.
treshold = Math.min((int)(initialCapacity * defaultLoadFactor),maximumCapacity + 1); //Pre-compute the treshold.
table = new Object[initialCapacity]; //Reserve the actual table.
//Add all elements of the collection.
final int tMax = initialCapacity - 1;
ADDALL:
for(E element : c) { //Add all elements from the collection.
Object object = element;
if(object == null) { //Don't try to add null. Add the object representing null instead.
object = nullElement;
}
//Compute the desired bucket for the element.
final int hash = object.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples are at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
int offset = 1; //By how much we must grow the index while searching. Index grows quadratically.
Object elem;
//Search for the element.
while((elem = table[index]) != null) {
if(elem.hashCode() == hash && elem.equals(object)) { //The element is already in the table.
continue ADDALL; //Skip this element. Continue with the next one.
}
index = (index + offset++) & tMax;
}
//table[index] is now null (since the while loop ended) so this is a free spot.
table[index] = object; //Place it at our free spot.
modCount++;
}
}
/**
* Creates a hash set from a clone operation. The provided parameters are
* stored literally in the fields.
* @param loadFactor The load factor.
* @param size The number of elements in the set.
* @param table The hash table for the set.
*/
private HashSet(final float loadFactor,final int size,final Object[] table) {
this.loadFactor = loadFactor;
this.size = size;
this.table = table;
treshold = Math.min((int)(table.length * loadFactor),maximumCapacity + 1);
}
/**
* Adds the specified element to this set if it is not already present. More
* formally, adds the specified element {@code e} to this set if this set
* contains no element {@code f} such that
* {@code (e == null ? f == null : e.equals(f))}. If this set already
* contains the element, the call leaves the set unchanged and returns
* {@code false}.
* @param element The element to be added to this set.
* @return {@code true} if this set did not already contain the specified
* element, or {@code false} otherwise.
*/
@Override
public boolean add(final E element) {
Object object = element;
if(object == null) { //Don't try to add null. Add the object representing null instead.
object = nullElement;
}
final int tMax = table.length - 1;
//Compute the desired bucket for the element.
final int hash = object.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples are at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
int offset = 1; //By how much we must grow the index while searching. Index grows quadratically.
Object elem;
//Search for the element.
while((elem = table[index]) != null) {
if(elem == tombstone) { //There was an object here...
//Continue the search, but no more gravedigging.
int searchIndex = (index + offset++) & tMax;
while((elem = table[searchIndex]) != null) {
if(elem.hashCode() == hash && elem.equals(object)) { //The element is already in the table.
return false;
}
searchIndex = (searchIndex + offset++) & tMax;
}
table[index] = object; //Place it at the tombstone.
modCount++;
if(++size > treshold) { //Getting too big.
resize(table.length << 1);
}
return true;
}
if(elem.hashCode() == hash && elem.equals(object)) { //The element is already in the table.
return false;
}
index = (index + offset++) & tMax;
}
//table[index] is now null (since the while loop ended) so this is a free spot.
table[index] = object; //Place it at our free spot.
modCount++;
if(++size > treshold) { //Getting too big.
resize(table.length << 1);
}
return true;
}
/**
* Adds all of the elements in the specified collection to this set. If the
* specified collection is this set, a
* {@link ConcurrentModificationException} is thrown.
* <p>This implementation iterates over the specified collection, and adds
* each object returned by the iterator to this collection, in turn.</p>
* @param c The collection containing elements to be added to this set.
* @return {@code true} if this set changed as a result of the call.
* @throws NullPointerException The specified collection is {@code null}.
*/
@Override
public boolean addAll(final Collection<? extends E> c) {
if(c == null) {
throw new NullPointerException("The specified collection to add to the set is null.");
}
//Make sure we have enough capacity, even if they're all new elements.
if(size + c.size() >= treshold) {
if(table.length == maximumCapacity) { //We're already at maximum capacity. Don't trigger this again.
treshold = Integer.MAX_VALUE;
} else {
final int newCapacity = net.dulek.math.Math.roundUpPower2((int)((size + c.size()) / loadFactor));
resize(newCapacity);
//Add all elements, but don't check for tombstones or the treshold (since we just rehashed everything anyways).
boolean modified = false;
final int tMax = newCapacity - 1;
ADDINGALL:
for(Object element : c) {
if(element == null) { //Don't try to add null. Add the object representing null instead.
element = nullElement;
}
//Compute the desired bucket for the element.
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples are at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
int offset = 1; //By how much we must grow the index while searching. Index grows quadratically.
Object elem;
//Search for the element.
while((elem = table[index]) != null) {
if(elem.hashCode() == hash && elem.equals(element)) { //The element is already in the table.
continue ADDINGALL; //Continue with the next element.
}
index = (index + offset++) & tMax;
}
//table[index] is now null (since the while loop ended) so this is a free spot.
table[index] = element; //Place it at our free spot.
size++;
modified = true;
}
if(modified) {
modCount++;
return true;
}
return false;
}
}
//Add all elements, but keep checking for tombstones.
boolean modified = false;
for(E element : c) { //Add all elements from the collection.
modified |= add(element);
}
return modified;
}
/**
* Removes all of the elements from this set. The set will be empty after
* this call returns.
*/
@Override
public void clear() {
modCount++;
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
for(int i = t.length - 1;i >= 0;i--) {
t[i] = null; //Erase the table.
}
size = 0;
}
/**
* Returns a shallow copy of this {@code HashSet} instance: The elements
* themselves are not cloned.
* @return A shallow copy of this set.
* @throws CloneNotSupportedException The {@code clone()} operation is not
* supported by the {@code Object} class. This also allows extensions of
* this implementation to not support {@code clone()}.
*/
@Override
@SuppressWarnings("unchecked") //Caused by cloning the super-object and casting it back to HashSet.
public HashSet<E> clone() throws CloneNotSupportedException {
final HashSet<E> result = (HashSet<E>)super.clone();
result.table = new Object[table.length];
System.arraycopy(table,0,result.table,0,table.length);
result.loadFactor = loadFactor;
result.size = size;
result.treshold = treshold;
return result;
}
/**
* Returns {@code true} if this set contains the specified element. More
* formally, returns {@code true} if and only if this set contains an
* element {@code e} such that
* {@code (o == null ? e == null : o.equals(e))}.
* @param o The element whose presence in this set is to be tested.
* @return {@code true} if this set contains the specified element, or
* {@code false} otherwise.
*/
@Override
public boolean contains(Object o) {
if(o == null) { //For null-elements, search for the object representing a null-element.
o = nullElement;
}
final Object[] t = table; //Local cache for speed without JIT.
final int tMax = t.length - 1;
//Compute the desired bucket for the element.
final int hash = o.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
int offset = 1;
Object elem;
while((elem = t[index]) != null) { //Search until we hit an empty spot.
if(elem.hashCode() == hash && elem.equals(o)) { //There is the element we seek.
return true;
}
index = (index + offset++) & tMax;
}
return false; //Reached an empty spot and haven't found it yet.
}
/**
* Returns {@code true} if this set contains all of the elements in the
* specified collection.
* <p>This implementation iterates over the specified collection, checking
* each element returned by the iterator in turn to see if it's contained in
* this set. If all elements are so contained, {@code true} is returned, and
* otherwise {@code false} is returned.</p>
* @param c The collection to be checked for containment in this set.
* @return {@code true} if this set contains all of the elements in the
* specified collection.
* @throws ClassCastException The types of one or more elements in the
* specified collection are not subclasses of the type of elements in this
* set.
* @throws NullPointerException The specified collection is {@code null}.
*/
@Override
@SuppressWarnings("element-type-mismatch") //Caused by checking elements of the collection for containment in this set.
public boolean containsAll(final Collection<?> c) {
if(c == null) {
throw new NullPointerException("The specified collection to check for containment in this set is null.");
}
for(final Object element : c) { //Check for every element in the collection whether it is contained in the set.
if(!contains(element)) { //Throws ClassCastException if not a subclass of E.
return false;
}
}
return true;
}
/**
* Compares the specified object with this set for equality. Returns
* {@code true} if the given object is also a set, the two sets have the
* same size, and every member of the specified set is contained in this
* set. This ensures that the {@code equals(Object)} method works properly
* across different implementations of the {@code Set} interface.
* <p>This implementation first checks if the specified object is this set;
* if so it returns {@code true}. Then, it checks if the specified object is
* a set whose size is identical to the size of this set; if not, it returns
* {@code false}. If so, it returns {@code containsAll((Set)o)}.
* @param o The object to be compared for equality with this set.
* @return {@code true} if the specified object is equal to this set, or
* {@code false} otherwise.
*/
@Override
public boolean equals(final Object o) {
if(o == this) { //It's the same object.
return true;
}
if(o == null) { //It's not even an object.
return false;
}
if(!(o instanceof Set)) { //It's not even a set.
return false;
}
final Set<?> set = (Set)o;
if(set.size() != size) { //The cardinalities of the sets are not equal.
return false;
}
try {
return containsAll(set);
} catch(final ClassCastException e) { //Generic type arguments are not E.
return false;
}
}
/**
* Returns the hash code for this set. The hash code of a set is defined to
* be the sum of the hash codes of the elements in the set, where the hash
* code of a {@code null}-element is defined to be zero. This ensures that
* {@code s1.equals(s2)} implies that {@code s1.hashCode() == s2.hashCode()}
* for any two sets {@code s1} and {@code s2}, as required by the general
* contract of {@link Object#hashCode()}.
* @return The hash code for this set.
* @see Set#hashCode()
*/
@Override
public int hashCode() {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
int result = 0;
for(int i = t.length - 1;i >= 0;i--) { //Iterate over the buckets of the hash table.
final Object elem;
if((elem = t[i]) != null && elem != tombstone && elem != nullElement) { //Don't count empty buckets, tombstones or the null-element in the hash.
result += elem.hashCode(); //Take the sum of all hashcodes.
}
}
return result;
}
/**
* Returns {@code true} if this set contains no elements.
* @return {@code true} if this set contains no elements, or {@code false}
* otherwise.
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* Returns an iterator over the elements in this set. The elements are
* returned in no particular order, as the order depends on the order in
* which they are stored in the hash table, and this is unspecified.
* <p>Note that the iterator will search through all buckets of the hash
* table to search for the elements of the set. The time complexity of a
* complete iteration of the set scales with the capacity of the hash table
* plus the number of elements in the set. Also, the time between two
* consecutive calls to {@link Iterator#next()} may vary.</p>
* <p>The iterator is fail-fast, which means that if a structural
* modification is made to the hash set after this method call, the iterator
* returned by this method call will throw a
* {@link ConcurrentModificationException} when {@link Iterator#next()} or
* {@link Iterator#remove()} is called. This behaviour prevents
* nondeterministic or unexpected behaviour caused by the concurrent
* modification of the set while it is being iterated over. Rather than
* giving inconsequent results, it always fails to give a result.</p>
* @return An iterator over the elements in this set.
*/
@Override
public Iterator<E> iterator() {
return new Itr();
}
/**
* Removes the specified element from this set if it is present. More
* formally, removes an element {@code e} such that
* {@code (element == null ? e == null : element.equals(e))}, if this set
* contains such an element. Returns {@code true} if this set contained the
* element (or equivalently, if this set changed as a result of the call).
* This set will not contain the element once the call returns.
* @param element The object to be removed from this set, if present.
* @return {@code true} if the set contained the specified element, or
* {@code false} otherwise.
*/
@Override
public boolean remove(Object element) {
if(element == null) { //Don't try to remove null. Remove the object representing null instead.
element = nullElement;
}
final Object[] t = table; //Local cache for speed without JIT.
final int tMax = t.length - 1;
//Compute the desired bucket for the element.
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
Object elem;
int offset = 1;
while((elem = t[index]) != null) { //Look for the object.
if(elem.hashCode() == hash && elem.equals(element)) { //This is the element we seek.
t[index] = tombstone; //R.I.P.
modCount++;
size--;
return true;
}
index = (index + offset++) & tMax;
}
return false; //Reached an empty spot without any hit. Not found.
}
/**
* Removes from this set all of its elements that are contained in the
* specified collection. If the specified collection is also a set, this
* operation effectively modifies this set so that its value is the
* asymmetric set difference of the two sets.
* <p>This implementation iterates over either the specified collection or
* over the set, based on which is smaller: the size of the collection or
* the capacity of the hash table. Since the hash table iterates over the
* total size of the table rather than just the elements, its table capacity
* is compared rather than the cardinality of the set. When iterating over
* the collection, each element of the collection is removed from the set if
* it is present. When iterating over the set, each element of the set is
* removed from the set if it is contained in the collection.</p>
* @param c The collection containing elements to be removed from this set.
* @return {@code true} if this set changed as a result of the call, or
* {@code false} otherwise.
* @throws ClassCastException The class of an element of the specified
* collection is not a subclass of the types of elements in this set.
* @throws NullPointerException The specified collection is {@code null}.
*/
@Override
public boolean removeAll(final Collection<?> c) {
if(c == null) {
throw new NullPointerException("The specified collection to remove all elements from is null.");
}
final Object[] t = table; //Local cache for speed without JIT.
int removedElements = 0;
//Pick whichever method is fastest:
if(table.length > c.size() || (c instanceof List && table.length > Math.sqrt(c.size()))) { //Iterate over c, removing all elements from this set. Lists have linear contains() methods, so they get special treatment.
final int tMax = t.length - 1;
for(Object element : c) { //Iterate over the collection.
if(element == null) { //Don't try to remove null. Remove the object representing null instead.
element = nullElement;
}
//Compute the desired bucket for the element.
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
Object elem;
int offset = 1;
while((elem = t[index]) != null) { //Look for the object.
if(elem.hashCode() == hash && elem.equals(element)) { //This is the element we seek.
t[index] = tombstone; //R.I.P.
removedElements++;
break;
}
index = (index + offset++) & tMax;
}
//Element not found. Continue with the next element.
}
if(removedElements >= 0) { //That actually removed something.
modCount++;
size -= removedElements;
return true;
}
return false;
}
//Otherwise, iterate over the set, removing all elements that are in c.
for(int i = t.length - 1;i >= 0;i--) {
final Object elem;
if((elem = t[i]) != null && elem != tombstone && ((elem == nullElement && c.contains(null)) || c.contains(elem))) { //If it's the null-element, check if c has a null-element. Otherwise, just check for the element itself.
t[i] = tombstone; //R.I.P.
removedElements++;
}
}
if(removedElements >= 0) { //That actually removed something.
modCount++;
size -= removedElements;
return true;
}
return false;
}
/**
* Retains only the elements in this set that are contained in the specified
* collection. In other words, removes from this set all of its elements
* that are not contained in the specified collection. When the method call
* returns, the set will contain the intersection of the original elements
* of the set and the elements of the collection.
* <p>This implementation iterates over the elements of the set and checks
* for each element whether it is contained in the specified collection,
* removing it if it is not contained.</p>
* <p>List collections get special treatment. Their
* {@link List#contains(Object)} method is generally linear-time and their
* iterator constant per element. Therefore, when encountered with a list of
* reasonable size, this method will instead clear the set and then iterate
* over the list, re-adding those elements that were in the original set.
* </p>
* @param c The collection to retain the elements from.
* @return {@code true} if this set changed as a result of the call, or
* {@code false} otherwise.
* @throws ClassCastException The class of an element of the specified
* collection is not a subclass of the elements of this set.
* @throws NullPointerException The specified collection is {@code null}.
*/
@Override
public boolean retainAll(final Collection<?> c) {
if(c == null) {
throw new NullPointerException("The specified collection to retain all elements from is null.");
}
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
if(c instanceof List && t.length > Math.sqrt(c.size())) { //Lists have linear contains() methods and will get special treatment.
//Iterate over the list and add all elements that are both in the list and in the original table.
final Object[] newTable = new Object[t.length];
final int tMax = t.length - 1;
int retainedElements = 0;
for(Object element : c) { //See if it's in the original hash table.
if(element == null) { //Don't try to find null. Find the object representing null instead.
element = nullElement;
}
//Compute the desired bucket for the element.
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
Object elem;
int offset = 1;
while((elem = t[index]) != null) { //Look for the object.
if(elem == tombstone) { //Copy over tombstones as well, or we'd have to rehash everything.
newTable[index] = elem;
} else if(elem.hashCode() == hash && elem.equals(element)) { //Found it!
newTable[index] = elem; //Copy it to the new table.
t[index] = tombstone; //Don't find it a second time.
retainedElements++;
break;
}
index = (index + offset++) & tMax;
}
//Element not found. Continue with the next element.
}
for(int i = tMax;i >= 0;i--) { //Place tombstones in the new table where elements have been removed.
if(t[i] != null && newTable[i] == null) {
newTable[i] = tombstone;
}
}
table = newTable; //Use the new table. The old one was modified anyhow.
if(retainedElements < size) { //That actually removed something.
modCount++;
size = retainedElements;
return true;
}
return false;
}
int removedElements = 0;
for(int i = t.length - 1;i >= 0;i--) {
final Object elem;
if((elem = t[i]) != null && elem != tombstone && ((elem == nullElement && !c.contains(null)) || !c.contains(elem))) { //If it's the null-element, check if c has a null-element. Otherwise, just check for the element itself.
t[i] = tombstone; //R.I.P.
removedElements++;
}
}
if(removedElements > 0) { //That actually removed something.
modCount++;
size -= removedElements;
return true;
}
return false;
}
/**
* Returns the number of elements in this set.
* @return The number of elements in this set.
*/
@Override
public int size() {
return size;
}
/**
* Returns an array containing all of the elements in this set. The elements
* are in no particular order.
* <p>The returned array will be "safe" in that no references to it are
* maintained by this set. The caller is thus free to modify the returned
* array; it will not have any effect on the set.</p>
* <p>This implementation searches through the hash table for active
* elements and copies every element it finds to the resulting array.
* @return An array containing all of the elements in this set.
*/
@Override
public Object[] toArray() {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
final Object[] result = new Object[size];
int pos = 0; //Position in the result table to put the next element.
for(int i = t.length - 1;i >= 0;i--) {
final Object elem = t[i];
if(elem != null && elem != tombstone) {
if(elem == nullElement) {
pos++; //This element in the result can remain null.
} else {
result[pos++] = elem;
}
}
}
return result;
}
/**
* Returns an array containing all of the elements in this set; the runtime
* type of the returned array is that of the specified array. If the set
* fits in the specified array, it is returned therein. Otherwise, a new
* array is allocated with the runtime type of the specified array and the
* size of this set.
* <p>If this set fits in the specified array with room to spare (i.e. the
* array has more elements than this set), the elements following the end of
* the set remain {@code null}.</p>
* <p>The elements are returned in no particular order.</p>
* @param <E> The type of elements in the new array.
* @param a The array into which the elements of this set are to be stored,
* if it is big enough; otherwise, a new array of the same runtime type is
* allocated for this purpose.
* @return An array containing all of the elements in this set.
* @throws ArrayStoreException The runtime type of the specified array is
* not a supertype of the runtime type of every element in this collection.
* @throws NullPointerException The specified array is {@code null}.
*/
@Override
@SuppressWarnings("unchecked") //The reflection array creation, and casting Objects from the hash table to E's for the result.
public <E> E[] toArray(final E[] a) {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
final E[] result;
if(a.length >= size) { //Array suffices.
result = a;
} else { //Too many elements for the array.
result = (E[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(),size); //Allocate a new array.
}
int pos = 0; //Position in the result table to put the next element.
for(int i = t.length - 1;i >= 0;i--) {
final E elem = (E)t[i]; //Safe cast, since t[] contains only E's.
if(elem != null && elem != tombstone) {
if(elem == nullElement) {
pos++; //This element in the result can remain null.
} else {
result[pos++] = elem;
}
}
}
return result;
}
/**
* Returns a {@code String} representation of this set. The {@code String}
* representation reflects the mathematical notation of a set. It consists
* of a list of the set's elements, in no particular order, enclosed in
* curly brackets ({@code "{}"}). Adjacent elements are separated
* by commas (","). Elements are converted to strings by their
* {@link Object#toString()} methods.
* @return A {@code String} representation of this set.
*/
@Override
public String toString() {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
final int s = size;
final StringBuilder result = new StringBuilder(2 + 5 * s); //Reserve 2 chars for brackets, 4 for each element and 1 for the commas after each element.
result.append('{');
int count = 0; //The number of elements found so far. This tells us whether this is the last element (to append a comma or not).
for(int i = t.length - 1;i >= 0;i--) {
final Object elem = t[i];
if(elem != null && elem != tombstone) { //Found an element.
if(elem == this) { //Don't go into infinite recursion if it contains itself!
result.append("(this Set)");
} else if(elem == nullElement) { //This one has a special string: null.
result.append("null");
} else {
result.append(elem); //Calls the toString() method.
}
if(++count < s) { //That was not the last element. Add a comma.
result.append(',');
}
}
}
result.append('}');
return result.toString(); //Finalise and return.
}
/**
* Helper method to rehash the table to a new size. A new array will be
* allocated for the hash table with the specified capacity. All elements in
* the old table will be rehashed and placed in the new table.
* @param newCapacity The capacity of the new hash table. This must be a
* power of {@code 2}!
*/
protected void resize(final int newCapacity) {
final Object[] newTable = new Object[newCapacity];
final int tMax = newCapacity - 1;
for(int i = table.length - 1;i >= 0;i--) {
final Object element = table[i];
if(element == null || element == tombstone) { //This bucket was empty. And don't put tombstones in the new table either.
continue;
}
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples are at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (newCapacity - 1 has all bits on, since newCapacity is a power of 2). Same as modulo length.
int offset = 1;
while(newTable[index] != null) { //Search for a spot to place it.
index = (index + offset++) & tMax;
}
//Since newTable[index] is now null due to the while loop, we have an empty spot for the element.
newTable[index] = element;
}
table = newTable; //Use the new table from now on.
treshold = Math.min((int)(newCapacity * loadFactor),maximumCapacity + 1); //Set a new treshold for the next rehash.
}
/**
* Reconstitute the {@code HashSet} instance from a stream (that is,
* deserialise it).
* @param s The stream to read the state of a {@code HashSet} from.
* @throws ClassNotFoundException The SerialVersionUID of the class does not
* match any known version of {@code HashSet}.
* @throws IOException Something went wrong reading from the specified
* stream.
*/
private void readObject(final ObjectInputStream s) throws IOException,ClassNotFoundException {
s.defaultReadObject(); //Read the default serialisation magic.
final int capacity = s.readInt(); //Read table capacity.
final Object[] t = new Object[capacity]; //Create the actual hash table for the hash set.
loadFactor = s.readFloat(); //Read load factor.
size = s.readInt(); //Read size.
for(int i = size - 1;i >= 0;i--) { //Read each element.
final Object element = s.readObject(); //Read the element itself.
final int hashCode = element.hashCode();
int index = hashCode ^ ((hashCode >>> 20) ^ (hashCode >>> 12)); //Find the index at which to place it.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & (capacity - 1);
t[index] = element; //Store it at that location.
}
table = t; //Store the hash table in the object.
treshold = (int)(table.length * loadFactor);
}
/**
* Save the state of this {@code HashSet} instance to a stream (that is,
* serialise it).
* @serialData The capacity ({@code int}) and load factor ({@code float}) of
* the hash table are emitted, followed by the number of elements in the set
* ({@code int}), followed by all elements ({@code Object}s) in no
* particular order.
* @param s The stream to write the state of this {@code HashSet} to.
* @throws IOException Something went wrong writing to the specified stream.
*/
private void writeObject(final ObjectOutputStream s) throws IOException {
Object[] t = table; //Cache a local copy for faster access without JIT compiler.
s.defaultWriteObject(); //Write the default serialisation magic.
s.writeInt(t.length); //Write table capacity.
s.writeFloat(loadFactor); //Write load factor.
s.writeInt(size); //Write size.
for(int i = t.length - 1;i >= 0;i--) {
if(t[i] != null) {
s.writeObject(t[i]); //Write out each element.
}
}
}
/**
* This is a custom implementation of {@link Iterator} that iterates over
* the elements of a hash set. The iterator gives the elements of the set in
* no particular order. The actual order will be the reverse order of the
* elements in the set as they are ordered in the internal hash table of the
* set.
* <p>Note that the iterator will search through all buckets of the hash
* table to search for the elements of the set. The time complexity of a
* complete iteration of the set scales with the capacity of the hash table
* plus the number of elements in the set. Also, the time between two
* consecutive calls to {@link Iterator#next()} may vary.</p>
* <p>The iterator is fail-fast, which means that if a structural
* modification is made to the hash set after this method call, the iterator
* will throw a {@link ConcurrentModificationException} when {@link #next()}
* or {@link #remove()} is called. This behaviour prevents nondeterministic
* or unexpected behaviour caused by the concurrent modification of the set
* while it is being iterated over. Rather than giving inconsequent results,
* it always fails to give a result.</p>
*/
protected class Itr implements Iterator<E> {
/**
* The expected modification count of the accompanying {@code HashSet}.
* If this is different from the actual modification count of the set, a
* concurrent modification on the set has occurred and every method
* should throw a {@link ConcurrentModificationException}.
*/
protected int expectedModCount;
/**
* The current slot in the iteration. If this index is negative, the
* iteration is complete.
*/
protected int index;
/**
* The index of the last element that was returned by a call to
* {@link #next()}. This element will be removed from the table if
* {@link #remove()} would be called. A value of -1 indicates that
* {@link #next()} has not yet been called or not since the last call to
* {@link #remove()} (or that {@link #next()} didn't return an element).
*/
protected int last = -1;
/**
* Creates a new iterator over the {@code HashSet}. The iterator will
* start at the last element in the table, iterating towards index
* {@code 0}.
*/
protected Itr() {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
for(index = t.length - 1;index >= 0 && (t[index] == null || t[index] == tombstone);index--); //Set index in advance to the index of the first element.
expectedModCount = modCount; //Store the modCount of the HashSet. From here, concurrent modification will throw an exception.
}
/**
* Returns {@code true} if the iteration has more elements. In other
* words, returns {@code true} if {@link #next()} would return an
* element of the set rather than throwing a
* {@code NoSuchElementException}.
* @return {@code true} if the iteration has more elements, or
* {@code false} otherwise.
*/
@Override
public boolean hasNext() {
return index >= 0;
}
/**
* Returns the next element in the iteration.
* @return The next element in the iteration.
* @throws ConcurrentModificationException The set was structurally
* modified between the constructing of this iterator and the calling of
* this method.
* @throws NoSuchElementException The iteration has no more elements.
*/
@Override
@SuppressWarnings("unchecked") //Caused by the casting of a table element to the returned E.
public E next() {
if(modCount != expectedModCount) { //Some concurrent modification has been made on the set!
throw new ConcurrentModificationException();
}
if(index < 0) { //We're through the array.
last = -1;
throw new NoSuchElementException();
}
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
last = index;
for(index--;index >= 0 && (t[index] == null || t[index] == tombstone);index--); //Set the index on the next position.
if(t[last] == nullElement) {
return null; //Return null instead of the element representing null.
}
return (E)t[last]; //Safe cast, since the table contains only E's.
}
/**
* Removes from the set the last element returned by this iterator. This
* method can be called only once per call to {@link #next()}.
* @throws ConcurrentModificationException The set was structurally
* modified between the constructing of this iterator and the calling of
* this method.
* @throws IllegalStateException The {@link #next()} method has not yet
* been called, or the {@code remove()} method has already been called
* after the last call to the {@code next()} method.
*/
@Override
public void remove() {
if(last < 0) { //Nothing to remove.
throw new IllegalStateException();
}
if(modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
//Delete the element at 'last'.
if(table[last] != null && table[last] != tombstone) {
table[last] = tombstone; //R.I.P.
size--;
modCount++;
expectedModCount = modCount; //This modification is expected since the iterator made it.
last = -1; //Set this to negative so the next call doesn't try to remove it again.
}
}
}
} | src/net/dulek/collections/HashSet.java | /**
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or distribute
* this software, either in source code form or as a compiled binary, for any
* purpose, commercial or non-commercial, and by any means.
*
* In jurisdictions that recognize copyright laws, the author or authors of this
* software dedicate any and all copyright interest in the software to the
* public domain. We make this dedication for the benefit of the public at large
* and to the detriment of our heirs and successors. We intend this dedication
* to be an overt act of relinquishment in perpetuity of all present and future
* rights to this software under copyright law.
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.dulek.collections;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.*;
/**
* This class represents a set of elements, implemented using a hash table. A
* set is an unordered collection of elements, containing no duplicate elements.
* Being unordered, the set makes no guarantees as to the order of its elements.
* This set is unsynchronised, and permits the {@code null} element.
* <p>This implementation is heavily based on the default
* {@link java.util.HashMap HashMap} implementation of Java 7, but some
* improvements were made to better facilitate sets rather than key-value
* mappings, since the default implementation of {@link HashSet} maintains a
* heavy-weight {@code HashMap} to implement the set. Additionally, the default
* implementation provides two ways of hashing its keys: the standard
* {@code hashCode()} method of the keys or a cryptographically more secure
* variant for {@code String}s that uses a random seed. This implementation
* foregoes the latter hashing method, making it potentially more vulnerable to
* collision attacks. Lastly, the default implementation uses the separate
* chaining method for preventing collisions. In an effort to rid the
* implementation from additional "entry" instances, separate chaining is
* infeasable. Instead, open addressing with quadratic probing was chosen.
* Quadratic probing avoids the clustering problem better than linear probing
* and in Java the locality of reference makes no difference. It was chosen over
* more complex collision resolution techniques for how it requires less memory
* overhead.</p>
* <p>This implementation provides expected constant-time performance for all
* basic operations of the set: {@link #add(E)}, {@link #remove(Object)} and
* {@link #contains(Object)}. This expected performance expects that the hash
* function disperses the elements properly among the buckets. Iteration over
* the set requires time proportional to the "capacity" of the hash table (the
* number of buckets) plus its size (the number of elements). Thus, it's very
* important not to set the initial capacity too high (or the load factor too
* low) if iteration performance is important.</p>
* <p>An instance of {@code HashSet} has two parameters that affect its
* performance: the initial capacity and the load factor. The capacity is the
* number of buckets in the hash table, and the initial capacity is simply the
* capacity at the time the hash table is created. The load factor is a measure
* of how full the hash table is allowed to get before its capacity is
* automatically increased. When the number of entries in the hash table exceeds
* the product of the load factor and the current capacity, the hash table is
* rehashed, meaning all elements will be distributed over a new table. The new
* table will be approximately twice the size of the old table.</p>
* <p>As a general rule, the default load factor offers a good tradeoff between
* time and space costs. Higher values reduce the space overhead but increase
* the time cost of the basic operations. Lower values increase the memory
* requirement but reduce the time cost. The expected number of entries in the
* set and its load factor should be taken into account when setting its initial
* capacity, so as to minimise the number of rehash operations. If the initial
* capacity is greater than the maximum number of entries divided by the load
* factor, no rehash operations will ever occur. The load factor cannot exceed
* {@code 1} in this implementation, since there can be only one element in each
* bucket.</p>
* <p>If many elements are to be stored in a {@code HashSet} instance, creating
* it with a sufficiently large capacity will allow the elements to be stored
* more efficiently than letting it perform automatic rehashing as needed to
* grow the table.</p>
* <p>Note that this implementation is not synchronised. If multiple threads
* access the {@code HashSet} concurrently, and at least one of these threads
* modifies the map structurally, it must be synchronised externally. A
* structural modification is any operation that adds or removes one or more
* elements. This is typically accomplished by synchronising on some object that
* naturally encapsulates the set. If no such object exists, the set should be
* "wrapped" using the
* {@link java.util.Collections#synchronizedSet Collections.synchronizedSet}
* methods. This is best done at creation time, to prevent accidental
* unsynchronised access to the set:
* {@code Set<...> s = Collections.synchronizedSet(new HashSet<>(...));}</p>
* <p>The iterators returned by this class's {@link #iterator()} method are
* fail-fast: if the set is structurally modified at any time after the iterator
* is created, in any way except through the iterator's own
* {@link Iterator#remove()} method, the {@code Iterator} throws a
* {@link ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behaviour at an undetermined time in the future.
* </p>
* <p>Note that the fail-fast behaviour of an iterator cannot be guaranteed as
* it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronised concurrent modification. Fail-fast iterators throw
* {@code ConcurrentModificationException}s on a best-effort basis. Therefore,
* it would be wrong to write a program that depended on this exception for its
* correctness: the fail-fast behaviour of iterators should only be used to
* detect bugs.</p>
* @author Ruben Dulek
* @param <E> The types of elements stored in this set.
* @see Collection
* @see java.util.HashMap
* @see Set
* @version 1.0
*/
public class HashSet<E> implements Set<E>,Cloneable,Serializable {
/**
* The default initial capacity of the hash table. This will be the initial
* capacity of the hash table if no initial capacity is specified in the
* constructing of the set. It must be a power of two, so keep the bitshift
* operator in this value, please.
*/
protected static final int defaultInitialCapacity = 1 << 4;
/**
* The default load factor. This will be the load factor if none is
* specified in the constructing of the set. A value of 0.7 is a good
* trade-off between memory usage and time cost. Must be between {@code 0}
* and {@code 1}.
*/
protected static final float defaultLoadFactor = 0.7f;
/**
* The load factor for the hash table. This indicates the maximum fraction
* of buckets that can be filled before the table is rehashed to a bigger
* table.
* @serial The factor is converted to a {@code String} via
* {@code Float.toString(loadFactor)}.
*/
protected float loadFactor;
/**
* The maximum capacity of the table. This is used if a higher value is
* implicity specified by either of the constructors with arguments. It must
* be a power of two, so keep the bitshift operator in this value, please.
*/
protected static final int maximumCapacity = 1 << 30;
/**
* The number of times this {@code HashSet} has been structurally modified.
* Structural modifications are those that change the number of elements in
* the set or otherwise modify its internal structure (e.g. a rehash). This
* field is used to make iterators over the set fail-fast.
*/
protected transient int modCount;
/**
* This object represents the {@code null}-element. If it is in the set, the
* set contains the {@code null}-element. Methods that allow access to the
* actual elements of the set (such as {@link Iterator#next()}) should mind
* not to return this object, but return {@code null} instead.
*/
protected static final Object nullElement = new Object();
/**
* The version of the serialised format of the set. This identifies a
* serialisation as being the serialised format of this class.
*/
private static final long serialVersionUID = 4882436748081726100L;
/**
* The number of elements in this set.
*/
protected transient int size;
/**
* The actual hash table. Its length must always be a power of two. The
* table will be resized as necessary, rehashing every element in it.
*/
protected transient Object[] table;
/**
* When an element is removed, it will be replaced by a tombstone, marking
* that the bucket used to contain an element, and that there might still be
* elements after the tombstone belonging to buckets before the tombstone.
*/
protected static final Object tombstone = new Object();
/**
* The next size value at which to resize and rehash the table. It will be
* kept at {@code table.length * loadFactor}.
*/
protected int treshold;
/**
* Constructs an empty {@code HashSet} with the default initial capacity
* (16) and the default load factor (0.7). Note that it is good practice to
* always specify an initial capacity if there is any idea of approximately
* how many elements the set will hold.
*/
public HashSet() {
loadFactor = defaultLoadFactor;
treshold = (int)(defaultInitialCapacity * defaultLoadFactor); //Pre-compute the treshold.
table = new Object[defaultInitialCapacity]; //Reserve the actual table.
}
/**
* Constructs an empty {@code HashSet} with the specified initial capacity
* and the default load factor (0.7).
* @param initialCapacity The initial capacity of the hash table.
* @throws IllegalArgumentException The initial capacity is negative.
*/
public HashSet(int initialCapacity) {
if(initialCapacity <= 0) {
throw new IllegalArgumentException("The initial capacity of " + initialCapacity + " is negative.");
}
if(initialCapacity > maximumCapacity) {
initialCapacity = maximumCapacity;
}
initialCapacity = net.dulek.math.Math.roundUpPower2(initialCapacity); //Find the next power of 2 greater than or equal to initialCapacity.
loadFactor = defaultLoadFactor;
treshold = Math.min((int)(initialCapacity * loadFactor),maximumCapacity + 1); //Pre-compute the treshold.
table = new Object[initialCapacity]; //Reserve the actual table.
}
/**
* Constructs an empty {@code HashSet} with the specified initial capacity
* and load factor.
* @param initialCapacity The initial capacity of the hash table.
* @param loadFactor The load factor.
* @throws IllegalArgumentException The initial capacity is negative or the
* load factor is not positive.
*/
public HashSet(int initialCapacity,final float loadFactor) {
if(initialCapacity < 0) {
throw new IllegalArgumentException("The initial capacity of " + initialCapacity + " is negative.");
}
if(initialCapacity > maximumCapacity) {
initialCapacity = maximumCapacity;
}
if(loadFactor <= 0 || Float.isNaN(loadFactor)) {
throw new IllegalArgumentException("The load factor of " + loadFactor + " is not positive.");
}
if(loadFactor >= 1) {
throw new IllegalArgumentException("The load factor of " + loadFactor + " is too high.");
}
initialCapacity = net.dulek.math.Math.roundUpPower2(initialCapacity); //Find the next power of 2 greater than or equal to initialCapacity.
this.loadFactor = loadFactor;
treshold = Math.min((int)(initialCapacity * loadFactor),maximumCapacity + 1); //Pre-compute the treshold.
table = new Object[initialCapacity]; //Reserve the actual table.
}
/**
* Constructs a new set containing the elements in the specified collection.
* The set is created with a default load factor (0.7) and an initial
* capacity sufficient to contain the elements in the specified collection.
* @param c The collection whose elements are to be placed into this set.
* @throws NullPointerException The specified collection is {@code null}.
*/
public HashSet(final Collection<? extends E> c) {
if(c == null) {
throw new NullPointerException("The specified collection to initialise the set with is null.");
}
loadFactor = defaultLoadFactor;
final int initialCapacity = net.dulek.math.Math.roundUpPower2(Math.max((int)(c.size() / defaultLoadFactor),defaultInitialCapacity)); //Make the capacity enough for all elements but no lower than the default initial capacity.
treshold = Math.min((int)(initialCapacity * defaultLoadFactor),maximumCapacity + 1); //Pre-compute the treshold.
table = new Object[initialCapacity]; //Reserve the actual table.
//Add all elements of the collection.
final int tMax = initialCapacity - 1;
ADDALL:
for(E element : c) { //Add all elements from the collection.
Object object = element;
if(object == null) { //Don't try to add null. Add the object representing null instead.
object = nullElement;
}
//Compute the desired bucket for the element.
final int hash = object.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples are at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
int offset = 1; //By how much we must grow the index while searching. Index grows quadratically.
Object elem;
//Search for the element.
while((elem = table[index]) != null) {
if(elem.hashCode() == hash && elem.equals(object)) { //The element is already in the table.
continue ADDALL; //Skip this element. Continue with the next one.
}
index = (index + offset++) & tMax;
}
//table[index] is now null (since the while loop ended) so this is a free spot.
table[index] = object; //Place it at our free spot.
modCount++;
}
}
/**
* Creates a hash set from a clone operation. The provided parameters are
* stored literally in the fields.
* @param loadFactor The load factor.
* @param size The number of elements in the set.
* @param table The hash table for the set.
*/
private HashSet(final float loadFactor,final int size,final Object[] table) {
this.loadFactor = loadFactor;
this.size = size;
this.table = table;
treshold = Math.min((int)(table.length * loadFactor),maximumCapacity + 1);
}
/**
* Adds the specified element to this set if it is not already present. More
* formally, adds the specified element {@code e} to this set if this set
* contains no element {@code f} such that
* {@code (e == null ? f == null : e.equals(f))}. If this set already
* contains the element, the call leaves the set unchanged and returns
* {@code false}.
* @param element The element to be added to this set.
* @return {@code true} if this set did not already contain the specified
* element, or {@code false} otherwise.
*/
@Override
public boolean add(final E element) {
Object object = element;
if(object == null) { //Don't try to add null. Add the object representing null instead.
object = nullElement;
}
final int tMax = table.length - 1;
//Compute the desired bucket for the element.
final int hash = object.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples are at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
int offset = 1; //By how much we must grow the index while searching. Index grows quadratically.
Object elem;
//Search for the element.
while((elem = table[index]) != null) {
if(elem == tombstone) { //There was an object here...
//Continue the search, but no more gravedigging.
int searchIndex = (index + offset++) & tMax;
while((elem = table[searchIndex]) != null) {
if(elem.hashCode() == hash && elem.equals(object)) { //The element is already in the table.
return false;
}
searchIndex = (searchIndex + offset++) & tMax;
}
table[index] = object; //Place it at the tombstone.
modCount++;
if(++size > treshold) { //Getting too big.
resize(table.length << 1);
}
return true;
}
if(elem.hashCode() == hash && elem.equals(object)) { //The element is already in the table.
return false;
}
index = (index + offset++) & tMax;
}
//table[index] is now null (since the while loop ended) so this is a free spot.
table[index] = object; //Place it at our free spot.
modCount++;
if(++size > treshold) { //Getting too big.
resize(table.length << 1);
}
return true;
}
/**
* Adds all of the elements in the specified collection to this set. If the
* specified collection is this set, a
* {@link ConcurrentModificationException} is thrown.
* <p>This implementation iterates over the specified collection, and adds
* each object returned by the iterator to this collection, in turn.</p>
* @param c The collection containing elements to be added to this set.
* @return {@code true} if this set changed as a result of the call.
* @throws NullPointerException The specified collection is {@code null}.
*/
@Override
public boolean addAll(final Collection<? extends E> c) {
if(c == null) {
throw new NullPointerException("The specified collection to add to the set is null.");
}
//Make sure we have enough capacity, even if they're all new elements.
if(size + c.size() >= treshold) {
if(table.length == maximumCapacity) { //We're already at maximum capacity. Don't trigger this again.
treshold = Integer.MAX_VALUE;
} else {
final int newCapacity = net.dulek.math.Math.roundUpPower2((int)((size + c.size()) / loadFactor));
resize(newCapacity);
//Add all elements, but don't check for tombstones or the treshold (since we just rehashed everything anyways).
boolean modified = false;
final int tMax = newCapacity - 1;
ADDINGALL:
for(Object element : c) {
if(element == null) { //Don't try to add null. Add the object representing null instead.
element = nullElement;
}
//Compute the desired bucket for the element.
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples are at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
int offset = 1; //By how much we must grow the index while searching. Index grows quadratically.
Object elem;
//Search for the element.
while((elem = table[index]) != null) {
if(elem.hashCode() == hash && elem.equals(element)) { //The element is already in the table.
continue ADDINGALL; //Continue with the next element.
}
index = (index + offset++) & tMax;
}
//table[index] is now null (since the while loop ended) so this is a free spot.
table[index] = element; //Place it at our free spot.
size++;
modified = true;
}
if(modified) {
modCount++;
return true;
}
return false;
}
}
//Add all elements, but keep checking for tombstones.
boolean modified = false;
for(E element : c) { //Add all elements from the collection.
modified |= add(element);
}
return modified;
}
/**
* Removes all of the elements from this set. The set will be empty after
* this call returns.
*/
@Override
public void clear() {
modCount++;
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
for(int i = t.length - 1;i >= 0;i--) {
t[i] = null; //Erase the table.
}
size = 0;
}
/**
* Returns a shallow copy of this {@code HashSet} instance: The elements
* themselves are not cloned.
* @return A shallow copy of this set.
* @throws CloneNotSupportedException The {@code clone()} operation is not
* supported by the {@code Object} class. This also allows extensions of
* this implementation to not support {@code clone()}.
*/
@Override
@SuppressWarnings("unchecked") //Caused by cloning the super-object and casting it back to HashSet.
public HashSet<E> clone() throws CloneNotSupportedException {
final HashSet<E> result = (HashSet<E>)super.clone();
result.table = new Object[table.length];
System.arraycopy(table,0,result.table,0,table.length);
result.loadFactor = loadFactor;
result.size = size;
result.treshold = treshold;
return result;
}
/**
* Returns {@code true} if this set contains the specified element. More
* formally, returns {@code true} if and only if this set contains an
* element {@code e} such that
* {@code (o == null ? e == null : o.equals(e))}.
* @param o The element whose presence in this set is to be tested.
* @return {@code true} if this set contains the specified element, or
* {@code false} otherwise.
*/
@Override
public boolean contains(Object o) {
if(o == null) { //For null-elements, search for the object representing a null-element.
o = nullElement;
}
final Object[] t = table; //Local cache for speed without JIT.
final int tMax = t.length - 1;
//Compute the desired bucket for the element.
final int hash = o.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
int offset = 1;
Object elem;
while((elem = t[index]) != null) { //Search until we hit an empty spot.
if(elem.hashCode() == hash && elem.equals(o)) { //There is the element we seek.
return true;
}
index = (index + offset++) & tMax;
}
return false; //Reached an empty spot and haven't found it yet.
}
/**
* Returns {@code true} if this set contains all of the elements in the
* specified collection.
* <p>This implementation iterates over the specified collection, checking
* each element returned by the iterator in turn to see if it's contained in
* this set. If all elements are so contained, {@code true} is returned, and
* otherwise {@code false} is returned.</p>
* @param c The collection to be checked for containment in this set.
* @return {@code true} if this set contains all of the elements in the
* specified collection.
* @throws ClassCastException The types of one or more elements in the
* specified collection are not subclasses of the type of elements in this
* set.
* @throws NullPointerException The specified collection is {@code null}.
*/
@Override
@SuppressWarnings("element-type-mismatch") //Caused by checking elements of the collection for containment in this set.
public boolean containsAll(final Collection<?> c) {
if(c == null) {
throw new NullPointerException("The specified collection to check for containment in this set is null.");
}
for(final Object element : c) { //Check for every element in the collection whether it is contained in the set.
if(!contains(element)) { //Throws ClassCastException if not a subclass of E.
return false;
}
}
return true;
}
/**
* Compares the specified object with this set for equality. Returns
* {@code true} if the given object is also a set, the two sets have the
* same size, and every member of the specified set is contained in this
* set. This ensures that the {@code equals(Object)} method works properly
* across different implementations of the {@code Set} interface.
* <p>This implementation first checks if the specified object is this set;
* if so it returns {@code true}. Then, it checks if the specified object is
* a set whose size is identical to the size of this set; if not, it returns
* {@code false}. If so, it returns {@code containsAll((Set)o)}.
* @param o The object to be compared for equality with this set.
* @return {@code true} if the specified object is equal to this set, or
* {@code false} otherwise.
*/
@Override
public boolean equals(final Object o) {
if(o == this) { //It's the same object.
return true;
}
if(o == null) { //It's not even an object.
return false;
}
if(!(o instanceof Set)) { //It's not even a set.
return false;
}
final Set<?> set = (Set)o;
if(set.size() != size) { //The cardinalities of the sets are not equal.
return false;
}
try {
return containsAll(set);
} catch(final ClassCastException e) { //Generic type arguments are not E.
return false;
}
}
/**
* Returns the hash code for this set. The hash code of a set is defined to
* be the sum of the hash codes of the elements in the set, where the hash
* code of a {@code null}-element is defined to be zero. This ensures that
* {@code s1.equals(s2)} implies that {@code s1.hashCode() == s2.hashCode()}
* for any two sets {@code s1} and {@code s2}, as required by the general
* contract of {@link Object#hashCode()}.
* @return The hash code for this set.
* @see Set#hashCode()
*/
@Override
public int hashCode() {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
int result = 0;
for(int i = t.length - 1;i >= 0;i--) { //Iterate over the buckets of the hash table.
final Object elem;
if((elem = t[i]) != null && elem != tombstone && elem != nullElement) { //Don't count empty buckets, tombstones or the null-element in the hash.
result += elem.hashCode(); //Take the sum of all hashcodes.
}
}
return result;
}
/**
* Returns {@code true} if this set contains no elements.
* @return {@code true} if this set contains no elements, or {@code false}
* otherwise.
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* Returns an iterator over the elements in this set. The elements are
* returned in no particular order, as the order depends on the order in
* which they are stored in the hash table, and this is unspecified.
* <p>Note that the iterator will search through all buckets of the hash
* table to search for the elements of the set. The time complexity of a
* complete iteration of the set scales with the capacity of the hash table
* plus the number of elements in the set. Also, the time between two
* consecutive calls to {@link Iterator#next()} may vary.</p>
* <p>The iterator is fail-fast, which means that if a structural
* modification is made to the hash set after this method call, the iterator
* returned by this method call will throw a
* {@link ConcurrentModificationException} when {@link Iterator#next()} or
* {@link Iterator#remove()} is called. This behaviour prevents
* nondeterministic or unexpected behaviour caused by the concurrent
* modification of the set while it is being iterated over. Rather than
* giving inconsequent results, it always fails to give a result.</p>
* @return An iterator over the elements in this set.
*/
@Override
public Iterator<E> iterator() {
return new Itr();
}
/**
* Removes the specified element from this set if it is present. More
* formally, removes an element {@code e} such that
* {@code (element == null ? e == null : element.equals(e))}, if this set
* contains such an element. Returns {@code true} if this set contained the
* element (or equivalently, if this set changed as a result of the call).
* This set will not contain the element once the call returns.
* @param element The object to be removed from this set, if present.
* @return {@code true} if the set contained the specified element, or
* {@code false} otherwise.
*/
@Override
public boolean remove(Object element) {
if(element == null) { //Don't try to remove null. Remove the object representing null instead.
element = nullElement;
}
final Object[] t = table; //Local cache for speed without JIT.
final int tMax = t.length - 1;
//Compute the desired bucket for the element.
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
Object elem;
int offset = 1;
while((elem = t[index]) != null) { //Look for the object.
if(elem.hashCode() == hash && elem.equals(element)) { //This is the element we seek.
t[index] = tombstone; //R.I.P.
modCount++;
size--;
return true;
}
index = (index + offset++) & tMax;
}
return false; //Reached an empty spot without any hit. Not found.
}
/**
* Removes from this set all of its elements that are contained in the
* specified collection. If the specified collection is also a set, this
* operation effectively modifies this set so that its value is the
* asymmetric set difference of the two sets.
* <p>This implementation iterates over either the specified collection or
* over the set, based on which is smaller: the size of the collection or
* the capacity of the hash table. Since the hash table iterates over the
* total size of the table rather than just the elements, its table capacity
* is compared rather than the cardinality of the set. When iterating over
* the collection, each element of the collection is removed from the set if
* it is present. When iterating over the set, each element of the set is
* removed from the set if it is contained in the collection.</p>
* @param c The collection containing elements to be removed from this set.
* @return {@code true} if this set changed as a result of the call, or
* {@code false} otherwise.
* @throws ClassCastException The class of an element of the specified
* collection is not a subclass of the types of elements in this set.
* @throws NullPointerException The specified collection is {@code null}.
*/
@Override
public boolean removeAll(final Collection<?> c) {
if(c == null) {
throw new NullPointerException("The specified collection to remove all elements from is null.");
}
final Object[] t = table; //Local cache for speed without JIT.
int removedElements = 0;
//Pick whichever method is fastest:
if(table.length > c.size() || (c instanceof List && table.length > Math.sqrt(c.size()))) { //Iterate over c, removing all elements from this set. Lists have linear contains() methods, so they get special treatment.
final int tMax = t.length - 1;
for(Object element : c) { //Iterate over the collection.
if(element == null) { //Don't try to remove null. Remove the object representing null instead.
element = nullElement;
}
//Compute the desired bucket for the element.
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
Object elem;
int offset = 1;
while((elem = t[index]) != null) { //Look for the object.
if(elem.hashCode() == hash && elem.equals(element)) { //This is the element we seek.
t[index] = tombstone; //R.I.P.
removedElements++;
break;
}
index = (index + offset++) & tMax;
}
//Element not found. Continue with the next element.
}
if(removedElements >= 0) { //That actually removed something.
modCount++;
size -= removedElements;
return true;
}
return false;
}
//Otherwise, iterate over the set, removing all elements that are in c.
for(int i = t.length - 1;i >= 0;i--) {
final Object elem;
if((elem = t[i]) != null && elem != tombstone && ((elem == nullElement && c.contains(null)) || c.contains(elem))) { //If it's the null-element, check if c has a null-element. Otherwise, just check for the element itself.
t[i] = tombstone; //R.I.P.
removedElements++;
}
}
if(removedElements >= 0) { //That actually removed something.
modCount++;
size -= removedElements;
return true;
}
return false;
}
/**
* Retains only the elements in this set that are contained in the specified
* collection. In other words, removes from this set all of its elements
* that are not contained in the specified collection. When the method call
* returns, the set will contain the intersection of the original elements
* of the set and the elements of the collection.
* <p>This implementation iterates over the elements of the set and checks
* for each element whether it is contained in the specified collection,
* removing it if it is not contained.</p>
* <p>List collections get special treatment. Their
* {@link List#contains(Object)} method is generally linear-time and their
* iterator constant per element. Therefore, when encountered with a list of
* reasonable size, this method will instead clear the set and then iterate
* over the list, re-adding those elements that were in the original set.
* </p>
* @param c The collection to retain the elements from.
* @return {@code true} if this set changed as a result of the call, or
* {@code false} otherwise.
* @throws ClassCastException The class of an element of the specified
* collection is not a subclass of the elements of this set.
* @throws NullPointerException The specified collection is {@code null}.
*/
@Override
public boolean retainAll(final Collection<?> c) {
if(c == null) {
throw new NullPointerException("The specified collection to retain all elements from is null.");
}
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
if(c instanceof List && t.length > Math.sqrt(c.size())) { //Lists have linear contains() methods and will get special treatment.
//Iterate over the list and add all elements that are both in the list and in the original table.
final Object[] newTable = new Object[t.length];
final int tMax = t.length - 1;
int retainedElements = 0;
for(Object element : c) { //See if it's in the original hash table.
if(element == null) { //Don't try to find null. Find the object representing null instead.
element = nullElement;
}
//Compute the desired bucket for the element.
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (length - 1 has all bits on, since length is a power of 2). Same as modulo length.
Object elem;
int offset = 1;
while((elem = t[index]) != null) { //Look for the object.
if(elem == tombstone) { //Copy over tombstones as well, or we'd have to rehash everything.
newTable[index] = elem;
} else if(elem.hashCode() == hash && elem.equals(element)) { //Found it!
newTable[index] = elem; //Copy it to the new table.
t[index] = tombstone; //Don't find it a second time.
retainedElements++;
break;
}
index = (index + offset++) & tMax;
}
//Element not found. Continue with the next element.
}
for(int i = tMax;i >= 0;i--) { //Place tombstones in the new table where elements have been removed.
if(t[i] != null && newTable[i] == null) {
newTable[i] = tombstone;
}
}
table = newTable; //Use the new table. The old one was modified anyhow.
if(retainedElements < size) { //That actually removed something.
modCount++;
size = retainedElements;
return true;
}
return false;
}
int removedElements = 0;
for(int i = t.length - 1;i >= 0;i--) {
final Object elem;
if((elem = t[i]) != null && elem != tombstone && ((elem == nullElement && !c.contains(null)) || !c.contains(elem))) { //If it's the null-element, check if c has a null-element. Otherwise, just check for the element itself.
t[i] = tombstone; //R.I.P.
removedElements++;
}
}
if(removedElements > 0) { //That actually removed something.
modCount++;
size -= removedElements;
return true;
}
return false;
}
/**
* Returns the number of elements in this set.
* @return The number of elements in this set.
*/
@Override
public int size() {
return size;
}
/**
* Returns an array containing all of the elements in this set. The elements
* are in no particular order.
* <p>The returned array will be "safe" in that no references to it are
* maintained by this set. The caller is thus free to modify the returned
* array; it will not have any effect on the set.</p>
* <p>This implementation searches through the hash table for active
* elements and copies every element it finds to the resulting array.
* @return An array containing all of the elements in this set.
*/
@Override
public Object[] toArray() {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
final Object[] result = new Object[size];
int pos = 0; //Position in the result table to put the next element.
for(int i = t.length - 1;i >= 0;i--) {
final Object elem = t[i];
if(elem != null && elem != tombstone) {
if(elem == nullElement) {
pos++; //This element in the result can remain null.
} else {
result[pos++] = elem;
}
}
}
return result;
}
/**
* Returns an array containing all of the elements in this set; the runtime
* type of the returned array is that of the specified array. If the set
* fits in the specified array, it is returned therein. Otherwise, a new
* array is allocated with the runtime type of the specified array and the
* size of this set.
* <p>If this set fits in the specified array with room to spare (i.e. the
* array has more elements than this set), the elements following the end of
* the set remain {@code null}.</p>
* <p>The elements are returned in no particular order.</p>
* @param <E> The type of elements in the new array.
* @param a The array into which the elements of this set are to be stored,
* if it is big enough; otherwise, a new array of the same runtime type is
* allocated for this purpose.
* @return An array containing all of the elements in this set.
* @throws ArrayStoreException The runtime type of the specified array is
* not a supertype of the runtime type of every element in this collection.
* @throws NullPointerException The specified array is {@code null}.
*/
@Override
@SuppressWarnings("unchecked") //The reflection array creation, and casting Objects from the hash table to E's for the result.
public <E> E[] toArray(final E[] a) {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
final E[] result;
if(a.length >= size) { //Array suffices.
result = a;
} else { //Too many elements for the array.
result = (E[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(),size); //Allocate a new array.
}
int pos = 0; //Position in the result table to put the next element.
for(int i = t.length - 1;i >= 0;i--) {
final E elem = (E)t[i]; //Safe cast, since t[] contains only E's.
if(elem != null && elem != tombstone) {
if(elem == nullElement) {
pos++; //This element in the result can remain null.
} else {
result[pos++] = elem;
}
}
}
return result;
}
/**
* Returns a {@code String} representation of this set. The {@code String}
* representation reflects the mathematical notation of a set. It consists
* of a list of the set's elements, in no particular order, enclosed in
* curly brackets ({@code "{}"}). Adjacent elements are separated
* by commas (","). Elements are converted to strings by their
* {@link Object#toString()} methods.
* @return A {@code String} representation of this set.
*/
@Override
public String toString() {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
final int s = size;
final StringBuilder result = new StringBuilder(2 + 5 * s); //Reserve 2 chars for brackets, 4 for each element and 1 for the commas after each element.
result.append('{');
int count = 0; //The number of elements found so far. This tells us whether this is the last element (to append a comma or not).
for(int i = t.length - 1;i >= 0;i--) {
final Object elem = t[i];
if(elem != null && elem != tombstone) { //Found an element.
if(elem == this) { //Don't go into infinite recursion if it contains itself!
result.append("(this Set)");
} else if(elem == nullElement) { //This one has a special string: null.
result.append("null");
} else {
result.append(elem); //Calls the toString() method.
}
if(++count < s) { //That was not the last element. Add a comma.
result.append(',');
}
}
}
result.append('}');
return result.toString(); //Finalise and return.
}
/**
* Helper method to rehash the table to a new size. A new array will be
* allocated for the hash table with the specified capacity. All elements in
* the old table will be rehashed and placed in the new table.
* @param newCapacity The capacity of the new hash table. This must be a
* power of {@code 2}!
*/
protected void resize(final int newCapacity) {
final Object[] newTable = new Object[newCapacity];
final int tMax = newCapacity - 1;
for(int i = table.length - 1;i >= 0;i--) {
final Object element = table[i];
if(element == null || element == tombstone) { //This bucket was empty. And don't put tombstones in the new table either.
continue;
}
final int hash = element.hashCode();
int index = hash ^ ((hash >>> 20) ^ (hash >>> 12)); //These shifts ensure that hash codes that differ only by constant multiples are at each bit position have a bounded number of collisions.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & tMax; //Keep only the lower bits (newCapacity - 1 has all bits on, since newCapacity is a power of 2). Same as modulo length.
int offset = 1;
while(newTable[index] != null) { //Search for a spot to place it.
index = (index + offset++) & tMax;
}
//Since newTable[index] is now null due to the while loop, we have an empty spot for the element.
newTable[index] = element;
}
table = newTable; //Use the new table from now on.
treshold = Math.min((int)(newCapacity * loadFactor),maximumCapacity + 1); //Set a new treshold for the next rehash.
}
/**
* Reconstitute the {@code HashSet} instance from a stream (that is,
* deserialise it).
* @param s The stream to read the state of a {@code HashSet} from.
* @throws ClassNotFoundException The SerialVersionUID of the class does not
* match any known version of {@code HashSet}.
* @throws IOException Something went wrong reading from the specified
* stream.
*/
private void readObject(final ObjectInputStream s) throws IOException,ClassNotFoundException {
s.defaultReadObject(); //Read the default serialisation magic.
final int capacity = s.readInt(); //Read table capacity.
final Object[] t = new Object[capacity]; //Create the actual hash table for the hash set.
loadFactor = s.readFloat(); //Read load factor.
size = s.readInt(); //Read size.
for(int i = size - 1;i >= 0;i--) { //Read each element.
final Object element = s.readObject(); //Read the element itself.
final int hashCode = element.hashCode();
int index = hashCode ^ ((hashCode >>> 20) ^ (hashCode >>> 12)); //Find the index at which to place it.
index = (index ^ (index >>> 7) ^ (index >>> 4)) & (capacity - 1);
t[index] = element; //Store it at that location.
}
table = t; //Store the hash table in the object.
treshold = (int)(table.length * loadFactor);
}
/**
* Save the state of this {@code HashSet} instance to a stream (that is,
* serialise it).
* @serialData The capacity ({@code int}) and load factor ({@code float}) of
* the hash table are emitted, followed by the number of elements in the set
* ({@code int}), followed by all elements ({@code Object}s) in no
* particular order.
* @param s The stream to write the state of this {@code HashSet} to.
* @throws IOException Something went wrong writing to the specified stream.
*/
private void writeObject(final ObjectOutputStream s) throws IOException {
Object[] t = table; //Cache a local copy for faster access without JIT compiler.
s.defaultWriteObject(); //Write the default serialisation magic.
s.writeInt(t.length); //Write table capacity.
s.writeFloat(loadFactor); //Write load factor.
s.writeInt(size); //Write size.
for(int i = t.length - 1;i >= 0;i--) {
if(t[i] != null) {
s.writeObject(t[i]); //Write out each element.
}
}
}
/**
* This is a custom implementation of {@link Iterator} that iterates over
* the elements of a hash set. The iterator gives the elements of the set in
* no particular order. The actual order will be the reverse order of the
* elements in the set as they are ordered in the internal hash table of the
* set.
* <p>Note that the iterator will search through all buckets of the hash
* table to search for the elements of the set. The time complexity of a
* complete iteration of the set scales with the capacity of the hash table
* plus the number of elements in the set. Also, the time between two
* consecutive calls to {@link Iterator#next()} may vary.</p>
* <p>The iterator is fail-fast, which means that if a structural
* modification is made to the hash set after this method call, the iterator
* will throw a {@link ConcurrentModificationException} when {@link #next()}
* or {@link #remove()} is called. This behaviour prevents nondeterministic
* or unexpected behaviour caused by the concurrent modification of the set
* while it is being iterated over. Rather than giving inconsequent results,
* it always fails to give a result.</p>
*/
protected class Itr implements Iterator<E> {
/**
* The expected modification count of the accompanying {@code HashSet}.
* If this is different from the actual modification count of the set, a
* concurrent modification on the set has occurred and every method
* should throw a {@link ConcurrentModificationException}.
*/
protected int expectedModCount;
/**
* The current slot in the iteration. If this index is negative, the
* iteration is complete.
*/
protected int index;
/**
* The index of the last element that was returned by a call to
* {@link #next()}. This element will be removed from the table if
* {@link #remove()} would be called. A value of -1 indicates that
* {@link #next()} has not yet been called or not since the last call to
* {@link #remove()} (or that {@link #next()} didn't return an element).
*/
protected int last = -1;
/**
* Creates a new iterator over the {@code HashSet}. The iterator will
* start at the last element in the table, iterating towards index
* {@code 0}.
*/
protected Itr() {
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
for(index = t.length - 1;index >= 0 && t[index] == null || t[index] == tombstone;index--); //Set index in advance to the index of the first element.
expectedModCount = modCount; //Store the modCount of the HashSet. From here, concurrent modification will throw an exception.
}
/**
* Returns {@code true} if the iteration has more elements. In other
* words, returns {@code true} if {@link #next()} would return an
* element of the set rather than throwing a
* {@code NoSuchElementException}.
* @return {@code true} if the iteration has more elements, or
* {@code false} otherwise.
*/
@Override
public boolean hasNext() {
return index >= 0;
}
/**
* Returns the next element in the iteration.
* @return The next element in the iteration.
* @throws ConcurrentModificationException The set was structurally
* modified between the constructing of this iterator and the calling of
* this method.
* @throws NoSuchElementException The iteration has no more elements.
*/
@Override
@SuppressWarnings("unchecked") //Caused by the casting of a table element to the returned E.
public E next() {
if(modCount != expectedModCount) { //Some concurrent modification has been made on the set!
throw new ConcurrentModificationException();
}
if(index < 0) { //We're through the array.
last = -1;
throw new NoSuchElementException();
}
final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
last = index;
for(index--;index >= 0 && (t[index] == null || t[index] == tombstone);index--); //Set the index on the next position.
if(t[last] == nullElement) {
return null; //Return null instead of the element representing null.
}
return (E)t[last]; //Safe cast, since the table contains only E's.
}
/**
* Removes from the set the last element returned by this iterator. This
* method can be called only once per call to {@link #next()}.
* @throws ConcurrentModificationException The set was structurally
* modified between the constructing of this iterator and the calling of
* this method.
* @throws IllegalStateException The {@link #next()} method has not yet
* been called, or the {@code remove()} method has already been called
* after the last call to the {@code next()} method.
*/
@Override
public void remove() {
if(last < 0) { //Nothing to remove.
throw new IllegalStateException();
}
if(modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
//Delete the element at 'last'.
if(table[last] != null && table[last] != tombstone) {
table[last] = tombstone; //R.I.P.
size--;
modCount++;
expectedModCount = modCount; //This modification is expected since the iterator made it.
last = -1; //Set this to negative so the next call doesn't try to remove it again.
}
}
}
} | Fix iterator constructor starting index
Communativity was wrong, should've been in brackets to start the
iterator at the correct place.
| src/net/dulek/collections/HashSet.java | Fix iterator constructor starting index | <ide><path>rc/net/dulek/collections/HashSet.java
<ide> */
<ide> protected Itr() {
<ide> final Object[] t = table; //Cache a local copy for faster access without JIT compiler.
<del> for(index = t.length - 1;index >= 0 && t[index] == null || t[index] == tombstone;index--); //Set index in advance to the index of the first element.
<add> for(index = t.length - 1;index >= 0 && (t[index] == null || t[index] == tombstone);index--); //Set index in advance to the index of the first element.
<ide> expectedModCount = modCount; //Store the modCount of the HashSet. From here, concurrent modification will throw an exception.
<ide> }
<ide> |
|
JavaScript | apache-2.0 | 8906299ae1f5a66325dfd240a85b819119678ae6 | 0 | youtube/js_mse_eme,youtube/js_mse_eme,youtube/js_mse_eme | /*
Copyright 2018 Google 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.
*/
'use strict';
/**
* MSE Conformance Test Suite.
* @class
*/
var ConformanceTest = function() {
var mseVersion = 'Current Editor\'s Draft';
var webkitPrefix = MediaSource.prototype.version.indexOf('webkit') >= 0;
var tests = [];
var info = 'No MSE Support!';
if (window.MediaSource) {
info = 'MSE Spec Version: ' + mseVersion;
info += ' | webkit prefix: ' + webkitPrefix.toString();
}
info += ' | Default Timeout: ' + TestBase.timeout + 'ms';
var fields = ['passes', 'failures', 'timeouts'];
var createConformanceTest = function(name, category, mandatory) {
var t = createMSTest(name);
t.prototype.index = tests.length;
t.prototype.passes = 0;
t.prototype.failures = 0;
t.prototype.timeouts = 0;
t.prototype.category = category || 'General';
if (typeof mandatory === 'boolean') {
t.prototype.mandatory = mandatory;
}
tests.push(t);
return t;
};
var createInitialMediaStateTest = function(state, value, check) {
var test = createConformanceTest('InitialMedia' +
util.MakeCapitalName(state), 'Media Element Core');
check = typeof(check) === 'undefined' ? 'checkEq' : check;
test.prototype.title = 'Test if the state ' + state +
' is correct when onsourceopen is called';
test.prototype.onsourceopen = function() {
this.runner[check](this.video[state], value, state);
this.runner.succeed();
};
};
createInitialMediaStateTest('duration', NaN);
createInitialMediaStateTest('videoWidth', 0);
createInitialMediaStateTest('videoHeight', 0);
createInitialMediaStateTest('readyState', HTMLMediaElement.HAVE_NOTHING);
createInitialMediaStateTest('src', '', 'checkNE');
createInitialMediaStateTest('currentSrc', '', 'checkNE');
var testXHRUint8Array = createConformanceTest('XHRUint8Array', 'XHR');
testXHRUint8Array.prototype.title = 'Ensure that XHR can send an Uint8Array';
testXHRUint8Array.prototype.timeout = 10000;
testXHRUint8Array.prototype.start = function(runner, video) {
var s = 'XHR DATA';
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i < s.length; i++) {
view[i] = s.charCodeAt(i);
}
var xhr = runner.XHRManager.createPostRequest(
'https://drmproxy.appspot.com/echo',
function(e) {
runner.checkEq(String.fromCharCode.apply(null, xhr.getResponseData()),
s, 'XHR response');
runner.succeed();
},
view.length);
xhr.send(view);
};
var testXHRAbort = createConformanceTest('XHRAbort', 'XHR');
testXHRAbort.prototype.title = 'Ensure that XHR aborts actually abort by ' +
'issuing an absurd number of them and then aborting all but one.';
testXHRAbort.prototype.start = function(runner, video) {
var N = 100;
var startTime = Date.now();
var lastAbortTime;
function startXHR(i) {
var xhr = runner.XHRManager.createRequest(
Media.VP9.VideoNormal.src + '?x=' + Date.now() + '.' + i, function() {
if (i >= N) {
xhr.getResponseData(); // This will verify status internally.
runner.succeed();
}
});
if (i < N) {
runner.timeouts.setTimeout(xhr.abort.bind(xhr), 10);
runner.timeouts.setTimeout(startXHR.bind(null, i + 1), 1);
lastAbortTime = Date.now();
}
xhr.send();
};
startXHR(0);
};
var testXHROpenState = createConformanceTest('XHROpenState', 'XHR');
testXHROpenState.prototype.title = 'Ensure XMLHttpRequest.open does not ' +
'reset XMLHttpRequest.responseType';
testXHROpenState.prototype.start = function(runner, video) {
var xhr = new XMLHttpRequest;
// It should not be an error to set responseType before calling open
xhr.responseType = 'arraybuffer';
xhr.open('GET', 'http://google.com', true);
runner.checkEq(xhr.responseType, 'arraybuffer', 'XHR responseType');
runner.succeed();
};
var testPresence = createConformanceTest('Presence', 'MSE Core');
testPresence.prototype.title = 'Test if MediaSource object is present.';
testPresence.prototype.start = function(runner, video) {
if (!window.MediaSource)
return runner.fail('No MediaSource object available.');
var ms = new MediaSource();
if (!ms)
return runner.fail('Found MediaSource but could not create one');
if (ms.version)
this.log('Media source version reported as ' + ms.version);
else
this.log('No media source version reported');
runner.succeed();
};
var testAttach = createConformanceTest('Attach', 'MSE Core');
testAttach.prototype.timeout = 2000;
testAttach.prototype.title =
'Test if MediaSource object can be attached to video.';
testAttach.prototype.start = function(runner, video) {
this.ms = new MediaSource();
this.ms.addEventListener('sourceopen', function() {
runner.succeed();
});
video.src = window.URL.createObjectURL(this.ms);
video.load();
};
var testAddSourceBuffer = createConformanceTest('AddSourceBuffer', 'MSE Core');
testAddSourceBuffer.prototype.title =
'Test if we can add source buffer';
testAddSourceBuffer.prototype.onsourceopen = function() {
try {
this.runner.checkEq(this.ms.sourceBuffers.length, 0, 'Source buffer number');
this.ms.addSourceBuffer(Media.AAC.mimetype);
this.runner.checkEq(this.ms.sourceBuffers.length, 1, 'Source buffer number');
this.ms.addSourceBuffer(Media.VP9.mimetype);
this.runner.checkEq(this.ms.sourceBuffers.length, 2, 'Source buffer number');
} catch (e) {
this.runner.fail(e);
}
this.runner.succeed();
};
var testAddSourceBufferException = createConformanceTest('AddSBException',
'MSE Core');
testAddSourceBufferException.prototype.title = 'Test if add incorrect source ' +
'buffer type will fire the correct exceptions.';
testAddSourceBufferException.prototype.onsourceopen = function() {
var runner = this.runner;
var self = this;
runner.checkException(function() {
self.ms.addSourceBuffer('^^^');
}, DOMException.NOT_SUPPORTED_ERR);
runner.checkException(function() {
var ms = new MediaSource;
ms.addSourceBuffer(Media.AAC.mimetype);
}, DOMException.INVALID_STATE_ERR);
runner.succeed();
};
var testSourceRemove = createConformanceTest('RemoveSourceBuffer', 'MSE Core');
testSourceRemove.prototype.title = 'Test if we can add/remove source buffers';
testSourceRemove.prototype.onsourceopen = function() {
var sb = this.ms.addSourceBuffer(Media.AAC.mimetype);
this.ms.removeSourceBuffer(sb);
this.runner.checkEq(this.ms.sourceBuffers.length, 0, 'Source buffer number');
this.ms.addSourceBuffer(Media.AAC.mimetype);
this.runner.checkEq(this.ms.sourceBuffers.length, 1, 'Source buffer number');
for (var i = 0; i < 10; ++i) {
try {
sb = this.ms.addSourceBuffer(Media.VP9.mimetype);
this.runner.checkEq(this.ms.sourceBuffers.length, 2,
'Source buffer number');
this.ms.removeSourceBuffer(sb);
this.runner.checkEq(this.ms.sourceBuffers.length, 1,
'Source buffer number');
} catch (e) {
return this.runner.fail(e);
}
}
this.runner.succeed();
};
var createInitialMSStateTest = function(state, value, check) {
var test = createConformanceTest('InitialMS' + util.MakeCapitalName(state),
'MSE Core');
check = typeof(check) === 'undefined' ? 'checkEq' : check;
test.prototype.title = 'Test if the state ' + state +
' is correct when onsourceopen is called';
test.prototype.onsourceopen = function() {
this.runner[check](this.ms[state], value, state);
this.runner.succeed();
};
};
createInitialMSStateTest('duration', NaN);
createInitialMSStateTest('readyState', 'open');
var testDuration = createConformanceTest('Duration', 'MSE Core');
testDuration.prototype.title =
'Test if we can set duration.';
testDuration.prototype.onsourceopen = function() {
this.ms.duration = 10;
this.runner.checkEq(this.ms.duration, 10, 'ms.duration');
this.runner.succeed();
};
var mediaElementEvents = createConformanceTest('MediaElementEvents', 'MSE Core');
mediaElementEvents.prototype.title = 'Test events on the MediaElement.';
mediaElementEvents.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var audioStream = Media.AAC.Audio1MB;
var videoStream = Media.VP9.Video1MB;
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var self = this;
var videoXhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
self.log('onload called');
var onUpdate = function() {
videoSb.removeEventListener('update', onUpdate);
setDuration(1.0, ms, [videoSb, audioSb], function() {
if (audioSb.updating || videoSb.updating) {
runner.fail('Source buffers are updating on duration change.');
return;
}
ms.endOfStream();
media.play();
});
}
videoSb.addEventListener('update', onUpdate);
videoSb.appendBuffer(videoXhr.getResponseData());
});
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
self.log('onload called');
var onAudioUpdate = function() {
audioSb.removeEventListener('update', onAudioUpdate);
videoXhr.send();
}
audioSb.addEventListener('update', onAudioUpdate);
audioSb.appendBuffer(audioXhr.getResponseData());
});
media.addEventListener('ended', function() {
self.log('onended called');
runner.succeed();
});
audioXhr.send();
};
var mediaSourceEvents = createConformanceTest('MediaSourceEvents', 'MSE Core');
mediaSourceEvents.prototype.title = 'Test if the events on MediaSource are correct.';
mediaSourceEvents.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var audioStream = Media.AAC.Audio1MB;
var videoStream = Media.VP9.Video1MB;
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var lastState = 'open';
var self = this;
var videoXhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
self.log('onload called');
videoSb.appendBuffer(videoXhr.getResponseData());
videoSb.abort();
ms.endOfStream();
});
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
self.log('onload called');
audioSb.appendBuffer(audioXhr.getResponseData());
audioSb.abort();
videoXhr.send();
});
ms.addEventListener('sourceclose', function() {
self.log('onsourceclose called');
runner.checkEq(lastState, 'ended', 'The previous state');
runner.succeed();
});
ms.addEventListener('sourceended', function() {
self.log('onsourceended called');
runner.checkEq(lastState, 'open', 'The previous state');
lastState = 'ended';
media.removeAttribute('src');
media.load();
});
audioXhr.send();
};
var testBufferSize = createConformanceTest('VideoBufferSize', 'MSE Core');
testBufferSize.prototype.title = 'Determines video buffer sizes by ' +
'appending incrementally until discard occurs, and tests that it meets ' +
'the minimum requirements for streaming.';
testBufferSize.prototype.onsourceopen = function() {
var runner = this.runner;
// The test clip has a bitrate which is nearly exactly 1MB/sec, and
// lasts 1s. We start appending it repeatedly until we get eviction.
var videoStream = Media.VP9.Video1MB;
var sb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioStream = Media.AAC.Audio1MB;
var unused_audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
var MIN_SIZE = 12 * 1024 * 1024;
var ESTIMATED_MIN_TIME = 12;
var xhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
var onBufferFull = function() {
runner.checkGE(expectedTime - sb.buffered.start(0), ESTIMATED_MIN_TIME,
'Estimated source buffer size');
runner.succeed();
};
var expectedTime = 0;
var expectedSize = 0;
var appendCount = 0;
sb.addEventListener('updateend', function onUpdate() {
appendCount++;
self.log('Append count ' + appendCount);
if (sb.buffered.start(0) > 0 || expectedTime > sb.buffered.end(0)) {
sb.removeEventListener('updateend', onUpdate);
onBufferFull();
} else {
expectedTime += videoStream.duration;
expectedSize += videoStream.size;
// Pass the test if the UA can handle 10x more than expected.
if (expectedSize > (10 * MIN_SIZE)) {
sb.removeEventListener('updateend', onUpdate);
onBufferFull();
return;
}
sb.timestampOffset = expectedTime;
try {
sb.appendBuffer(xhr.getResponseData());
} catch (e) {
var QUOTA_EXCEEDED_ERROR_CODE = 22;
if (e.code == QUOTA_EXCEEDED_ERROR_CODE) {
sb.removeEventListener('updateend', onUpdate);
onBufferFull();
} else {
runner.fail(e);
}
}
}
});
sb.appendBuffer(xhr.getResponseData());
});
xhr.send();
};
var testStartPlayWithoutData = createConformanceTest('StartPlayWithoutData',
'MSE Core');
testStartPlayWithoutData.prototype.title =
'Test if we can start play before feeding any data. The play should ' +
'start automatically after data is appended';
testStartPlayWithoutData.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var audioStream = Media.AAC.AudioHuge;
var videoStream = Media.VP9.VideoHuge;
var videoChain = new ResetInit(
new FileSource(videoStream.src, runner.XHRManager, runner.timeouts));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioChain = new ResetInit(
new FileSource(audioStream.src, runner.XHRManager, runner.timeouts));
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
media.play();
appendUntil(runner.timeouts, media, videoSb, videoChain, 1, function() {
appendUntil(runner.timeouts, media, audioSb, audioChain, 1, function() {
playThrough(
runner.timeouts, media, 1, 2,
videoSb, videoChain, audioSb, audioChain, function() {
runner.checkGE(media.currentTime, 2, 'currentTime');
runner.succeed();
});
});
});
};
var testEventTimestamp = createConformanceTest('EventTimestamp', 'MSE Core');
testEventTimestamp.prototype.title = 'Test Event Timestamp is relative to ' +
'the initial page load';
testEventTimestamp.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
var videoStream = Media.VP9.VideoTiny;
var audioStream = Media.AAC.AudioTiny;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
runner.checkGr(Date.now(), 1360000000000, 'Date.now()');
var lastTime = 0.0;
var requestCounter = 0;
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.appendBuffer(this.getResponseData());
video.addEventListener('timeupdate', function(e) {
runner.checkGE(e.timeStamp, lastTime, 'event.timeStamp');
lastTime = e.timeStamp;
if (!video.paused && video.currentTime >= 2 && requestCounter >= 3) {
runner.succeed();
}
requestCounter++;
});
video.play();
}, 0, 500000);
var videoXhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
videoSb.appendBuffer(this.getResponseData());
audioXhr.send();
}, 0, 1500000);
videoXhr.send();
};
var testSeekTimeUpdate = createConformanceTest('SeekTimeUpdate', 'MSE Core');
testSeekTimeUpdate.prototype.title =
'Timeupdate event fired with correct currentTime after seeking.';
testSeekTimeUpdate.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var videoStream = Media.VP9.VideoNormal;
var audioStream = Media.AAC.AudioNormal;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var lastTime = 0;
var updateCount = 0;
var xhr = runner.XHRManager.createRequest(videoStream.src, function() {
videoSb.appendBuffer(xhr.getResponseData());
var xhr2 = runner.XHRManager.createRequest(audioStream.src, function() {
audioSb.appendBuffer(xhr2.getResponseData());
callAfterLoadedMetaData(media, function() {
media.addEventListener('timeupdate', function(e) {
if (!media.paused) {
++updateCount;
runner.checkGE(media.currentTime, lastTime, 'media.currentTime');
if (updateCount > 3) {
updateCount = 0;
lastTime += 10;
if (lastTime >= 35)
runner.succeed();
else
media.currentTime = lastTime + 6;
}
}
});
media.play();
});
}, 0, 1000000);
xhr2.send();
}, 0, 5000000);
this.ms.duration = 100000000; // Ensure that we can seek to any position.
xhr.send();
};
/**
* Creates a MSE currentTime Accuracy test to validate if the media.currentTime
* is accurate to within 250 milliseconds during active playback. This can
* be used for video features a standard frame rate or a high frame rate.
*/
var createCurrentTimeAccuracyTest =
function(videoStream, audioStream, frameRate) {
var test = createConformanceTest(
frameRate + 'Accuracy', 'MSE currentTime');
test.prototype.title = 'Test the currentTime granularity.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
var maxTimeDiff = 0;
var baseTimeDiff = 0;
var times = 0;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoXhr = runner.XHRManager.createRequest(
videoStream.src, function(e) {
videoSb.appendBuffer(this.getResponseData());
video.addEventListener('timeupdate', function(e) {
if (times === 0) {
baseTimeDiff = util.ElapsedTimeInS() - video.currentTime;
} else {
var timeDiff = util.ElapsedTimeInS() - video.currentTime;
maxTimeDiff = Math.max(
Math.abs(timeDiff - baseTimeDiff), maxTimeDiff);
}
if (times > 500 || video.currentTime > 10) {
runner.checkLE(
maxTimeDiff, 0.25, 'media.currentTime diff during playback');
runner.succeed();
}
++times;
});
video.play();
}, 0, 2500000);
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.appendBuffer(this.getResponseData());
videoXhr.send();
}, 0, 2500000);
audioXhr.send();
};
};
createCurrentTimeAccuracyTest(
Media.VP9.Webgl720p30fps, Media.AAC.AudioNormal, 'SFR');
createCurrentTimeAccuracyTest(
Media.VP9.Webgl720p60fps, Media.AAC.AudioNormal, 'HFR');
/**
* Creates a MSE currentTime PausedAccuracy test to validate if
* the media.currentTime is accurate to within 32 milliseconds when content
* is paused. This can be used for video features a standard frame rate
* or a high frame rate. Test checks the accuracy of media.currentTime at
* two events: when content is paused and when content is played again after
* the pause, if either one meets the threshold, test passes.
*/
var createCurrentTimePausedAccuracyTest =
function(videoStream, audioStream, frameRate) {
var test = createConformanceTest(
frameRate + 'PausedAccuracy', 'MSE currentTime', false);
test.prototype.title = 'Test the currentTime granularity when pause.';
test.prototype.onsourceopen = function() {
var maxDiffInS = 0.032;
var runner = this.runner;
var video = this.video;
var baseTimeDiff = 0;
var times = 0;
var assertTimeAtPlay = false;
var currentTimeIsAccurate = false;
var self = this;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoXhr = runner.XHRManager.createRequest(
videoStream.src, function(e) {
videoSb.appendBuffer(this.getResponseData());
function onTimeUpdate(e) {
if (times === 0) {
baseTimeDiff = util.ElapsedTimeInS() - video.currentTime;
}
if (times > 500 || video.currentTime > 10) {
video.removeEventListener('timeupdate', onTimeUpdate);
video.pause();
}
++times;
};
video.addEventListener('play', function() {
if (assertTimeAtPlay) {
var timeDiff = util.ElapsedTimeInS() - video.currentTime;
var currentTimeDiff = Math.abs(baseTimeDiff - timeDiff);
self.log('media.currentTime is ' + currentTimeDiff + 's different' +
' from actual time when video is played after a pause.');
currentTimeIsAccurate =
currentTimeIsAccurate || (currentTimeDiff <= maxDiffInS);
runner.checkEq(
currentTimeIsAccurate,
true,
'media.currentTime diff is within ' + maxDiffInS + 's');
assertTimeAtPlay = false;
runner.succeed();
}
});
video.addEventListener('pause', function(e) {
var timeDiff = util.ElapsedTimeInS() - video.currentTime;
var currentTimeDiff = Math.abs(baseTimeDiff - timeDiff);
runner.checkEq(video.paused, true, 'media.paused');
self.log('meida.currentTime is ' + currentTimeDiff +
's different from actual time when video is paused.');
currentTimeIsAccurate = currentTimeDiff <= maxDiffInS;
assertTimeAtPlay = true;
video.play();
});
video.addEventListener('timeupdate', onTimeUpdate);
video.play();
}, 0, 2500000);
var audioXhr = runner.XHRManager.createRequest(
audioStream.src, function(e) {
audioSb.appendBuffer(this.getResponseData());
videoXhr.send();
}, 0, 2500000);
audioXhr.send();
};
};
createCurrentTimePausedAccuracyTest(
Media.VP9.Webgl720p30fps, Media.AAC.AudioNormal, 'SFR');
createCurrentTimePausedAccuracyTest(
Media.VP9.Webgl720p60fps, Media.AAC.AudioNormal, 'HFR');
var createSupportTest = function(mimetype, desc) {
var test = createConformanceTest(desc + 'Support', 'MSE Formats');
test.prototype.title =
'Test if we support ' + desc + ' with mimetype: ' + mimetype;
test.prototype.onsourceopen = function() {
try {
this.log('Trying format ' + mimetype);
var src = this.ms.addSourceBuffer(mimetype);
} catch (e) {
return this.runner.fail(e);
}
this.runner.succeed();
};
};
createSupportTest(Media.AAC.mimetype, 'AAC');
createSupportTest(Media.H264.mimetype, 'H264');
createSupportTest(Media.VP9.mimetype, 'VP9');
createSupportTest(Media.Opus.mimetype, 'Opus');
var createAppendTest = function(stream, unused_stream) {
var test = createConformanceTest(
'Append' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if we can append a whole ' +
stream.mediatype + ' file whose size is 1MB.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var xhr = runner.XHRManager.createRequest(stream.src, function(e) {
var data = xhr.getResponseData();
function updateEnd(e) {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(sb.buffered.end(0), stream.duration, 'Range end');
// Try appending twice in a row --
// this should throw an INVALID_STATE_ERR exception.
var caught = false;
try {
sb.removeEventListener('updateend', updateEnd);
sb.appendBuffer(data);
sb.appendBuffer(data);
}
catch (e) {
if (e.code === e.INVALID_STATE_ERR) {
runner.succeed();
} else {
runner.fail('Invalid error on double append: ' + e);
}
caught = true;
}
if (!caught) {
// We may have updated so fast that we didn't encounter the error.
if (sb.updating) {
// Not a great check due to race conditions, but will have to do.
runner.fail('Implementation did not throw INVALID_STATE_ERR.');
} else {
runner.succeed();
}
}
}
sb.addEventListener('updateend', updateEnd);
sb.appendBuffer(data);
});
xhr.send();
};
};
var createAbortTest = function(stream, unused_stream) {
var test = createConformanceTest(
'Abort' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if we can abort the current segment.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var xhr = runner.XHRManager.createRequest(stream.src, function(e) {
var responseData = xhr.getResponseData();
var abortEnded = function(e) {
sb.removeEventListener('updateend', abortEnded);
sb.addEventListener('update', function(e) {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkGr(sb.buffered.end(0), 0, 'Range end');
runner.succeed();
});
sb.appendBuffer(responseData);
}
var appendStarted = function(e) {
sb.removeEventListener('update', appendStarted);
sb.addEventListener('updateend', abortEnded);
sb.abort();
}
sb.addEventListener('update', appendStarted);
sb.appendBuffer(responseData);
}, 0, stream.size);
xhr.send();
};
};
var createTimestampOffsetTest = function(stream, unused_stream) {
var test = createConformanceTest(
'TimestampOffset' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if we can set timestamp offset.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var xhr = runner.XHRManager.createRequest(stream.src, function(e) {
sb.timestampOffset = 5;
sb.appendBuffer(xhr.getResponseData());
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 5, 'Range start');
runner.checkApproxEq(sb.buffered.end(0), stream.duration + 5,
'Range end');
runner.succeed();
});
});
xhr.send();
};
};
var createDASHLatencyTest = function(videoStream, audioStream) {
var test = createConformanceTest('DASHLatency' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title = 'Test SourceBuffer DASH switch latency';
test.prototype.onsourceopen = function() {
var self = this;
var runner = this.runner;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var video = this.video;
var videoXhr = runner.XHRManager.createRequest(videoStream.src,
function(e) {
var videoContent = videoXhr.getResponseData();
var expectedTime = 0;
var loopCount = 0;
var MAX_ITER = 300;
var OVERFLOW_OFFSET = 1.0;
var onBufferFull = function() {
var bufferSize = loopCount * videoStream.size / 1048576;
self.log('Buffer size: ' + Math.round(bufferSize) + 'MB');
var DASH_MAX_LATENCY = 1;
var newContentStartTime = videoSb.buffered.start(0) + 2;
self.log('Source buffer updated as exceeding buffer limit');
video.addEventListener('timeupdate', function onTimeUpdate(e) {
if (video.currentTime > newContentStartTime + DASH_MAX_LATENCY) {
video.removeEventListener('timeupdate', onTimeUpdate);
runner.succeed();
}
});
video.play();
}
videoSb.addEventListener('update', function onUpdate() {
expectedTime += videoStream.duration;
videoSb.timestampOffset = expectedTime;
loopCount++;
if (loopCount > MAX_ITER) {
videoSb.removeEventListener('update', onUpdate);
runner.fail('Failed to fill up source buffer.');
return;
}
// Fill up the buffer such that it overflow implementations.
if (expectedTime > videoSb.buffered.end(0) + OVERFLOW_OFFSET) {
videoSb.removeEventListener('update', onUpdate);
onBufferFull();
}
try {
videoSb.appendBuffer(videoContent);
} catch (e) {
videoSb.removeEventListener('update', onUpdate);
var QUOTA_EXCEEDED_ERROR_CODE = 22;
if (e.code == QUOTA_EXCEEDED_ERROR_CODE) {
onBufferFull();
} else {
runner.fail(e);
}
}
});
videoSb.appendBuffer(videoContent);;
});
var audioXhr = runner.XHRManager.createRequest(audioStream.src,
function(e) {
var audioContent = audioXhr.getResponseData();
audioSb.appendBuffer(audioContent);
videoXhr.send();
});
audioXhr.send();
};
};
var createDurationAfterAppendTest = function(stream, unused_stream) {
var test = createConformanceTest(
'DurationAfterAppend' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if the duration expands after appending data.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var sb = ms.addSourceBuffer(stream.mimetype);
var unused_sb = ms.addSourceBuffer(unused_stream.mimetype);
var self = this;
var xhr = runner.XHRManager.createRequest(stream.src,
function(e) {
var data = xhr.getResponseData();
var updateCb = function() {
var halfDuration;
var durationChanged = false;
var sbUpdated = false;
sb.removeEventListener('updateend', updateCb);
sb.abort();
if (sb.updating) {
runner.fail();
return;
}
media.addEventListener('durationchange', function onDurationChange() {
media.removeEventListener('durationchange', onDurationChange);
self.log('Duration change complete.');
runner.checkApproxEq(ms.duration, halfDuration, 'ms.duration');
durationChanged = true;
if (durationChanged && sbUpdated) {
runner.succeed();
}
});
halfDuration = sb.buffered.end(0) / 2;
setDuration(halfDuration, ms, sb, function() {
self.log('Remove() complete.');
runner.checkApproxEq(ms.duration, halfDuration, 'ms.duration');
runner.checkApproxEq(sb.buffered.end(0), halfDuration,
'sb.buffered.end(0)');
sb.addEventListener('updateend', function onUpdate() {
sb.removeEventListener('updateend', onUpdate);
runner.checkApproxEq(ms.duration, sb.buffered.end(0),
'ms.duration');
sbUpdated = true;
if (durationChanged && sbUpdated) {
runner.succeed();
}
});
sb.appendBuffer(data);
});
};
sb.addEventListener('updateend', updateCb);
sb.appendBuffer(data);
});
xhr.send();
};
};
var createPausedTest = function(stream) {
var test = createConformanceTest(
'PausedStateWith' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if the paused state is correct before or ' +
' after appending data.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var sb = ms.addSourceBuffer(stream.mimetype);
runner.checkEq(media.paused, true, 'media.paused');
var xhr = runner.XHRManager.createRequest(stream.src,
function(e) {
runner.checkEq(media.paused, true, 'media.paused');
sb.appendBuffer(xhr.getResponseData());
runner.checkEq(media.paused, true, 'media.paused');
sb.addEventListener('updateend', function() {
runner.checkEq(media.paused, true, 'media.paused');
runner.succeed();
});
});
xhr.send();
};
};
var createVideoDimensionTest = function(videoStream, audioStream) {
var test = createConformanceTest('VideoDimension' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title =
'Test if the readyState transition is correct.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var videoChain = new ResetInit(new FixedAppendSize(
new FileSource(videoStream.src, runner.XHRManager, runner.timeouts),
65536));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
runner.checkEq(media.videoWidth, 0, 'video width');
runner.checkEq(media.videoHeight, 0, 'video height');
var totalSuccess = 0;
function checkSuccess() {
totalSuccess++;
if (totalSuccess == 2)
runner.succeed();
}
media.addEventListener('loadedmetadata', function(e) {
self.log('loadedmetadata called');
runner.checkEq(media.videoWidth, 640, 'video width');
runner.checkEq(media.videoHeight, 360, 'video height');
checkSuccess();
});
runner.checkEq(media.readyState, media.HAVE_NOTHING, 'readyState');
var audioXhr = runner.XHRManager.createRequest(audioStream.src,
function(e) {
var audioContent = audioXhr.getResponseData();
audioSb.appendBuffer(audioContent);
appendInit(media, videoSb, videoChain, 0, checkSuccess);
});
audioXhr.send();
};
};
var createPlaybackStateTest = function(stream) {
var test = createConformanceTest('PlaybackState' + stream.codec,
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if the playback state transition is correct.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var videoStream = stream;
var audioStream = Media.AAC.AudioTiny;
var videoChain = new ResetInit(new FixedAppendSize(
new FileSource(videoStream.src, runner.XHRManager, runner.timeouts),
65536));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioChain = new ResetInit(new FixedAppendSize(
new FileSource(audioStream.src, runner.XHRManager, runner.timeouts),
65536));
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
media.play();
runner.checkEq(media.currentTime, 0, 'media.currentTime');
media.pause();
runner.checkEq(media.currentTime, 0, 'media.currentTime');
appendInit(media, audioSb, audioChain, 0, function() {
appendInit(media, videoSb, videoChain, 0, function() {
callAfterLoadedMetaData(media, function() {
media.play();
runner.checkEq(media.currentTime, 0, 'media.currentTime');
media.pause();
runner.checkEq(media.currentTime, 0, 'media.currentTime');
media.play();
appendUntil(
runner.timeouts, media, audioSb, audioChain, 5, function() {
appendUntil(
runner.timeouts, media, videoSb, videoChain, 5, function() {
playThrough(runner.timeouts, media, 1, 2, audioSb,
audioChain, videoSb, videoChain, function() {
var time = media.currentTime;
media.pause();
runner.checkApproxEq(media.currentTime, time, 'media.currentTime');
runner.succeed();
});
});
});
});
});
});
};
};
var createPlayPartialSegmentTest = function(stream) {
var test = createConformanceTest('PlayPartial' + stream.codec + 'Segment',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if we can play a partially appended video segment.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
var videoStream = stream;
var audioStream = Media.AAC.AudioTiny;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoXhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
videoSb.appendBuffer(this.getResponseData());
video.addEventListener('timeupdate', function(e) {
if (!video.paused && video.currentTime >= 2) {
runner.succeed();
}
});
video.play();
}, 0, 1500000);
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.appendBuffer(this.getResponseData());
videoXhr.send();
}, 0, 500000);
audioXhr.send();
};
};
var createIncrementalAudioTest = function(stream) {
var test = createConformanceTest('Incremental' + stream.codec + 'Audio',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if we can play a partially appended audio segment.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(Media.VP9.mimetype);
var xhr = runner.XHRManager.createRequest(stream.src, function(e) {
sb.appendBuffer(xhr.getResponseData());
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(sb.buffered.end(0), stream.get(200000), 'Range end');
runner.succeed();
});
}, 0, 200000);
xhr.send();
};
};
var createAppendAudioOffsetTest = function(stream1, stream2) {
var test = createConformanceTest('Append' + stream1.codec + 'AudioOffset',
'MSE (' + stream1.codec + ')');
test.prototype.title =
'Test if we can append audio data with an explicit offset.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
var unused_sb = this.ms.addSourceBuffer(Media.VP9.mimetype);
var sb = this.ms.addSourceBuffer(stream1.mimetype);
var xhr = runner.XHRManager.createRequest(stream1.src, function(e) {
sb.timestampOffset = 5;
sb.appendBuffer(this.getResponseData());
sb.addEventListener('updateend', function callXhr2() {
sb.removeEventListener('updateend', callXhr2);
xhr2.send();
});
}, 0, 200000);
var xhr2 = runner.XHRManager.createRequest(stream2.src, function(e) {
sb.abort();
sb.timestampOffset = 0;
sb.appendBuffer(this.getResponseData());
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(
sb.buffered.end(0), stream2.get('appendAudioOffset'), 'Range end');
runner.succeed();
});
}, 0, 200000);
xhr.send();
};
};
var createAppendVideoOffsetTest = function(stream1, stream2, audioStream) {
var test = createConformanceTest('Append' + stream1.codec + 'VideoOffset',
'MSE (' + stream1.codec + ')');
test.prototype.title =
'Test if we can append video data with an explicit offset.';
test.prototype.onsourceopen = function() {
var self = this;
var runner = this.runner;
var video = this.video;
var sb = this.ms.addSourceBuffer(stream1.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var xhr = runner.XHRManager.createRequest(stream1.src, function(e) {
sb.timestampOffset = 5;
sb.appendBuffer(this.getResponseData());
sb.addEventListener('update', function callXhr2() {
sb.removeEventListener('update', callXhr2);
xhr2.send();
});
}, 0, 200000);
var xhr2 = runner.XHRManager.createRequest(stream2.src, function(e) {
sb.abort();
sb.timestampOffset = 0;
sb.appendBuffer(this.getResponseData());
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(sb.buffered.end(0),
stream2.get('videoChangeRate'), 'Range end');
callAfterLoadedMetaData(video, function() {
video.addEventListener('seeked', function(e) {
self.log('seeked called');
video.addEventListener('timeupdate', function(e) {
self.log('timeupdate called with ' + video.currentTime);
if (!video.paused && video.currentTime >= 6) {
runner.succeed();
}
});
});
video.currentTime = 6;
});
});
video.play();
}, 0, 400000);
this.ms.duration = 100000000; // Ensure that we can seek to any position.
var audioXhr = runner.XHRManager.createRequest(audioStream.src,
function(e) {
var audioContent = audioXhr.getResponseData();
audioSb.appendBuffer(audioContent);
xhr.send();
});
audioXhr.send();
};
};
var createAppendMultipleInitTest = function(stream, unused_stream) {
var test = createConformanceTest(
'AppendMultipleInit' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if we can append multiple init segments.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new FileSource(stream.src, runner.XHRManager, runner.timeouts,
0, stream.size, stream.size);
var src = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var init;
function getEventAppend(cb, endCb) {
var chainCount = 0;
return function() {
if (chainCount < 10) {
++chainCount;
cb();
} else {
endCb();
}
};
}
chain.init(0, function(buf) {
init = buf;
chain.pull(function(buf) {
var firstAppend = getEventAppend(function() {
src.appendBuffer(init);
}, function() {
src.removeEventListener('update', firstAppend);
src.addEventListener('update', function abortAppend() {
src.removeEventListener('update', abortAppend);
src.abort();
var end = src.buffered.end(0);
var secondAppend = getEventAppend(function() {
src.appendBuffer(init);
}, function() {
runner.checkEq(src.buffered.end(0), end, 'Range end');
runner.succeed();
});
src.addEventListener('update', secondAppend);
secondAppend();
});
src.appendBuffer(buf);
});
src.addEventListener('update', firstAppend);
firstAppend();
});
});
};
};
var createAppendOutOfOrderTest = function(stream, unused_stream) {
var test = createConformanceTest(
'Append' + stream.codec + util.MakeCapitalName(stream.mediatype) + 'OutOfOrder',
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test appending segments out of order.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new FileSource(stream.src, runner.XHRManager, runner.timeouts);
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var bufs = [];
var i = 0;
// Append order of the segments.
var appendOrder = [0, 2, 1, 4, 3];
// Number of segments given the append order, since segments get merged.
var bufferedLength = [0, 1, 1, 2, 1];
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, bufferedLength[i],
'Source buffer number');
if (i == 1) {
runner.checkGr(sb.buffered.start(0), 0, 'Range start');
} else if (i > 0) {
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
}
i++;
if (i >= bufs.length) {
runner.succeed();
} else {
sb.appendBuffer(bufs[appendOrder[i]]);
}
});
chain.init(0, function(buf) {
bufs.push(buf);
chain.pull(function(buf) {
bufs.push(buf);
chain.pull(function(buf) {
bufs.push(buf);
chain.pull(function(buf) {
bufs.push(buf);
chain.pull(function(buf) {
bufs.push(buf);
sb.appendBuffer(bufs[0]);
});
});
});
});
});
};
};
var createBufferedRangeTest = function(stream, unused_stream) {
var test = createConformanceTest(
'BufferedRange' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test SourceBuffer.buffered get updated correctly after feeding data.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new ResetInit(
new FileSource(stream.src, runner.XHRManager, runner.timeouts));
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
runner.checkEq(sb.buffered.length, 0, 'Source buffer number');
appendInit(media, sb, chain, 0, function() {
runner.checkEq(sb.buffered.length, 0, 'Source buffer number');
appendUntil(runner.timeouts, media, sb, chain, 5, function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Source buffer number');
runner.checkGE(sb.buffered.end(0), 5, 'Range end');
runner.succeed();
});
});
};
};
var createMediaSourceDurationTest = function(videoStream, audioStream) {
var test = createConformanceTest('MediaSourceDuration' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title = 'Test if the duration on MediaSource can be set and ' +
'retrieved sucessfully.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var videoChain = new ResetInit(
new FileSource(videoStream.src, runner.XHRManager, runner.timeouts));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
var onsourceclose = function() {
self.log('onsourceclose called');
runner.assert(isNaN(ms.duration));
runner.succeed();
};
var appendVideo = function() {
runner.assert(isNaN(media.duration), 'Initial media duration not NaN');
media.play();
appendInit(media, videoSb, videoChain, 0, function() {
appendUntil(runner.timeouts, media, videoSb, videoChain, 10,
function() {
setDuration(5, ms, [videoSb, audioSb], function() {
runner.checkEq(ms.duration, 5, 'ms.duration');
runner.checkEq(media.duration, 5, 'media.duration');
runner.checkLE(videoSb.buffered.end(0), 5.1, 'Range end');
videoSb.abort();
videoChain.seek(0);
appendInit(media, videoSb, videoChain, 0, function() {
appendUntil(runner.timeouts, media, videoSb, videoChain, 10,
function() {
runner.checkApproxEq(ms.duration, 10, 'ms.duration');
setDuration(5, ms, [videoSb, audioSb], function() {
if (videoSb.updating) {
runner.fail('Source buffer is updating on duration change');
return;
}
var duration = videoSb.buffered.end(0);
ms.endOfStream();
runner.checkApproxEq(ms.duration, duration, 'ms.duration',
0.01);
ms.addEventListener('sourceended', function() {
runner.checkApproxEq(ms.duration, duration, 'ms.duration',
0.01);
runner.checkEq(media.duration, duration, 'media.duration');
ms.addEventListener('sourceclose', onsourceclose);
media.removeAttribute('src');
media.load();
});
media.play();
});
});
});
});
});
});
};
var audioXhr = runner.XHRManager.createRequest(audioStream.src,
function(e) {
audioSb.addEventListener('updateend', function onAudioUpdate() {
audioSb.removeEventListener('updateend', onAudioUpdate);
appendVideo();
});
var audioContent = audioXhr.getResponseData();
audioSb.appendBuffer(audioContent);
});
audioXhr.send();
};
};
var createOverlapTest = function(stream, unused_stream) {
var test = createConformanceTest(
stream.codec + util.MakeCapitalName(stream.mediatype) + 'WithOverlap',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if media data with overlap will be merged into one range.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new ResetInit(
new FileSource(stream.src, runner.XHRManager, runner.timeouts));
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var GAP = 0.1;
appendInit(media, sb, chain, 0, function() {
chain.pull(function(buf) {
sb.addEventListener('update', function appendOuter() {
sb.removeEventListener('update', appendOuter);
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
var segmentDuration = sb.buffered.end(0);
sb.timestampOffset = segmentDuration - GAP;
chain.seek(0);
chain.pull(function(buf) {
sb.addEventListener('update', function appendMiddle() {
sb.removeEventListener('update', appendMiddle);
chain.pull(function(buf) {
sb.addEventListener('update', function appendInner() {
runner.checkEq(
sb.buffered.length, 1, 'Source buffer number');
runner.checkApproxEq(sb.buffered.end(0),
segmentDuration * 2 - GAP, 'Range end');
runner.succeed();
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
};
};
var createSmallGapTest = function(stream, unused_stream) {
var test = createConformanceTest(
stream.codec + util.MakeCapitalName(stream.mediatype) + 'WithSmallGap',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if media data with a gap smaller than an media frame size ' +
'will be merged into one buffered range.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new ResetInit(
new FileSource(stream.src, runner.XHRManager, runner.timeouts));
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var GAP = 0.01;
appendInit(media, sb, chain, 0, function() {
chain.pull(function(buf) {
sb.addEventListener('update', function appendOuter() {
sb.removeEventListener('update', appendOuter);
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
var segmentDuration = sb.buffered.end(0);
sb.timestampOffset = segmentDuration + GAP;
chain.seek(0);
chain.pull(function(buf) {
sb.addEventListener('update', function appendMiddle() {
sb.removeEventListener('update', appendMiddle);
chain.pull(function(buf) {
sb.addEventListener('update', function appendInner() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkApproxEq(sb.buffered.end(0),
segmentDuration * 2 + GAP, 'Range end');
runner.succeed();
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
};
};
var createLargeGapTest = function(stream, unused_stream) {
var test = createConformanceTest(
stream.codec + util.MakeCapitalName(stream.mediatype) + 'WithLargeGap',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if media data with a gap larger than an media frame size ' +
'will not be merged into one buffered range.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new ResetInit(
new FileSource(stream.src, runner.XHRManager, runner.timeouts));
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var GAP = 0.3;
appendInit(media, sb, chain, 0, function() {
chain.pull(function(buf) {
sb.addEventListener('update', function appendOuter() {
sb.removeEventListener('update', appendOuter);
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
var segmentDuration = sb.buffered.end(0);
sb.timestampOffset = segmentDuration + GAP;
chain.seek(0);
chain.pull(function(buf) {
sb.addEventListener('update', function appendMiddle() {
sb.removeEventListener('update', appendMiddle);
chain.pull(function(buf) {
sb.addEventListener('update', function appendInner() {
runner.checkEq(sb.buffered.length, 2, 'Source buffer number');
runner.succeed();
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
};
};
var createSeekTest = function(videoStream) {
var test = createConformanceTest('Seek' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title = 'Test if we can seek during playing. It' +
' also tests if the implementation properly supports seek operation' +
' fired immediately after another seek that hasn\'t been completed.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var audioStream = Media.AAC.AudioNormal;
var videoChain = new ResetInit(new FileSource(
videoStream.src, runner.XHRManager, runner.timeouts));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioChain = new ResetInit(new FileSource(
audioStream.src, runner.XHRManager, runner.timeouts));
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
this.ms.duration = 100000000; // Ensure that we can seek to any position.
appendUntil(runner.timeouts, media, videoSb, videoChain, 20, function() {
appendUntil(runner.timeouts, media, audioSb, audioChain, 20, function() {
self.log('Seek to 17s');
callAfterLoadedMetaData(media, function() {
media.currentTime = 17;
media.play();
playThrough(
runner.timeouts, media, 10, 19,
videoSb, videoChain, audioSb, audioChain, function() {
runner.checkGE(media.currentTime, 19, 'currentTime');
self.log('Seek to 28s');
media.currentTime = 53;
media.currentTime = 58;
playThrough(
runner.timeouts, media, 10, 60,
videoSb, videoChain, audioSb, audioChain, function() {
runner.checkGE(media.currentTime, 60, 'currentTime');
self.log('Seek to 7s');
media.currentTime = 0;
media.currentTime = 7;
videoChain.seek(7, videoSb);
audioChain.seek(7, audioSb);
playThrough(runner.timeouts, media, 10, 9,
videoSb, videoChain, audioSb, audioChain, function() {
runner.checkGE(media.currentTime, 9, 'currentTime');
runner.succeed();
});
});
});
});
});
});
};
};
var createBufUnbufSeekTest = function(videoStream) {
var test = createConformanceTest('BufUnbufSeek' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title = 'Seek into and out of a buffered region.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var audioStream = Media.AAC.AudioNormal;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var xhr = runner.XHRManager.createRequest(videoStream.src, function() {
videoSb.appendBuffer(xhr.getResponseData());
var xhr2 = runner.XHRManager.createRequest(audioStream.src, function() {
audioSb.appendBuffer(xhr2.getResponseData());
callAfterLoadedMetaData(media, function() {
var N = 30;
function loop(i) {
if (i > N) {
media.currentTime = 1.005;
media.addEventListener('timeupdate', function(e) {
if (!media.paused && media.currentTime > 3)
runner.succeed();
});
return;
}
media.currentTime = (i++ % 2) * 1.0e6 + 1;
runner.timeouts.setTimeout(loop.bind(null, i), 50);
}
media.play();
media.addEventListener('play', loop.bind(null, 0));
});
}, 0, 100000);
xhr2.send();
}, 0, 1000000);
this.ms.duration = 100000000; // Ensure that we can seek to any position.
xhr.send();
};
};
var createDelayedTest = function(delayed, nonDelayed) {
var test = createConformanceTest(
'Delayed' + delayed.codec + util.MakeCapitalName(delayed.mediatype),
'MSE (' + delayed.codec + ')');
test.prototype.title = 'Test if we can play properly when there' +
' is not enough ' + delayed.mediatype + ' data. The play should resume once ' +
delayed.mediatype + ' data is appended.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
// Chrome allows for 3 seconds of underflow for streams that have audio
// but are video starved. See code.google.com/p/chromium/issues/detail?id=423801
var underflowTime = 0.0;
if (delayed.mediatype == 'video') {
underflowTime = 3.0;
}
var chain = new FixedAppendSize(
new ResetInit(
new FileSource(nonDelayed.src, runner.XHRManager, runner.timeouts)
), 16384);
var src = this.ms.addSourceBuffer(nonDelayed.mimetype);
var delayedChain = new FixedAppendSize(
new ResetInit(
new FileSource(delayed.src, runner.XHRManager, runner.timeouts)
), 16384);
var delayedSrc = this.ms.addSourceBuffer(delayed.mimetype);
var self = this;
var ontimeupdate = function(e) {
if (!media.paused) {
var end = delayedSrc.buffered.end(0);
runner.checkLE(media.currentTime, end + 1.0 + underflowTime,
'media.currentTime (' + media.readyState + ')');
}
};
appendUntil(runner.timeouts, media, src, chain, 15, function() {
appendUntil(runner.timeouts, media, delayedSrc, delayedChain, 8,
function() {
var end = delayedSrc.buffered.end(0);
self.log('Start play when there is only ' + end + ' seconds of ' +
test.prototype.desc + ' data.');
media.play();
media.addEventListener('timeupdate', ontimeupdate);
waitUntil(runner.timeouts, media, end + 3, function() {
runner.checkLE(media.currentTime, end + 1.0 + underflowTime, 'media.currentTime');
runner.checkGr(media.currentTime, end - 1.0 - underflowTime, 'media.currentTime');
runner.succeed();
});
});
});
};
};
// Opus Specific tests.
createAppendTest(Media.Opus.SantaHigh, Media.VP9.Video1MB);
createAbortTest(Media.Opus.SantaHigh, Media.VP9.Video1MB);
createTimestampOffsetTest(Media.Opus.CarLow, Media.VP9.Video1MB);
createDurationAfterAppendTest(Media.Opus.CarLow, Media.VP9.Video1MB);
createPausedTest(Media.Opus.CarLow);
createIncrementalAudioTest(Media.Opus.CarMed);
createAppendAudioOffsetTest(Media.Opus.CarMed, Media.Opus.CarHigh);
createAppendMultipleInitTest(Media.Opus.CarLow, Media.VP9.Video1MB);
createAppendOutOfOrderTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createBufferedRangeTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createOverlapTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createSmallGapTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createLargeGapTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createDelayedTest(Media.Opus.CarMed, Media.VP9.VideoNormal);
// AAC Specific tests.
createAppendTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createAbortTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createTimestampOffsetTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createDurationAfterAppendTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createPausedTest(Media.AAC.Audio1MB);
createIncrementalAudioTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createAppendAudioOffsetTest(Media.AAC.AudioNormal, Media.AAC.AudioHuge);
createAppendMultipleInitTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createAppendOutOfOrderTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createBufferedRangeTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createOverlapTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createSmallGapTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createLargeGapTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createDelayedTest(Media.AAC.AudioNormal, Media.VP9.VideoNormal);
// VP9 Specific tests.
createAppendTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createAbortTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createTimestampOffsetTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createDASHLatencyTest(Media.VP9.VideoTiny, Media.AAC.Audio1MB);
createDurationAfterAppendTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createPausedTest(Media.VP9.Video1MB);
createVideoDimensionTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createPlaybackStateTest(Media.VP9.VideoNormal);
createPlayPartialSegmentTest(Media.VP9.VideoTiny);
createAppendVideoOffsetTest(Media.VP9.VideoNormal, Media.VP9.VideoTiny,
Media.AAC.AudioNormal);
createAppendMultipleInitTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createAppendOutOfOrderTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createBufferedRangeTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createMediaSourceDurationTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createOverlapTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createSmallGapTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createLargeGapTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createSeekTest(Media.VP9.VideoNormal);
createBufUnbufSeekTest(Media.VP9.VideoNormal);
createDelayedTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
// H264 Specific tests.
createAppendTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createAbortTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createTimestampOffsetTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createDASHLatencyTest(Media.H264.VideoTiny, Media.AAC.Audio1MB);
createDurationAfterAppendTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createPausedTest(Media.H264.Video1MB);
createVideoDimensionTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createPlaybackStateTest(Media.H264.VideoNormal);
createPlayPartialSegmentTest(Media.H264.VideoTiny);
createAppendVideoOffsetTest(Media.H264.VideoNormal, Media.H264.VideoTiny,
Media.AAC.Audio1MB);
createAppendMultipleInitTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createAppendOutOfOrderTest(Media.H264.CarMedium, Media.AAC.Audio1MB);
createBufferedRangeTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createMediaSourceDurationTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createOverlapTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createSmallGapTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createLargeGapTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createSeekTest(Media.H264.VideoNormal);
createBufUnbufSeekTest(Media.H264.VideoNormal);
createDelayedTest(Media.H264.VideoNormal, Media.AAC.AudioNormal);
var testWAAContext = createConformanceTest('WAAPresence', 'MSE Web Audio API');
testWAAContext.prototype.title = 'Test if AudioContext is supported';
testWAAContext.prototype.start = function(runner, video) {
var Ctor = window.AudioContext || window.webkitAudioContext;
if (!Ctor)
return runner.fail('No AudioContext object available.');
var ctx = new Ctor();
if (!ctx)
return runner.fail('Found AudioContext but could not create one');
runner.succeed();
};
var createCreateMESTest = function(audioStream, videoStream) {
var test = createConformanceTest(
audioStream.codec + '/' + videoStream.codec + 'CreateMediaElementSource',
'MSE Web Audio API (Optional)',
false);
test.prototype.title =
'Test if AudioContext#createMediaElementSource supports mimetype ' +
audioStream.mimetype + '/' + videoStream.mimetype;
test.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
try {
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
} catch (e) {
runner.fail(e.message);
return;
}
var Ctor = window.AudioContext || window.webkitAudioContext;
var ctx = new Ctor();
var audioXhr =
runner.XHRManager.createRequest(audioStream.src, function(e) {
var data = audioXhr.getResponseData();
function updateEnd(e) {
runner.checkEq(audioSb.buffered.length, 1, 'Source buffer number');
runner.checkEq(audioSb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(
audioSb.buffered.end(0), audioStream.duration, 'Range end');
audioSb.removeEventListener('updateend', updateEnd);
video.play();
}
audioSb.addEventListener('updateend', updateEnd);
audioSb.appendBuffer(data);
});
var videoXhr =
runner.XHRManager.createRequest(videoStream.src, function(e) {
var data = videoXhr.getResponseData();
videoSb.appendBuffer(data);
audioXhr.send();
});
videoXhr.send();
video.addEventListener('timeupdate', function onTimeUpdate() {
if (!video.paused && video.currentTime >= 5) {
video.removeEventListener('timeupdate', onTimeUpdate);
try {
runner.log('Creating MES');
var source = ctx.createMediaElementSource(video);
} catch (e) {
runner.fail(e);
return;
} finally {
ctx.close();
}
runner.checkNE(source, null, 'MediaElementSource');
runner.succeed();
}
});
}
}
createCreateMESTest(Media.Opus.CarLow, Media.VP9.VideoNormal);
createCreateMESTest(Media.AAC.Audio1MB, Media.VP9.VideoNormal);
createCreateMESTest(Media.AAC.Audio1MB, Media.H264.VideoNormal);
var frameTestOnSourceOpen = function() {
var runner = this.runner;
var media = this.video;
var audioStream = Media.AAC.AudioNormal;
var videoChain = new FixedAppendSize(new ResetInit(
new FileSource(this.filename, runner.XHRManager, runner.timeouts)));
var videoSb = this.ms.addSourceBuffer(Media.H264.mimetype);
var audioChain = new FixedAppendSize(new ResetInit(
new FileSource(audioStream.src, runner.XHRManager, runner.timeouts)));
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
media.play();
playThrough(runner.timeouts, media, 5, 18, videoSb, videoChain,
audioSb, audioChain, runner.succeed.bind(runner));
};
var testFrameGaps = createConformanceTest('H264FrameGaps', 'Media');
testFrameGaps.prototype.title = 'Test media with frame durations of 24FPS ' +
'but segment timing corresponding to 23.976FPS';
testFrameGaps.prototype.filename = Media.H264.FrameGap.src;
testFrameGaps.prototype.onsourceopen = frameTestOnSourceOpen;
var testFrameOverlaps = createConformanceTest('H264FrameOverlaps', 'Media');
testFrameOverlaps.prototype.title = 'Test media with frame durations of ' +
'23.976FPS but segment timing corresponding to 24FPS';
testFrameOverlaps.prototype.filename = Media.H264.FrameOverlap.src;
testFrameOverlaps.prototype.onsourceopen = frameTestOnSourceOpen;
var createAudio51Test = function(audioStream) {
var test = createConformanceTest(audioStream.codec + '5.1', 'Media');
test.prototype.title = 'Test 5.1-channel ' + audioStream.codec;
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var videoStream = Media.VP9.VideoNormal;
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var xhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.appendBuffer(xhr.getResponseData());
var xhr2 = runner.XHRManager.createRequest(videoStream.src, function(e) {
videoSb.appendBuffer(xhr2.getResponseData());
media.play();
media.addEventListener('timeupdate', function(e) {
if (!media.paused && media.currentTime > 2) {
runner.succeed();
}
});
}, 0, 3000000);
xhr2.send();
});
xhr.send();
}
}
createAudio51Test(Media.Opus.Audio51);
createAudio51Test(Media.AAC.Audio51);
var createHeAacTest = function(audioStream) {
var test = createConformanceTest('HE-AAC/' +
audioStream.get('sbrSignaling') + 'SBR', 'Media');
test.prototype.title = 'Test playback of HE-AAC with ' +
audioStream.get('sbrSignaling') + ' SBR signaling.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var videoStream = Media.VP9.Video1MB;
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var xhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.addEventListener('update', function() {
var xhr2 = runner.XHRManager.createRequest(videoStream.src,
function(e) {
videoSb.addEventListener('update', function() {
ms.endOfStream();
media.addEventListener('ended', function(e) {
if (media.currentTime > audioStream.duration + 1) {
runner.fail();
} else {
runner.checkApproxEq(media.currentTime, audioStream.duration,
'media.currentTime');
runner.succeed();
}
});
media.play();
});
videoSb.appendBuffer(xhr2.getResponseData());
}, 0, videoStream.size);
xhr2.send();
});
audioSb.appendBuffer(xhr.getResponseData());
}, 0, audioStream.size);
xhr.send();
}
}
createHeAacTest(Media.AAC.AudioLowExplicitHE);
createHeAacTest(Media.AAC.AudioLowImplicitHE);
return {tests: tests, info: info, fields: fields, viewType: 'default'};
};
| js/tests/tip/conformanceTest.js | /*
Copyright 2018 Google 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.
*/
'use strict';
/**
* MSE Conformance Test Suite.
* @class
*/
var ConformanceTest = function() {
var mseVersion = 'Current Editor\'s Draft';
var webkitPrefix = MediaSource.prototype.version.indexOf('webkit') >= 0;
var tests = [];
var info = 'No MSE Support!';
if (window.MediaSource) {
info = 'MSE Spec Version: ' + mseVersion;
info += ' | webkit prefix: ' + webkitPrefix.toString();
}
info += ' | Default Timeout: ' + TestBase.timeout + 'ms';
var fields = ['passes', 'failures', 'timeouts'];
var createConformanceTest = function(name, category, mandatory) {
var t = createMSTest(name);
t.prototype.index = tests.length;
t.prototype.passes = 0;
t.prototype.failures = 0;
t.prototype.timeouts = 0;
t.prototype.category = category || 'General';
if (typeof mandatory === 'boolean') {
t.prototype.mandatory = mandatory;
}
tests.push(t);
return t;
};
var createInitialMediaStateTest = function(state, value, check) {
var test = createConformanceTest('InitialMedia' +
util.MakeCapitalName(state), 'Media Element Core');
check = typeof(check) === 'undefined' ? 'checkEq' : check;
test.prototype.title = 'Test if the state ' + state +
' is correct when onsourceopen is called';
test.prototype.onsourceopen = function() {
this.runner[check](this.video[state], value, state);
this.runner.succeed();
};
};
createInitialMediaStateTest('duration', NaN);
createInitialMediaStateTest('videoWidth', 0);
createInitialMediaStateTest('videoHeight', 0);
createInitialMediaStateTest('readyState', HTMLMediaElement.HAVE_NOTHING);
createInitialMediaStateTest('src', '', 'checkNE');
createInitialMediaStateTest('currentSrc', '', 'checkNE');
var testXHRUint8Array = createConformanceTest('XHRUint8Array', 'XHR');
testXHRUint8Array.prototype.title = 'Ensure that XHR can send an Uint8Array';
testXHRUint8Array.prototype.timeout = 10000;
testXHRUint8Array.prototype.start = function(runner, video) {
var s = 'XHR DATA';
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i < s.length; i++) {
view[i] = s.charCodeAt(i);
}
var xhr = runner.XHRManager.createPostRequest(
'https://drmproxy.appspot.com/echo',
function(e) {
runner.checkEq(String.fromCharCode.apply(null, xhr.getResponseData()),
s, 'XHR response');
runner.succeed();
},
view.length);
xhr.send(view);
};
var testXHRAbort = createConformanceTest('XHRAbort', 'XHR');
testXHRAbort.prototype.title = 'Ensure that XHR aborts actually abort by ' +
'issuing an absurd number of them and then aborting all but one.';
testXHRAbort.prototype.start = function(runner, video) {
var N = 100;
var startTime = Date.now();
var lastAbortTime;
function startXHR(i) {
var xhr = runner.XHRManager.createRequest(
Media.VP9.VideoNormal.src + '?x=' + Date.now() + '.' + i, function() {
if (i >= N) {
xhr.getResponseData(); // This will verify status internally.
runner.succeed();
}
});
if (i < N) {
runner.timeouts.setTimeout(xhr.abort.bind(xhr), 10);
runner.timeouts.setTimeout(startXHR.bind(null, i + 1), 1);
lastAbortTime = Date.now();
}
xhr.send();
};
startXHR(0);
};
var testXHROpenState = createConformanceTest('XHROpenState', 'XHR');
testXHROpenState.prototype.title = 'Ensure XMLHttpRequest.open does not ' +
'reset XMLHttpRequest.responseType';
testXHROpenState.prototype.start = function(runner, video) {
var xhr = new XMLHttpRequest;
// It should not be an error to set responseType before calling open
xhr.responseType = 'arraybuffer';
xhr.open('GET', 'http://google.com', true);
runner.checkEq(xhr.responseType, 'arraybuffer', 'XHR responseType');
runner.succeed();
};
var testPresence = createConformanceTest('Presence', 'MSE Core');
testPresence.prototype.title = 'Test if MediaSource object is present.';
testPresence.prototype.start = function(runner, video) {
if (!window.MediaSource)
return runner.fail('No MediaSource object available.');
var ms = new MediaSource();
if (!ms)
return runner.fail('Found MediaSource but could not create one');
if (ms.version)
this.log('Media source version reported as ' + ms.version);
else
this.log('No media source version reported');
runner.succeed();
};
var testAttach = createConformanceTest('Attach', 'MSE Core');
testAttach.prototype.timeout = 2000;
testAttach.prototype.title =
'Test if MediaSource object can be attached to video.';
testAttach.prototype.start = function(runner, video) {
this.ms = new MediaSource();
this.ms.addEventListener('sourceopen', function() {
runner.succeed();
});
video.src = window.URL.createObjectURL(this.ms);
video.load();
};
var testAddSourceBuffer = createConformanceTest('AddSourceBuffer', 'MSE Core');
testAddSourceBuffer.prototype.title =
'Test if we can add source buffer';
testAddSourceBuffer.prototype.onsourceopen = function() {
try {
this.runner.checkEq(this.ms.sourceBuffers.length, 0, 'Source buffer number');
this.ms.addSourceBuffer(Media.AAC.mimetype);
this.runner.checkEq(this.ms.sourceBuffers.length, 1, 'Source buffer number');
this.ms.addSourceBuffer(Media.VP9.mimetype);
this.runner.checkEq(this.ms.sourceBuffers.length, 2, 'Source buffer number');
} catch (e) {
this.runner.fail(e);
}
this.runner.succeed();
};
var testAddSourceBufferException = createConformanceTest('AddSBException',
'MSE Core');
testAddSourceBufferException.prototype.title = 'Test if add incorrect source ' +
'buffer type will fire the correct exceptions.';
testAddSourceBufferException.prototype.onsourceopen = function() {
var runner = this.runner;
var self = this;
runner.checkException(function() {
self.ms.addSourceBuffer('^^^');
}, DOMException.NOT_SUPPORTED_ERR);
runner.checkException(function() {
var ms = new MediaSource;
ms.addSourceBuffer(Media.AAC.mimetype);
}, DOMException.INVALID_STATE_ERR);
runner.succeed();
};
var testSourceRemove = createConformanceTest('RemoveSourceBuffer', 'MSE Core');
testSourceRemove.prototype.title = 'Test if we can add/remove source buffers';
testSourceRemove.prototype.onsourceopen = function() {
var sb = this.ms.addSourceBuffer(Media.AAC.mimetype);
this.ms.removeSourceBuffer(sb);
this.runner.checkEq(this.ms.sourceBuffers.length, 0, 'Source buffer number');
this.ms.addSourceBuffer(Media.AAC.mimetype);
this.runner.checkEq(this.ms.sourceBuffers.length, 1, 'Source buffer number');
for (var i = 0; i < 10; ++i) {
try {
sb = this.ms.addSourceBuffer(Media.VP9.mimetype);
this.runner.checkEq(this.ms.sourceBuffers.length, 2,
'Source buffer number');
this.ms.removeSourceBuffer(sb);
this.runner.checkEq(this.ms.sourceBuffers.length, 1,
'Source buffer number');
} catch (e) {
return this.runner.fail(e);
}
}
this.runner.succeed();
};
var createInitialMSStateTest = function(state, value, check) {
var test = createConformanceTest('InitialMS' + util.MakeCapitalName(state),
'MSE Core');
check = typeof(check) === 'undefined' ? 'checkEq' : check;
test.prototype.title = 'Test if the state ' + state +
' is correct when onsourceopen is called';
test.prototype.onsourceopen = function() {
this.runner[check](this.ms[state], value, state);
this.runner.succeed();
};
};
createInitialMSStateTest('duration', NaN);
createInitialMSStateTest('readyState', 'open');
var testDuration = createConformanceTest('Duration', 'MSE Core');
testDuration.prototype.title =
'Test if we can set duration.';
testDuration.prototype.onsourceopen = function() {
this.ms.duration = 10;
this.runner.checkEq(this.ms.duration, 10, 'ms.duration');
this.runner.succeed();
};
var mediaElementEvents = createConformanceTest('MediaElementEvents', 'MSE Core');
mediaElementEvents.prototype.title = 'Test events on the MediaElement.';
mediaElementEvents.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var audioStream = Media.AAC.Audio1MB;
var videoStream = Media.VP9.Video1MB;
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var self = this;
var videoXhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
self.log('onload called');
var onUpdate = function() {
videoSb.removeEventListener('update', onUpdate);
setDuration(1.0, ms, [videoSb, audioSb], function() {
if (audioSb.updating || videoSb.updating) {
runner.fail('Source buffers are updating on duration change.');
return;
}
ms.endOfStream();
media.play();
});
}
videoSb.addEventListener('update', onUpdate);
videoSb.appendBuffer(videoXhr.getResponseData());
});
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
self.log('onload called');
var onAudioUpdate = function() {
audioSb.removeEventListener('update', onAudioUpdate);
videoXhr.send();
}
audioSb.addEventListener('update', onAudioUpdate);
audioSb.appendBuffer(audioXhr.getResponseData());
});
media.addEventListener('ended', function() {
self.log('onended called');
runner.succeed();
});
audioXhr.send();
};
var mediaSourceEvents = createConformanceTest('MediaSourceEvents', 'MSE Core');
mediaSourceEvents.prototype.title = 'Test if the events on MediaSource are correct.';
mediaSourceEvents.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var audioStream = Media.AAC.Audio1MB;
var videoStream = Media.VP9.Video1MB;
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var lastState = 'open';
var self = this;
var videoXhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
self.log('onload called');
videoSb.appendBuffer(videoXhr.getResponseData());
videoSb.abort();
ms.endOfStream();
});
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
self.log('onload called');
audioSb.appendBuffer(audioXhr.getResponseData());
audioSb.abort();
videoXhr.send();
});
ms.addEventListener('sourceclose', function() {
self.log('onsourceclose called');
runner.checkEq(lastState, 'ended', 'The previous state');
runner.succeed();
});
ms.addEventListener('sourceended', function() {
self.log('onsourceended called');
runner.checkEq(lastState, 'open', 'The previous state');
lastState = 'ended';
media.removeAttribute('src');
media.load();
});
audioXhr.send();
};
var testBufferSize = createConformanceTest('VideoBufferSize', 'MSE Core');
testBufferSize.prototype.title = 'Determines video buffer sizes by ' +
'appending incrementally until discard occurs, and tests that it meets ' +
'the minimum requirements for streaming.';
testBufferSize.prototype.onsourceopen = function() {
var runner = this.runner;
// The test clip has a bitrate which is nearly exactly 1MB/sec, and
// lasts 1s. We start appending it repeatedly until we get eviction.
var videoStream = Media.VP9.Video1MB;
var sb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioStream = Media.AAC.Audio1MB;
var unused_audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
var MIN_SIZE = 12 * 1024 * 1024;
var ESTIMATED_MIN_TIME = 12;
var xhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
var onBufferFull = function() {
runner.checkGE(expectedTime - sb.buffered.start(0), ESTIMATED_MIN_TIME,
'Estimated source buffer size');
runner.succeed();
};
var expectedTime = 0;
var expectedSize = 0;
var appendCount = 0;
sb.addEventListener('updateend', function onUpdate() {
appendCount++;
self.log('Append count ' + appendCount);
if (sb.buffered.start(0) > 0 || expectedTime > sb.buffered.end(0)) {
sb.removeEventListener('updateend', onUpdate);
onBufferFull();
} else {
expectedTime += videoStream.duration;
expectedSize += videoStream.size;
// Pass the test if the UA can handle 10x more than expected.
if (expectedSize > (10 * MIN_SIZE)) {
sb.removeEventListener('updateend', onUpdate);
onBufferFull();
return;
}
sb.timestampOffset = expectedTime;
try {
sb.appendBuffer(xhr.getResponseData());
} catch (e) {
var QUOTA_EXCEEDED_ERROR_CODE = 22;
if (e.code == QUOTA_EXCEEDED_ERROR_CODE) {
sb.removeEventListener('updateend', onUpdate);
onBufferFull();
} else {
runner.fail(e);
}
}
}
});
sb.appendBuffer(xhr.getResponseData());
});
xhr.send();
};
var testStartPlayWithoutData = createConformanceTest('StartPlayWithoutData',
'MSE Core');
testStartPlayWithoutData.prototype.title =
'Test if we can start play before feeding any data. The play should ' +
'start automatically after data is appended';
testStartPlayWithoutData.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var audioStream = Media.AAC.AudioHuge;
var videoStream = Media.VP9.VideoHuge;
var videoChain = new ResetInit(
new FileSource(videoStream.src, runner.XHRManager, runner.timeouts));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioChain = new ResetInit(
new FileSource(audioStream.src, runner.XHRManager, runner.timeouts));
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
media.play();
appendUntil(runner.timeouts, media, videoSb, videoChain, 1, function() {
appendUntil(runner.timeouts, media, audioSb, audioChain, 1, function() {
playThrough(
runner.timeouts, media, 1, 2,
videoSb, videoChain, audioSb, audioChain, function() {
runner.checkGE(media.currentTime, 2, 'currentTime');
runner.succeed();
});
});
});
};
var testEventTimestamp = createConformanceTest('EventTimestamp', 'MSE Core');
testEventTimestamp.prototype.title = 'Test Event Timestamp is relative to ' +
'the initial page load';
testEventTimestamp.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
var videoStream = Media.VP9.VideoTiny;
var audioStream = Media.AAC.AudioTiny;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
runner.checkGr(Date.now(), 1360000000000, 'Date.now()');
var lastTime = 0.0;
var requestCounter = 0;
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.appendBuffer(this.getResponseData());
video.addEventListener('timeupdate', function(e) {
runner.checkGE(e.timeStamp, lastTime, 'event.timeStamp');
lastTime = e.timeStamp;
if (!video.paused && video.currentTime >= 2 && requestCounter >= 3) {
runner.succeed();
}
requestCounter++;
});
video.play();
}, 0, 500000);
var videoXhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
videoSb.appendBuffer(this.getResponseData());
audioXhr.send();
}, 0, 1500000);
videoXhr.send();
};
var testSeekTimeUpdate = createConformanceTest('SeekTimeUpdate', 'MSE Core');
testSeekTimeUpdate.prototype.title =
'Timeupdate event fired with correct currentTime after seeking.';
testSeekTimeUpdate.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var videoStream = Media.VP9.VideoNormal;
var audioStream = Media.AAC.AudioNormal;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var lastTime = 0;
var updateCount = 0;
var xhr = runner.XHRManager.createRequest(videoStream.src, function() {
videoSb.appendBuffer(xhr.getResponseData());
var xhr2 = runner.XHRManager.createRequest(audioStream.src, function() {
audioSb.appendBuffer(xhr2.getResponseData());
callAfterLoadedMetaData(media, function() {
media.addEventListener('timeupdate', function(e) {
if (!media.paused) {
++updateCount;
runner.checkGE(media.currentTime, lastTime, 'media.currentTime');
if (updateCount > 3) {
updateCount = 0;
lastTime += 10;
if (lastTime >= 35)
runner.succeed();
else
media.currentTime = lastTime + 6;
}
}
});
media.play();
});
}, 0, 1000000);
xhr2.send();
}, 0, 5000000);
this.ms.duration = 100000000; // Ensure that we can seek to any position.
xhr.send();
};
/**
* Creates a MSE currentTime Accuracy test to validate if the media.currentTime
* is accurate to within 250 milliseconds during active playback. This can
* be used for video features a standard frame rate or a high frame rate.
*/
var createCurrentTimeAccuracyTest =
function(videoStream, audioStream, frameRate) {
var test = createConformanceTest(
frameRate + 'Accuracy', 'MSE currentTime');
test.prototype.title = 'Test the currentTime granularity.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
var maxTimeDiff = 0;
var baseTimeDiff = 0;
var times = 0;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoXhr = runner.XHRManager.createRequest(
videoStream.src, function(e) {
videoSb.appendBuffer(this.getResponseData());
video.addEventListener('timeupdate', function(e) {
if (times === 0) {
baseTimeDiff = util.ElapsedTimeInS() - video.currentTime;
} else {
var timeDiff = util.ElapsedTimeInS() - video.currentTime;
maxTimeDiff = Math.max(
Math.abs(timeDiff - baseTimeDiff), maxTimeDiff);
}
if (times > 500 || video.currentTime > 10) {
runner.checkLE(
maxTimeDiff, 0.25, 'media.currentTime diff during playback');
runner.succeed();
}
++times;
});
video.play();
}, 0, 2500000);
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.appendBuffer(this.getResponseData());
videoXhr.send();
}, 0, 2500000);
audioXhr.send();
};
};
createCurrentTimeAccuracyTest(
Media.VP9.Webgl720p30fps, Media.AAC.AudioNormal, 'SFR');
createCurrentTimeAccuracyTest(
Media.VP9.Webgl720p60fps, Media.AAC.AudioNormal, 'HFR');
/**
* Creates a MSE currentTime PausedAccuracy test to validate if
* the media.currentTime is accurate to within 32 milliseconds when content
* is paused. This can be used for video features a standard frame rate
* or a high frame rate. Test checks the accuracy of media.currentTime at
* two events: when content is paused and when content is played again after
* the pause, if either one meets the threshold, test passes.
*/
var createCurrentTimePausedAccuracyTest =
function(videoStream, audioStream, frameRate) {
var test = createConformanceTest(
frameRate + 'PausedAccuracy', 'MSE currentTime');
test.prototype.title = 'Test the currentTime granularity when pause.';
test.prototype.onsourceopen = function() {
var maxDiffInS = 0.032;
var runner = this.runner;
var video = this.video;
var baseTimeDiff = 0;
var times = 0;
var assertTimeAtPlay = false;
var currentTimeIsAccurate = false;
var self = this;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoXhr = runner.XHRManager.createRequest(
videoStream.src, function(e) {
videoSb.appendBuffer(this.getResponseData());
function onTimeUpdate(e) {
if (times === 0) {
baseTimeDiff = util.ElapsedTimeInS() - video.currentTime;
}
if (times > 500 || video.currentTime > 10) {
video.removeEventListener('timeupdate', onTimeUpdate);
video.pause();
}
++times;
};
video.addEventListener('play', function() {
if (assertTimeAtPlay) {
var timeDiff = util.ElapsedTimeInS() - video.currentTime;
var currentTimeDiff = Math.abs(baseTimeDiff - timeDiff);
self.log('media.currentTime is ' + currentTimeDiff + 's different' +
' from actual time when video is played after a pause.');
currentTimeIsAccurate =
currentTimeIsAccurate || (currentTimeDiff <= maxDiffInS);
runner.checkEq(
currentTimeIsAccurate,
true,
'media.currentTime diff is within ' + maxDiffInS + 's');
assertTimeAtPlay = false;
runner.succeed();
}
});
video.addEventListener('pause', function(e) {
var timeDiff = util.ElapsedTimeInS() - video.currentTime;
var currentTimeDiff = Math.abs(baseTimeDiff - timeDiff);
runner.checkEq(video.paused, true, 'media.paused');
self.log('meida.currentTime is ' + currentTimeDiff +
's different from actual time when video is paused.');
currentTimeIsAccurate = currentTimeDiff <= maxDiffInS;
assertTimeAtPlay = true;
video.play();
});
video.addEventListener('timeupdate', onTimeUpdate);
video.play();
}, 0, 2500000);
var audioXhr = runner.XHRManager.createRequest(
audioStream.src, function(e) {
audioSb.appendBuffer(this.getResponseData());
videoXhr.send();
}, 0, 2500000);
audioXhr.send();
};
};
createCurrentTimePausedAccuracyTest(
Media.VP9.Webgl720p30fps, Media.AAC.AudioNormal, 'SFR');
createCurrentTimePausedAccuracyTest(
Media.VP9.Webgl720p60fps, Media.AAC.AudioNormal, 'HFR');
var createSupportTest = function(mimetype, desc) {
var test = createConformanceTest(desc + 'Support', 'MSE Formats');
test.prototype.title =
'Test if we support ' + desc + ' with mimetype: ' + mimetype;
test.prototype.onsourceopen = function() {
try {
this.log('Trying format ' + mimetype);
var src = this.ms.addSourceBuffer(mimetype);
} catch (e) {
return this.runner.fail(e);
}
this.runner.succeed();
};
};
createSupportTest(Media.AAC.mimetype, 'AAC');
createSupportTest(Media.H264.mimetype, 'H264');
createSupportTest(Media.VP9.mimetype, 'VP9');
createSupportTest(Media.Opus.mimetype, 'Opus');
var createAppendTest = function(stream, unused_stream) {
var test = createConformanceTest(
'Append' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if we can append a whole ' +
stream.mediatype + ' file whose size is 1MB.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var xhr = runner.XHRManager.createRequest(stream.src, function(e) {
var data = xhr.getResponseData();
function updateEnd(e) {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(sb.buffered.end(0), stream.duration, 'Range end');
// Try appending twice in a row --
// this should throw an INVALID_STATE_ERR exception.
var caught = false;
try {
sb.removeEventListener('updateend', updateEnd);
sb.appendBuffer(data);
sb.appendBuffer(data);
}
catch (e) {
if (e.code === e.INVALID_STATE_ERR) {
runner.succeed();
} else {
runner.fail('Invalid error on double append: ' + e);
}
caught = true;
}
if (!caught) {
// We may have updated so fast that we didn't encounter the error.
if (sb.updating) {
// Not a great check due to race conditions, but will have to do.
runner.fail('Implementation did not throw INVALID_STATE_ERR.');
} else {
runner.succeed();
}
}
}
sb.addEventListener('updateend', updateEnd);
sb.appendBuffer(data);
});
xhr.send();
};
};
var createAbortTest = function(stream, unused_stream) {
var test = createConformanceTest(
'Abort' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if we can abort the current segment.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var xhr = runner.XHRManager.createRequest(stream.src, function(e) {
var responseData = xhr.getResponseData();
var abortEnded = function(e) {
sb.removeEventListener('updateend', abortEnded);
sb.addEventListener('update', function(e) {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkGr(sb.buffered.end(0), 0, 'Range end');
runner.succeed();
});
sb.appendBuffer(responseData);
}
var appendStarted = function(e) {
sb.removeEventListener('update', appendStarted);
sb.addEventListener('updateend', abortEnded);
sb.abort();
}
sb.addEventListener('update', appendStarted);
sb.appendBuffer(responseData);
}, 0, stream.size);
xhr.send();
};
};
var createTimestampOffsetTest = function(stream, unused_stream) {
var test = createConformanceTest(
'TimestampOffset' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if we can set timestamp offset.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var xhr = runner.XHRManager.createRequest(stream.src, function(e) {
sb.timestampOffset = 5;
sb.appendBuffer(xhr.getResponseData());
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 5, 'Range start');
runner.checkApproxEq(sb.buffered.end(0), stream.duration + 5,
'Range end');
runner.succeed();
});
});
xhr.send();
};
};
var createDASHLatencyTest = function(videoStream, audioStream) {
var test = createConformanceTest('DASHLatency' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title = 'Test SourceBuffer DASH switch latency';
test.prototype.onsourceopen = function() {
var self = this;
var runner = this.runner;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var video = this.video;
var videoXhr = runner.XHRManager.createRequest(videoStream.src,
function(e) {
var videoContent = videoXhr.getResponseData();
var expectedTime = 0;
var loopCount = 0;
var MAX_ITER = 300;
var OVERFLOW_OFFSET = 1.0;
var onBufferFull = function() {
var bufferSize = loopCount * videoStream.size / 1048576;
self.log('Buffer size: ' + Math.round(bufferSize) + 'MB');
var DASH_MAX_LATENCY = 1;
var newContentStartTime = videoSb.buffered.start(0) + 2;
self.log('Source buffer updated as exceeding buffer limit');
video.addEventListener('timeupdate', function onTimeUpdate(e) {
if (video.currentTime > newContentStartTime + DASH_MAX_LATENCY) {
video.removeEventListener('timeupdate', onTimeUpdate);
runner.succeed();
}
});
video.play();
}
videoSb.addEventListener('update', function onUpdate() {
expectedTime += videoStream.duration;
videoSb.timestampOffset = expectedTime;
loopCount++;
if (loopCount > MAX_ITER) {
videoSb.removeEventListener('update', onUpdate);
runner.fail('Failed to fill up source buffer.');
return;
}
// Fill up the buffer such that it overflow implementations.
if (expectedTime > videoSb.buffered.end(0) + OVERFLOW_OFFSET) {
videoSb.removeEventListener('update', onUpdate);
onBufferFull();
}
try {
videoSb.appendBuffer(videoContent);
} catch (e) {
videoSb.removeEventListener('update', onUpdate);
var QUOTA_EXCEEDED_ERROR_CODE = 22;
if (e.code == QUOTA_EXCEEDED_ERROR_CODE) {
onBufferFull();
} else {
runner.fail(e);
}
}
});
videoSb.appendBuffer(videoContent);;
});
var audioXhr = runner.XHRManager.createRequest(audioStream.src,
function(e) {
var audioContent = audioXhr.getResponseData();
audioSb.appendBuffer(audioContent);
videoXhr.send();
});
audioXhr.send();
};
};
var createDurationAfterAppendTest = function(stream, unused_stream) {
var test = createConformanceTest(
'DurationAfterAppend' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if the duration expands after appending data.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var sb = ms.addSourceBuffer(stream.mimetype);
var unused_sb = ms.addSourceBuffer(unused_stream.mimetype);
var self = this;
var xhr = runner.XHRManager.createRequest(stream.src,
function(e) {
var data = xhr.getResponseData();
var updateCb = function() {
var halfDuration;
var durationChanged = false;
var sbUpdated = false;
sb.removeEventListener('updateend', updateCb);
sb.abort();
if (sb.updating) {
runner.fail();
return;
}
media.addEventListener('durationchange', function onDurationChange() {
media.removeEventListener('durationchange', onDurationChange);
self.log('Duration change complete.');
runner.checkApproxEq(ms.duration, halfDuration, 'ms.duration');
durationChanged = true;
if (durationChanged && sbUpdated) {
runner.succeed();
}
});
halfDuration = sb.buffered.end(0) / 2;
setDuration(halfDuration, ms, sb, function() {
self.log('Remove() complete.');
runner.checkApproxEq(ms.duration, halfDuration, 'ms.duration');
runner.checkApproxEq(sb.buffered.end(0), halfDuration,
'sb.buffered.end(0)');
sb.addEventListener('updateend', function onUpdate() {
sb.removeEventListener('updateend', onUpdate);
runner.checkApproxEq(ms.duration, sb.buffered.end(0),
'ms.duration');
sbUpdated = true;
if (durationChanged && sbUpdated) {
runner.succeed();
}
});
sb.appendBuffer(data);
});
};
sb.addEventListener('updateend', updateCb);
sb.appendBuffer(data);
});
xhr.send();
};
};
var createPausedTest = function(stream) {
var test = createConformanceTest(
'PausedStateWith' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if the paused state is correct before or ' +
' after appending data.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var sb = ms.addSourceBuffer(stream.mimetype);
runner.checkEq(media.paused, true, 'media.paused');
var xhr = runner.XHRManager.createRequest(stream.src,
function(e) {
runner.checkEq(media.paused, true, 'media.paused');
sb.appendBuffer(xhr.getResponseData());
runner.checkEq(media.paused, true, 'media.paused');
sb.addEventListener('updateend', function() {
runner.checkEq(media.paused, true, 'media.paused');
runner.succeed();
});
});
xhr.send();
};
};
var createVideoDimensionTest = function(videoStream, audioStream) {
var test = createConformanceTest('VideoDimension' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title =
'Test if the readyState transition is correct.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var videoChain = new ResetInit(new FixedAppendSize(
new FileSource(videoStream.src, runner.XHRManager, runner.timeouts),
65536));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
runner.checkEq(media.videoWidth, 0, 'video width');
runner.checkEq(media.videoHeight, 0, 'video height');
var totalSuccess = 0;
function checkSuccess() {
totalSuccess++;
if (totalSuccess == 2)
runner.succeed();
}
media.addEventListener('loadedmetadata', function(e) {
self.log('loadedmetadata called');
runner.checkEq(media.videoWidth, 640, 'video width');
runner.checkEq(media.videoHeight, 360, 'video height');
checkSuccess();
});
runner.checkEq(media.readyState, media.HAVE_NOTHING, 'readyState');
var audioXhr = runner.XHRManager.createRequest(audioStream.src,
function(e) {
var audioContent = audioXhr.getResponseData();
audioSb.appendBuffer(audioContent);
appendInit(media, videoSb, videoChain, 0, checkSuccess);
});
audioXhr.send();
};
};
var createPlaybackStateTest = function(stream) {
var test = createConformanceTest('PlaybackState' + stream.codec,
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if the playback state transition is correct.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var videoStream = stream;
var audioStream = Media.AAC.AudioTiny;
var videoChain = new ResetInit(new FixedAppendSize(
new FileSource(videoStream.src, runner.XHRManager, runner.timeouts),
65536));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioChain = new ResetInit(new FixedAppendSize(
new FileSource(audioStream.src, runner.XHRManager, runner.timeouts),
65536));
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
media.play();
runner.checkEq(media.currentTime, 0, 'media.currentTime');
media.pause();
runner.checkEq(media.currentTime, 0, 'media.currentTime');
appendInit(media, audioSb, audioChain, 0, function() {
appendInit(media, videoSb, videoChain, 0, function() {
callAfterLoadedMetaData(media, function() {
media.play();
runner.checkEq(media.currentTime, 0, 'media.currentTime');
media.pause();
runner.checkEq(media.currentTime, 0, 'media.currentTime');
media.play();
appendUntil(
runner.timeouts, media, audioSb, audioChain, 5, function() {
appendUntil(
runner.timeouts, media, videoSb, videoChain, 5, function() {
playThrough(runner.timeouts, media, 1, 2, audioSb,
audioChain, videoSb, videoChain, function() {
var time = media.currentTime;
media.pause();
runner.checkApproxEq(media.currentTime, time, 'media.currentTime');
runner.succeed();
});
});
});
});
});
});
};
};
var createPlayPartialSegmentTest = function(stream) {
var test = createConformanceTest('PlayPartial' + stream.codec + 'Segment',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if we can play a partially appended video segment.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
var videoStream = stream;
var audioStream = Media.AAC.AudioTiny;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoXhr = runner.XHRManager.createRequest(videoStream.src, function(e) {
videoSb.appendBuffer(this.getResponseData());
video.addEventListener('timeupdate', function(e) {
if (!video.paused && video.currentTime >= 2) {
runner.succeed();
}
});
video.play();
}, 0, 1500000);
var audioXhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.appendBuffer(this.getResponseData());
videoXhr.send();
}, 0, 500000);
audioXhr.send();
};
};
var createIncrementalAudioTest = function(stream) {
var test = createConformanceTest('Incremental' + stream.codec + 'Audio',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if we can play a partially appended audio segment.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(Media.VP9.mimetype);
var xhr = runner.XHRManager.createRequest(stream.src, function(e) {
sb.appendBuffer(xhr.getResponseData());
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(sb.buffered.end(0), stream.get(200000), 'Range end');
runner.succeed();
});
}, 0, 200000);
xhr.send();
};
};
var createAppendAudioOffsetTest = function(stream1, stream2) {
var test = createConformanceTest('Append' + stream1.codec + 'AudioOffset',
'MSE (' + stream1.codec + ')');
test.prototype.title =
'Test if we can append audio data with an explicit offset.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
var unused_sb = this.ms.addSourceBuffer(Media.VP9.mimetype);
var sb = this.ms.addSourceBuffer(stream1.mimetype);
var xhr = runner.XHRManager.createRequest(stream1.src, function(e) {
sb.timestampOffset = 5;
sb.appendBuffer(this.getResponseData());
sb.addEventListener('updateend', function callXhr2() {
sb.removeEventListener('updateend', callXhr2);
xhr2.send();
});
}, 0, 200000);
var xhr2 = runner.XHRManager.createRequest(stream2.src, function(e) {
sb.abort();
sb.timestampOffset = 0;
sb.appendBuffer(this.getResponseData());
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(
sb.buffered.end(0), stream2.get('appendAudioOffset'), 'Range end');
runner.succeed();
});
}, 0, 200000);
xhr.send();
};
};
var createAppendVideoOffsetTest = function(stream1, stream2, audioStream) {
var test = createConformanceTest('Append' + stream1.codec + 'VideoOffset',
'MSE (' + stream1.codec + ')');
test.prototype.title =
'Test if we can append video data with an explicit offset.';
test.prototype.onsourceopen = function() {
var self = this;
var runner = this.runner;
var video = this.video;
var sb = this.ms.addSourceBuffer(stream1.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var xhr = runner.XHRManager.createRequest(stream1.src, function(e) {
sb.timestampOffset = 5;
sb.appendBuffer(this.getResponseData());
sb.addEventListener('update', function callXhr2() {
sb.removeEventListener('update', callXhr2);
xhr2.send();
});
}, 0, 200000);
var xhr2 = runner.XHRManager.createRequest(stream2.src, function(e) {
sb.abort();
sb.timestampOffset = 0;
sb.appendBuffer(this.getResponseData());
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(sb.buffered.end(0),
stream2.get('videoChangeRate'), 'Range end');
callAfterLoadedMetaData(video, function() {
video.addEventListener('seeked', function(e) {
self.log('seeked called');
video.addEventListener('timeupdate', function(e) {
self.log('timeupdate called with ' + video.currentTime);
if (!video.paused && video.currentTime >= 6) {
runner.succeed();
}
});
});
video.currentTime = 6;
});
});
video.play();
}, 0, 400000);
this.ms.duration = 100000000; // Ensure that we can seek to any position.
var audioXhr = runner.XHRManager.createRequest(audioStream.src,
function(e) {
var audioContent = audioXhr.getResponseData();
audioSb.appendBuffer(audioContent);
xhr.send();
});
audioXhr.send();
};
};
var createAppendMultipleInitTest = function(stream, unused_stream) {
var test = createConformanceTest(
'AppendMultipleInit' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test if we can append multiple init segments.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new FileSource(stream.src, runner.XHRManager, runner.timeouts,
0, stream.size, stream.size);
var src = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var init;
function getEventAppend(cb, endCb) {
var chainCount = 0;
return function() {
if (chainCount < 10) {
++chainCount;
cb();
} else {
endCb();
}
};
}
chain.init(0, function(buf) {
init = buf;
chain.pull(function(buf) {
var firstAppend = getEventAppend(function() {
src.appendBuffer(init);
}, function() {
src.removeEventListener('update', firstAppend);
src.addEventListener('update', function abortAppend() {
src.removeEventListener('update', abortAppend);
src.abort();
var end = src.buffered.end(0);
var secondAppend = getEventAppend(function() {
src.appendBuffer(init);
}, function() {
runner.checkEq(src.buffered.end(0), end, 'Range end');
runner.succeed();
});
src.addEventListener('update', secondAppend);
secondAppend();
});
src.appendBuffer(buf);
});
src.addEventListener('update', firstAppend);
firstAppend();
});
});
};
};
var createAppendOutOfOrderTest = function(stream, unused_stream) {
var test = createConformanceTest(
'Append' + stream.codec + util.MakeCapitalName(stream.mediatype) + 'OutOfOrder',
'MSE (' + stream.codec + ')');
test.prototype.title = 'Test appending segments out of order.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new FileSource(stream.src, runner.XHRManager, runner.timeouts);
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var bufs = [];
var i = 0;
// Append order of the segments.
var appendOrder = [0, 2, 1, 4, 3];
// Number of segments given the append order, since segments get merged.
var bufferedLength = [0, 1, 1, 2, 1];
sb.addEventListener('updateend', function() {
runner.checkEq(sb.buffered.length, bufferedLength[i],
'Source buffer number');
if (i == 1) {
runner.checkGr(sb.buffered.start(0), 0, 'Range start');
} else if (i > 0) {
runner.checkEq(sb.buffered.start(0), 0, 'Range start');
}
i++;
if (i >= bufs.length) {
runner.succeed();
} else {
sb.appendBuffer(bufs[appendOrder[i]]);
}
});
chain.init(0, function(buf) {
bufs.push(buf);
chain.pull(function(buf) {
bufs.push(buf);
chain.pull(function(buf) {
bufs.push(buf);
chain.pull(function(buf) {
bufs.push(buf);
chain.pull(function(buf) {
bufs.push(buf);
sb.appendBuffer(bufs[0]);
});
});
});
});
});
};
};
var createBufferedRangeTest = function(stream, unused_stream) {
var test = createConformanceTest(
'BufferedRange' + stream.codec + util.MakeCapitalName(stream.mediatype),
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test SourceBuffer.buffered get updated correctly after feeding data.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new ResetInit(
new FileSource(stream.src, runner.XHRManager, runner.timeouts));
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
runner.checkEq(sb.buffered.length, 0, 'Source buffer number');
appendInit(media, sb, chain, 0, function() {
runner.checkEq(sb.buffered.length, 0, 'Source buffer number');
appendUntil(runner.timeouts, media, sb, chain, 5, function() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkEq(sb.buffered.start(0), 0, 'Source buffer number');
runner.checkGE(sb.buffered.end(0), 5, 'Range end');
runner.succeed();
});
});
};
};
var createMediaSourceDurationTest = function(videoStream, audioStream) {
var test = createConformanceTest('MediaSourceDuration' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title = 'Test if the duration on MediaSource can be set and ' +
'retrieved sucessfully.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var videoChain = new ResetInit(
new FileSource(videoStream.src, runner.XHRManager, runner.timeouts));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
var onsourceclose = function() {
self.log('onsourceclose called');
runner.assert(isNaN(ms.duration));
runner.succeed();
};
var appendVideo = function() {
runner.assert(isNaN(media.duration), 'Initial media duration not NaN');
media.play();
appendInit(media, videoSb, videoChain, 0, function() {
appendUntil(runner.timeouts, media, videoSb, videoChain, 10,
function() {
setDuration(5, ms, [videoSb, audioSb], function() {
runner.checkEq(ms.duration, 5, 'ms.duration');
runner.checkEq(media.duration, 5, 'media.duration');
runner.checkLE(videoSb.buffered.end(0), 5.1, 'Range end');
videoSb.abort();
videoChain.seek(0);
appendInit(media, videoSb, videoChain, 0, function() {
appendUntil(runner.timeouts, media, videoSb, videoChain, 10,
function() {
runner.checkApproxEq(ms.duration, 10, 'ms.duration');
setDuration(5, ms, [videoSb, audioSb], function() {
if (videoSb.updating) {
runner.fail('Source buffer is updating on duration change');
return;
}
var duration = videoSb.buffered.end(0);
ms.endOfStream();
runner.checkApproxEq(ms.duration, duration, 'ms.duration',
0.01);
ms.addEventListener('sourceended', function() {
runner.checkApproxEq(ms.duration, duration, 'ms.duration',
0.01);
runner.checkEq(media.duration, duration, 'media.duration');
ms.addEventListener('sourceclose', onsourceclose);
media.removeAttribute('src');
media.load();
});
media.play();
});
});
});
});
});
});
};
var audioXhr = runner.XHRManager.createRequest(audioStream.src,
function(e) {
audioSb.addEventListener('updateend', function onAudioUpdate() {
audioSb.removeEventListener('updateend', onAudioUpdate);
appendVideo();
});
var audioContent = audioXhr.getResponseData();
audioSb.appendBuffer(audioContent);
});
audioXhr.send();
};
};
var createOverlapTest = function(stream, unused_stream) {
var test = createConformanceTest(
stream.codec + util.MakeCapitalName(stream.mediatype) + 'WithOverlap',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if media data with overlap will be merged into one range.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new ResetInit(
new FileSource(stream.src, runner.XHRManager, runner.timeouts));
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var GAP = 0.1;
appendInit(media, sb, chain, 0, function() {
chain.pull(function(buf) {
sb.addEventListener('update', function appendOuter() {
sb.removeEventListener('update', appendOuter);
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
var segmentDuration = sb.buffered.end(0);
sb.timestampOffset = segmentDuration - GAP;
chain.seek(0);
chain.pull(function(buf) {
sb.addEventListener('update', function appendMiddle() {
sb.removeEventListener('update', appendMiddle);
chain.pull(function(buf) {
sb.addEventListener('update', function appendInner() {
runner.checkEq(
sb.buffered.length, 1, 'Source buffer number');
runner.checkApproxEq(sb.buffered.end(0),
segmentDuration * 2 - GAP, 'Range end');
runner.succeed();
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
};
};
var createSmallGapTest = function(stream, unused_stream) {
var test = createConformanceTest(
stream.codec + util.MakeCapitalName(stream.mediatype) + 'WithSmallGap',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if media data with a gap smaller than an media frame size ' +
'will be merged into one buffered range.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new ResetInit(
new FileSource(stream.src, runner.XHRManager, runner.timeouts));
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var GAP = 0.01;
appendInit(media, sb, chain, 0, function() {
chain.pull(function(buf) {
sb.addEventListener('update', function appendOuter() {
sb.removeEventListener('update', appendOuter);
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
var segmentDuration = sb.buffered.end(0);
sb.timestampOffset = segmentDuration + GAP;
chain.seek(0);
chain.pull(function(buf) {
sb.addEventListener('update', function appendMiddle() {
sb.removeEventListener('update', appendMiddle);
chain.pull(function(buf) {
sb.addEventListener('update', function appendInner() {
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
runner.checkApproxEq(sb.buffered.end(0),
segmentDuration * 2 + GAP, 'Range end');
runner.succeed();
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
};
};
var createLargeGapTest = function(stream, unused_stream) {
var test = createConformanceTest(
stream.codec + util.MakeCapitalName(stream.mediatype) + 'WithLargeGap',
'MSE (' + stream.codec + ')');
test.prototype.title =
'Test if media data with a gap larger than an media frame size ' +
'will not be merged into one buffered range.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var chain = new ResetInit(
new FileSource(stream.src, runner.XHRManager, runner.timeouts));
var sb = this.ms.addSourceBuffer(stream.mimetype);
var unused_sb = this.ms.addSourceBuffer(unused_stream.mimetype);
var GAP = 0.3;
appendInit(media, sb, chain, 0, function() {
chain.pull(function(buf) {
sb.addEventListener('update', function appendOuter() {
sb.removeEventListener('update', appendOuter);
runner.checkEq(sb.buffered.length, 1, 'Source buffer number');
var segmentDuration = sb.buffered.end(0);
sb.timestampOffset = segmentDuration + GAP;
chain.seek(0);
chain.pull(function(buf) {
sb.addEventListener('update', function appendMiddle() {
sb.removeEventListener('update', appendMiddle);
chain.pull(function(buf) {
sb.addEventListener('update', function appendInner() {
runner.checkEq(sb.buffered.length, 2, 'Source buffer number');
runner.succeed();
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
runner.assert(safeAppend(sb, buf), 'safeAppend failed');
});
});
};
};
var createSeekTest = function(videoStream) {
var test = createConformanceTest('Seek' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title = 'Test if we can seek during playing. It' +
' also tests if the implementation properly supports seek operation' +
' fired immediately after another seek that hasn\'t been completed.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var audioStream = Media.AAC.AudioNormal;
var videoChain = new ResetInit(new FileSource(
videoStream.src, runner.XHRManager, runner.timeouts));
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioChain = new ResetInit(new FileSource(
audioStream.src, runner.XHRManager, runner.timeouts));
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var self = this;
this.ms.duration = 100000000; // Ensure that we can seek to any position.
appendUntil(runner.timeouts, media, videoSb, videoChain, 20, function() {
appendUntil(runner.timeouts, media, audioSb, audioChain, 20, function() {
self.log('Seek to 17s');
callAfterLoadedMetaData(media, function() {
media.currentTime = 17;
media.play();
playThrough(
runner.timeouts, media, 10, 19,
videoSb, videoChain, audioSb, audioChain, function() {
runner.checkGE(media.currentTime, 19, 'currentTime');
self.log('Seek to 28s');
media.currentTime = 53;
media.currentTime = 58;
playThrough(
runner.timeouts, media, 10, 60,
videoSb, videoChain, audioSb, audioChain, function() {
runner.checkGE(media.currentTime, 60, 'currentTime');
self.log('Seek to 7s');
media.currentTime = 0;
media.currentTime = 7;
videoChain.seek(7, videoSb);
audioChain.seek(7, audioSb);
playThrough(runner.timeouts, media, 10, 9,
videoSb, videoChain, audioSb, audioChain, function() {
runner.checkGE(media.currentTime, 9, 'currentTime');
runner.succeed();
});
});
});
});
});
});
};
};
var createBufUnbufSeekTest = function(videoStream) {
var test = createConformanceTest('BufUnbufSeek' + videoStream.codec,
'MSE (' + videoStream.codec + ')');
test.prototype.title = 'Seek into and out of a buffered region.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var audioStream = Media.AAC.AudioNormal;
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var xhr = runner.XHRManager.createRequest(videoStream.src, function() {
videoSb.appendBuffer(xhr.getResponseData());
var xhr2 = runner.XHRManager.createRequest(audioStream.src, function() {
audioSb.appendBuffer(xhr2.getResponseData());
callAfterLoadedMetaData(media, function() {
var N = 30;
function loop(i) {
if (i > N) {
media.currentTime = 1.005;
media.addEventListener('timeupdate', function(e) {
if (!media.paused && media.currentTime > 3)
runner.succeed();
});
return;
}
media.currentTime = (i++ % 2) * 1.0e6 + 1;
runner.timeouts.setTimeout(loop.bind(null, i), 50);
}
media.play();
media.addEventListener('play', loop.bind(null, 0));
});
}, 0, 100000);
xhr2.send();
}, 0, 1000000);
this.ms.duration = 100000000; // Ensure that we can seek to any position.
xhr.send();
};
};
var createDelayedTest = function(delayed, nonDelayed) {
var test = createConformanceTest(
'Delayed' + delayed.codec + util.MakeCapitalName(delayed.mediatype),
'MSE (' + delayed.codec + ')');
test.prototype.title = 'Test if we can play properly when there' +
' is not enough ' + delayed.mediatype + ' data. The play should resume once ' +
delayed.mediatype + ' data is appended.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
// Chrome allows for 3 seconds of underflow for streams that have audio
// but are video starved. See code.google.com/p/chromium/issues/detail?id=423801
var underflowTime = 0.0;
if (delayed.mediatype == 'video') {
underflowTime = 3.0;
}
var chain = new FixedAppendSize(
new ResetInit(
new FileSource(nonDelayed.src, runner.XHRManager, runner.timeouts)
), 16384);
var src = this.ms.addSourceBuffer(nonDelayed.mimetype);
var delayedChain = new FixedAppendSize(
new ResetInit(
new FileSource(delayed.src, runner.XHRManager, runner.timeouts)
), 16384);
var delayedSrc = this.ms.addSourceBuffer(delayed.mimetype);
var self = this;
var ontimeupdate = function(e) {
if (!media.paused) {
var end = delayedSrc.buffered.end(0);
runner.checkLE(media.currentTime, end + 1.0 + underflowTime,
'media.currentTime (' + media.readyState + ')');
}
};
appendUntil(runner.timeouts, media, src, chain, 15, function() {
appendUntil(runner.timeouts, media, delayedSrc, delayedChain, 8,
function() {
var end = delayedSrc.buffered.end(0);
self.log('Start play when there is only ' + end + ' seconds of ' +
test.prototype.desc + ' data.');
media.play();
media.addEventListener('timeupdate', ontimeupdate);
waitUntil(runner.timeouts, media, end + 3, function() {
runner.checkLE(media.currentTime, end + 1.0 + underflowTime, 'media.currentTime');
runner.checkGr(media.currentTime, end - 1.0 - underflowTime, 'media.currentTime');
runner.succeed();
});
});
});
};
};
// Opus Specific tests.
createAppendTest(Media.Opus.SantaHigh, Media.VP9.Video1MB);
createAbortTest(Media.Opus.SantaHigh, Media.VP9.Video1MB);
createTimestampOffsetTest(Media.Opus.CarLow, Media.VP9.Video1MB);
createDurationAfterAppendTest(Media.Opus.CarLow, Media.VP9.Video1MB);
createPausedTest(Media.Opus.CarLow);
createIncrementalAudioTest(Media.Opus.CarMed);
createAppendAudioOffsetTest(Media.Opus.CarMed, Media.Opus.CarHigh);
createAppendMultipleInitTest(Media.Opus.CarLow, Media.VP9.Video1MB);
createAppendOutOfOrderTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createBufferedRangeTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createOverlapTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createSmallGapTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createLargeGapTest(Media.Opus.CarMed, Media.VP9.Video1MB);
createDelayedTest(Media.Opus.CarMed, Media.VP9.VideoNormal);
// AAC Specific tests.
createAppendTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createAbortTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createTimestampOffsetTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createDurationAfterAppendTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createPausedTest(Media.AAC.Audio1MB);
createIncrementalAudioTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createAppendAudioOffsetTest(Media.AAC.AudioNormal, Media.AAC.AudioHuge);
createAppendMultipleInitTest(Media.AAC.Audio1MB, Media.H264.Video1MB);
createAppendOutOfOrderTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createBufferedRangeTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createOverlapTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createSmallGapTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createLargeGapTest(Media.AAC.AudioNormal, Media.H264.Video1MB);
createDelayedTest(Media.AAC.AudioNormal, Media.VP9.VideoNormal);
// VP9 Specific tests.
createAppendTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createAbortTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createTimestampOffsetTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createDASHLatencyTest(Media.VP9.VideoTiny, Media.AAC.Audio1MB);
createDurationAfterAppendTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createPausedTest(Media.VP9.Video1MB);
createVideoDimensionTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createPlaybackStateTest(Media.VP9.VideoNormal);
createPlayPartialSegmentTest(Media.VP9.VideoTiny);
createAppendVideoOffsetTest(Media.VP9.VideoNormal, Media.VP9.VideoTiny,
Media.AAC.AudioNormal);
createAppendMultipleInitTest(Media.VP9.Video1MB, Media.AAC.Audio1MB);
createAppendOutOfOrderTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createBufferedRangeTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createMediaSourceDurationTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createOverlapTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createSmallGapTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createLargeGapTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
createSeekTest(Media.VP9.VideoNormal);
createBufUnbufSeekTest(Media.VP9.VideoNormal);
createDelayedTest(Media.VP9.VideoNormal, Media.AAC.AudioNormal);
// H264 Specific tests.
createAppendTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createAbortTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createTimestampOffsetTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createDASHLatencyTest(Media.H264.VideoTiny, Media.AAC.Audio1MB);
createDurationAfterAppendTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createPausedTest(Media.H264.Video1MB);
createVideoDimensionTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createPlaybackStateTest(Media.H264.VideoNormal);
createPlayPartialSegmentTest(Media.H264.VideoTiny);
createAppendVideoOffsetTest(Media.H264.VideoNormal, Media.H264.VideoTiny,
Media.AAC.Audio1MB);
createAppendMultipleInitTest(Media.H264.Video1MB, Media.AAC.Audio1MB);
createAppendOutOfOrderTest(Media.H264.CarMedium, Media.AAC.Audio1MB);
createBufferedRangeTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createMediaSourceDurationTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createOverlapTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createSmallGapTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createLargeGapTest(Media.H264.VideoNormal, Media.AAC.Audio1MB);
createSeekTest(Media.H264.VideoNormal);
createBufUnbufSeekTest(Media.H264.VideoNormal);
createDelayedTest(Media.H264.VideoNormal, Media.AAC.AudioNormal);
var testWAAContext = createConformanceTest('WAAPresence', 'MSE Web Audio API');
testWAAContext.prototype.title = 'Test if AudioContext is supported';
testWAAContext.prototype.start = function(runner, video) {
var Ctor = window.AudioContext || window.webkitAudioContext;
if (!Ctor)
return runner.fail('No AudioContext object available.');
var ctx = new Ctor();
if (!ctx)
return runner.fail('Found AudioContext but could not create one');
runner.succeed();
};
var createCreateMESTest = function(audioStream, videoStream) {
var test = createConformanceTest(
audioStream.codec + '/' + videoStream.codec + 'CreateMediaElementSource',
'MSE Web Audio API (Optional)',
false);
test.prototype.title =
'Test if AudioContext#createMediaElementSource supports mimetype ' +
audioStream.mimetype + '/' + videoStream.mimetype;
test.prototype.onsourceopen = function() {
var runner = this.runner;
var video = this.video;
try {
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
} catch (e) {
runner.fail(e.message);
return;
}
var Ctor = window.AudioContext || window.webkitAudioContext;
var ctx = new Ctor();
var audioXhr =
runner.XHRManager.createRequest(audioStream.src, function(e) {
var data = audioXhr.getResponseData();
function updateEnd(e) {
runner.checkEq(audioSb.buffered.length, 1, 'Source buffer number');
runner.checkEq(audioSb.buffered.start(0), 0, 'Range start');
runner.checkApproxEq(
audioSb.buffered.end(0), audioStream.duration, 'Range end');
audioSb.removeEventListener('updateend', updateEnd);
video.play();
}
audioSb.addEventListener('updateend', updateEnd);
audioSb.appendBuffer(data);
});
var videoXhr =
runner.XHRManager.createRequest(videoStream.src, function(e) {
var data = videoXhr.getResponseData();
videoSb.appendBuffer(data);
audioXhr.send();
});
videoXhr.send();
video.addEventListener('timeupdate', function onTimeUpdate() {
if (!video.paused && video.currentTime >= 5) {
video.removeEventListener('timeupdate', onTimeUpdate);
try {
runner.log('Creating MES');
var source = ctx.createMediaElementSource(video);
} catch (e) {
runner.fail(e);
return;
} finally {
ctx.close();
}
runner.checkNE(source, null, 'MediaElementSource');
runner.succeed();
}
});
}
}
createCreateMESTest(Media.Opus.CarLow, Media.VP9.VideoNormal);
createCreateMESTest(Media.AAC.Audio1MB, Media.VP9.VideoNormal);
createCreateMESTest(Media.AAC.Audio1MB, Media.H264.VideoNormal);
var frameTestOnSourceOpen = function() {
var runner = this.runner;
var media = this.video;
var audioStream = Media.AAC.AudioNormal;
var videoChain = new FixedAppendSize(new ResetInit(
new FileSource(this.filename, runner.XHRManager, runner.timeouts)));
var videoSb = this.ms.addSourceBuffer(Media.H264.mimetype);
var audioChain = new FixedAppendSize(new ResetInit(
new FileSource(audioStream.src, runner.XHRManager, runner.timeouts)));
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
media.play();
playThrough(runner.timeouts, media, 5, 18, videoSb, videoChain,
audioSb, audioChain, runner.succeed.bind(runner));
};
var testFrameGaps = createConformanceTest('H264FrameGaps', 'Media');
testFrameGaps.prototype.title = 'Test media with frame durations of 24FPS ' +
'but segment timing corresponding to 23.976FPS';
testFrameGaps.prototype.filename = Media.H264.FrameGap.src;
testFrameGaps.prototype.onsourceopen = frameTestOnSourceOpen;
var testFrameOverlaps = createConformanceTest('H264FrameOverlaps', 'Media');
testFrameOverlaps.prototype.title = 'Test media with frame durations of ' +
'23.976FPS but segment timing corresponding to 24FPS';
testFrameOverlaps.prototype.filename = Media.H264.FrameOverlap.src;
testFrameOverlaps.prototype.onsourceopen = frameTestOnSourceOpen;
var createAudio51Test = function(audioStream) {
var test = createConformanceTest(audioStream.codec + '5.1', 'Media');
test.prototype.title = 'Test 5.1-channel ' + audioStream.codec;
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var videoStream = Media.VP9.VideoNormal;
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var xhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.appendBuffer(xhr.getResponseData());
var xhr2 = runner.XHRManager.createRequest(videoStream.src, function(e) {
videoSb.appendBuffer(xhr2.getResponseData());
media.play();
media.addEventListener('timeupdate', function(e) {
if (!media.paused && media.currentTime > 2) {
runner.succeed();
}
});
}, 0, 3000000);
xhr2.send();
});
xhr.send();
}
}
createAudio51Test(Media.Opus.Audio51);
createAudio51Test(Media.AAC.Audio51);
var createHeAacTest = function(audioStream) {
var test = createConformanceTest('HE-AAC/' +
audioStream.get('sbrSignaling') + 'SBR', 'Media');
test.prototype.title = 'Test playback of HE-AAC with ' +
audioStream.get('sbrSignaling') + ' SBR signaling.';
test.prototype.onsourceopen = function() {
var runner = this.runner;
var media = this.video;
var ms = this.ms;
var videoStream = Media.VP9.Video1MB;
var audioSb = this.ms.addSourceBuffer(audioStream.mimetype);
var videoSb = this.ms.addSourceBuffer(videoStream.mimetype);
var xhr = runner.XHRManager.createRequest(audioStream.src, function(e) {
audioSb.addEventListener('update', function() {
var xhr2 = runner.XHRManager.createRequest(videoStream.src,
function(e) {
videoSb.addEventListener('update', function() {
ms.endOfStream();
media.addEventListener('ended', function(e) {
if (media.currentTime > audioStream.duration + 1) {
runner.fail();
} else {
runner.checkApproxEq(media.currentTime, audioStream.duration,
'media.currentTime');
runner.succeed();
}
});
media.play();
});
videoSb.appendBuffer(xhr2.getResponseData());
}, 0, videoStream.size);
xhr2.send();
});
audioSb.appendBuffer(xhr.getResponseData());
}, 0, audioStream.size);
xhr.send();
}
}
createHeAacTest(Media.AAC.AudioLowExplicitHE);
createHeAacTest(Media.AAC.AudioLowImplicitHE);
return {tests: tests, info: info, fields: fields, viewType: 'default'};
};
| Make currentTimePausedAccuracy test optional
Bug: 78182905
Change-Id: I9e460973efba2e359295e54c7c529e2d36bba813
| js/tests/tip/conformanceTest.js | Make currentTimePausedAccuracy test optional | <ide><path>s/tests/tip/conformanceTest.js
<ide> var createCurrentTimePausedAccuracyTest =
<ide> function(videoStream, audioStream, frameRate) {
<ide> var test = createConformanceTest(
<del> frameRate + 'PausedAccuracy', 'MSE currentTime');
<add> frameRate + 'PausedAccuracy', 'MSE currentTime', false);
<ide> test.prototype.title = 'Test the currentTime granularity when pause.';
<ide> test.prototype.onsourceopen = function() {
<ide> var maxDiffInS = 0.032; |
|
Java | apache-2.0 | 07738b753d914f4f7d560191946fa524767a8b1c | 0 | Ryan800/realm-java,davicaetano/realm-java,DuongNTdev/realm-java,thdtjsdn/realm-java,DuongNTdev/realm-java,realm/realm-java,alwakelab/realm-java,Rowandjj/realm-java,hgl888/realm-java,cpinan/realm-java,mio4kon/realm-java,FabianTerhorst/realm-java,ShikaSD/realm-java,nartex/realm-java,awesome-niu/realm-java,dantman/realm-java,FabianTerhorst/realm-java,awesome-niu/realm-java,ShikaSD/realm-java,avipars/realm-java,GavinThePacMan/realm-java,JetXing/realm-java,mobileperfman/realm-java,alwakelab/realm-java,realm/realm-java,thdtjsdn/realm-java,realm/realm-java,avipars/realm-java,kidaa/realm-java,nartex/realm-java,bunnyblue/realm-java,yuuki1224/realm-java,alwakelab/realm-java,realm/realm-java,hgl888/realm-java,santoshmehta82/realm-java,ysnows/realm-java,bunnyblue/realm-java,JetXing/realm-java,mobileperfman/realm-java,horie1024/realm-java,myroid/realm-java,qingsong-xu/realm-java,ShikaSD/realm-java,thdtjsdn/realm-java,androiddream/realm-java,arunlodhi/realm-java,realm/realm-java,santoshmehta82/realm-java,horie1024/realm-java,santoshmehta82/realm-java,xxccll/realm-java,GeorgeMe/realm-java,GavinThePacMan/realm-java,GavinThePacMan/realm-java,msdgwzhy6/realm-java,DuongNTdev/realm-java,davicaetano/realm-java,dantman/realm-java,myroid/realm-java,ysnows/realm-java,GeorgeMe/realm-java,angcyo/realm-java,msdgwzhy6/realm-java,qingsong-xu/realm-java,kidaa/realm-java,arunlodhi/realm-java,teddywest32/realm-java,yuuki1224/realm-java,xxccll/realm-java,nartex/realm-java,qingsong-xu/realm-java,yuuki1224/realm-java,angcyo/realm-java,realm/realm-java,mio4kon/realm-java,arunlodhi/realm-java,xxccll/realm-java,myroid/realm-java,awesome-niu/realm-java,ppamorim/realm-java,teddywest32/realm-java,horie1024/realm-java,teddywest32/realm-java,kidaa/realm-java,msdgwzhy6/realm-java,mio4kon/realm-java,GeorgeMe/realm-java,msdgwzhy6/realm-java,androiddream/realm-java,ysnows/realm-java,hgl888/realm-java,mobileperfman/realm-java,thdtjsdn/realm-java,bunnyblue/realm-java,androiddream/realm-java,GavinThePacMan/realm-java,ShikaSD/realm-java,cpinan/realm-java,angcyo/realm-java,Ryan800/realm-java,JetXing/realm-java,awesome-niu/realm-java,Rowandjj/realm-java,avipars/realm-java,teddywest32/realm-java,ppamorim/realm-java,dantman/realm-java,hgl888/realm-java,FabianTerhorst/realm-java,ppamorim/realm-java,davicaetano/realm-java,ShikaSD/realm-java,Rowandjj/realm-java,Ryan800/realm-java,GeorgeMe/realm-java,DuongNTdev/realm-java,ppamorim/realm-java,realm/realm-java,teddywest32/realm-java,cpinan/realm-java,angcyo/realm-java | package io.realm;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.BaseAdapter;
import org.jetbrains.annotations.NotNull;
public abstract class RealmBaseAdapter<T extends RealmObject> extends BaseAdapter {
protected LayoutInflater inflater;
protected RealmResults<T> realmResults;
protected Context context;
protected int resId;
public RealmBaseAdapter(@NotNull Context context, int resId, @NotNull RealmResults<T> realmResults, boolean automaticUpdate) {
this.resId = resId;
this.context = context;
this.realmResults = realmResults;
this.inflater = LayoutInflater.from(context);
if (automaticUpdate) {
realmResults.getRealm().addChangeListener(new RealmChangeListener() {
@Override
public void onChange() {
notifyDataSetChanged();
}
});
}
}
@Override
public int getCount() {
return realmResults.size();
}
@Override
public T getItem(int i) {
return realmResults.get(i);
}
@Override
@Deprecated
public long getItemId(int i) {
return i; // TODO: find better solution
}
/**
* Update the RealmResults associated to the Adapter. Useful when the query has been changed.
* If the query does not change you might consider using the automaticUpdate feature
* @param realmResults the new RealmResults coming from the new query.
*/
public void updateRealmResults(RealmResults<T> realmResults) {
this.realmResults = realmResults;
notifyDataSetChanged();
}
}
| realm/src/main/java/io/realm/RealmBaseAdapter.java | package io.realm;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.BaseAdapter;
import org.jetbrains.annotations.NotNull;
public abstract class RealmBaseAdapter<T extends RealmObject> extends BaseAdapter {
protected LayoutInflater inflater;
protected RealmResults<T> realmResults;
protected Context context;
protected int resId;
public RealmBaseAdapter(@NotNull Context context, int resId, @NotNull RealmResults<T> realmResults, boolean automaticUpdate) {
this.resId = resId;
this.context = context;
this.realmResults = realmResults;
this.inflater = LayoutInflater.from(context);
if (automaticUpdate) {
realmResults.getRealm().addChangeListener(new RealmChangeListener() {
@Override
public void onChange() {
notifyDataSetChanged();
}
});
}
}
@Override
public int getCount() {
return realmResults.size();
}
@Override
public T getItem(int i) {
return realmResults.get(i);
}
@Override
@Deprecated
public long getItemId(int i) {
throw new UnsupportedOperationException("Realms are unordered, hence its objects don't have an immutable Id");
}
/**
* Update the RealmResults associated to the Adapter. Useful when the query has been changed.
* If the query does not change you might consider using the automaticUpdate feature
* @param realmResults the new RealmResults coming from the new query.
*/
public void updateRealmResults(RealmResults<T> realmResults) {
this.realmResults = realmResults;
notifyDataSetChanged();
}
}
| Minor fix | realm/src/main/java/io/realm/RealmBaseAdapter.java | Minor fix | <ide><path>ealm/src/main/java/io/realm/RealmBaseAdapter.java
<ide> @Override
<ide> @Deprecated
<ide> public long getItemId(int i) {
<del> throw new UnsupportedOperationException("Realms are unordered, hence its objects don't have an immutable Id");
<add> return i; // TODO: find better solution
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 31b1a68a1f609b6cfc544513f8a382d87ea2bdd8 | 0 | apache/incubator-taverna-engine,apache/incubator-taverna-engine | /*******************************************************************************
* Copyright (C) 2007 The University of Manchester
*
* Modifications to the initial code base are copyright of their
* respective authors, or their employers as appropriate.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
******************************************************************************/
package net.sf.taverna.t2.workflowmodel.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import net.sf.taverna.t2.annotation.annotationbeans.IdentificationAssertion;
import net.sf.taverna.t2.workflowmodel.CompoundEdit;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workflowmodel.DataflowInputPort;
import net.sf.taverna.t2.workflowmodel.DataflowOutputPort;
import net.sf.taverna.t2.workflowmodel.Datalink;
import net.sf.taverna.t2.workflowmodel.Edit;
import net.sf.taverna.t2.workflowmodel.EditException;
import net.sf.taverna.t2.workflowmodel.Edits;
import net.sf.taverna.t2.workflowmodel.EventForwardingOutputPort;
import net.sf.taverna.t2.workflowmodel.EventHandlingInputPort;
import net.sf.taverna.t2.workflowmodel.InputPort;
import net.sf.taverna.t2.workflowmodel.Merge;
import net.sf.taverna.t2.workflowmodel.MergeInputPort;
import net.sf.taverna.t2.workflowmodel.MergeOutputPort;
import net.sf.taverna.t2.workflowmodel.NamedWorkflowEntity;
import net.sf.taverna.t2.workflowmodel.OutputPort;
import net.sf.taverna.t2.workflowmodel.Port;
import net.sf.taverna.t2.workflowmodel.Processor;
import net.sf.taverna.t2.workflowmodel.ProcessorInputPort;
import net.sf.taverna.t2.workflowmodel.ProcessorOutputPort;
import net.sf.taverna.t2.workflowmodel.TokenProcessingEntity;
import net.sf.taverna.t2.workflowmodel.processor.activity.Activity;
import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityConfigurationException;
import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityInputPort;
import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityOutputPort;
import net.sf.taverna.t2.workflowmodel.processor.activity.DisabledActivity;
import net.sf.taverna.t2.workflowmodel.processor.activity.NestedDataflow;
import org.apache.log4j.Logger;
/**
* Various workflow model tools that can be helpful when constructing a
* dataflow.
* <p>
* Not to be confused with the @deprecated
* {@link net.sf.taverna.t2.workflowmodel.impl.Tools}
*
* @author David Withers
* @author Stian Soiland-Reyes
*
*/
public class Tools {
private static Logger logger = Logger.getLogger(Tools.class);
// private static Edits edits = new EditsImpl();
/**
* Find (and possibly create) an EventHandlingInputPort.
* <p>
* If the given inputPort is an instance of {@link EventHandlingInputPort},
* it is returned directly. If it is an ActivityInputPort - the owning
* processors (found by searching the dataflow) will be searced for a mapped
* input port. If this cannot be found, one will be created and mapped. The
* edits for this will be added to the editList and needs to be executed by
* the caller.
*
* @see #findEventHandlingOutputPort(List, Dataflow, OutputPort)
* @param editList
* List of {@link Edit}s to append any required edits (yet to be
* performed) to
* @param dataflow
* Dataflow containing the processors
* @param inputPort
* An EventHandlingInputPort or ActivityInputPort
* @return The found or created EventHandlingInputPort
*/
@SuppressWarnings("unchecked")
protected static EventHandlingInputPort findEventHandlingInputPort(
List<Edit<?>> editList, Dataflow dataflow, InputPort inputPort, Edits edits) {
if (inputPort instanceof EventHandlingInputPort) {
return (EventHandlingInputPort) inputPort;
} else if (!(inputPort instanceof ActivityInputPort)) {
throw new IllegalArgumentException("Unknown input port type for "
+ inputPort);
}
ActivityInputPort activityInput = (ActivityInputPort) inputPort;
Collection<Processor> processors = Tools
.getProcessorsWithActivityInputPort(dataflow, activityInput);
if (processors.isEmpty()) {
throw new IllegalArgumentException("Can't find ActivityInputPort "
+ activityInput.getName() + " in workflow " + dataflow);
}
// FIXME: Assumes only one matching processor
Processor processor = processors.iterator().next();
Activity activity = null;
for (Activity checkActivity : processor.getActivityList()) {
if (checkActivity.getInputPorts().contains(activityInput)) {
activity = checkActivity;
break;
}
}
if (activity == null) {
throw new IllegalArgumentException("Can't find activity for port "
+ activityInput.getName() + "within processor " + processor);
}
ProcessorInputPort input = Tools.getProcessorInputPort(processor,
activity, activityInput);
if (input != null) {
return input;
}
// port doesn't exist so create a processor port and map it
String processorPortName = uniquePortName(activityInput.getName(),
processor.getInputPorts());
ProcessorInputPort processorInputPort = edits.createProcessorInputPort(
processor, processorPortName, activityInput.getDepth());
editList.add(edits.getAddProcessorInputPortEdit(processor,
processorInputPort));
editList.add(edits.getAddActivityInputPortMappingEdit(activity,
processorPortName, activityInput.getName()));
return processorInputPort;
}
/**
* Find (and possibly create) an EventForwardingOutputPort.
* <p>
* If the given outputPort is an instance of
* {@link EventForwardingOutputPort}, it is returned directly. If it is an
* ActivityOutputPort - the owning processors (found by searching the
* dataflow) will be searced for a mapped output port. If this cannot be
* found, one will be created and mapped. The edits for this will be added
* to the editList and needs to be executed by the caller.
*
* @see #findEventHandlingInputPort(List, Dataflow, InputPort)
* @param editList
* List of {@link Edit}s to append any required edits (yet to be
* performed) to
* @param dataflow
* Dataflow containing the processors
* @param outputPort
* An EventForwardingOutputPort or ActivityOutputPort
* @return The found or created EventForwardingOutputPort
*/
@SuppressWarnings("unchecked")
protected static EventForwardingOutputPort findEventHandlingOutputPort(
List<Edit<?>> editList, Dataflow dataflow, OutputPort outputPort, Edits edits) {
if (outputPort instanceof EventForwardingOutputPort) {
return (EventForwardingOutputPort) outputPort;
} else if (!(outputPort instanceof ActivityOutputPort)) {
throw new IllegalArgumentException("Unknown output port type for "
+ outputPort);
}
ActivityOutputPort activityOutput = (ActivityOutputPort) outputPort;
Collection<Processor> processors = Tools
.getProcessorsWithActivityOutputPort(dataflow, activityOutput);
if (processors.isEmpty()) {
throw new IllegalArgumentException("Can't find ActivityOutputPort "
+ activityOutput.getName() + " in workflow " + dataflow);
}
// FIXME: Assumes only one matching processor
Processor processor = processors.iterator().next();
Activity activity = null;
for (Activity checkActivity : processor.getActivityList()) {
if (checkActivity.getOutputPorts().contains(activityOutput)) {
activity = checkActivity;
break;
}
}
if (activity == null) {
throw new IllegalArgumentException("Can't find activity for port "
+ activityOutput.getName() + "within processor "
+ processor);
}
ProcessorOutputPort processorOutputPort = Tools.getProcessorOutputPort(
processor, activity, activityOutput);
if (processorOutputPort != null) {
return processorOutputPort;
}
// port doesn't exist so create a processor port and map it
String processorPortName = uniquePortName(activityOutput.getName(),
processor.getOutputPorts());
processorOutputPort = edits.createProcessorOutputPort(processor,
processorPortName, activityOutput.getDepth(), activityOutput
.getGranularDepth());
editList.add(edits.getAddProcessorOutputPortEdit(processor,
processorOutputPort));
editList.add(edits.getAddActivityOutputPortMappingEdit(activity,
processorPortName, activityOutput.getName()));
return processorOutputPort;
}
/**
* Creates an Edit that creates a Datalink between a source and sink port
* and connects the Datalink.
*
* If the sink port already has a Datalink connected this method checks if a
* new Merge is required and creates and connects the required Datalinks.
*
* @param dataflow
* the Dataflow to add the Datalink to
* @param source
* the source of the Datalink
* @param sink
* the source of the Datalink
* @return an Edit that creates a Datalink between a source and sink port
* and connects the Datalink
*/
public static Edit<?> getCreateAndConnectDatalinkEdit(Dataflow dataflow,
EventForwardingOutputPort source, EventHandlingInputPort sink, Edits edits) {
Edit<?> edit = null;
Datalink incomingLink = sink.getIncomingLink();
if (incomingLink == null) {
Datalink datalink = edits.createDatalink(source, sink);
edit = edits.getConnectDatalinkEdit(datalink);
} else {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
Merge merge = null;
int counter = 0; // counter for merge input port names
if (incomingLink.getSource() instanceof MergeOutputPort) {
merge = ((MergeOutputPort) incomingLink.getSource()).getMerge();
} else {
merge = edits.createMerge(dataflow);
editList.add(edits.getAddMergeEdit(dataflow, merge));
editList.add(edits.getDisconnectDatalinkEdit(incomingLink));
MergeInputPort mergeInputPort = edits.createMergeInputPort(
merge, getUniqueMergeInputPortName(merge, incomingLink
.getSource().getName()
+ "To" + merge.getLocalName() + "_input",
counter++), incomingLink.getSink().getDepth());
editList.add(edits.getAddMergeInputPortEdit(merge,
mergeInputPort));
Datalink datalink = edits.createDatalink(incomingLink
.getSource(), mergeInputPort);
editList.add(edits.getConnectDatalinkEdit(datalink));
datalink = edits.createDatalink(merge.getOutputPort(),
incomingLink.getSink());
editList.add(edits.getConnectDatalinkEdit(datalink));
}
MergeInputPort mergeInputPort = edits.createMergeInputPort(merge,
getUniqueMergeInputPortName(merge, source.getName() + "To"
+ merge.getLocalName() + "_input", counter), sink
.getDepth());
editList.add(edits.getAddMergeInputPortEdit(merge, mergeInputPort));
Datalink datalink = edits.createDatalink(source, mergeInputPort);
editList.add(edits.getConnectDatalinkEdit(datalink));
edit = new CompoundEdit(editList);
}
return edit;
}
/**
* Get an {@link Edit} that will link the given output port to the given
* input port.
* <p>
* The output port can be an {@link EventForwardingOutputPort} (such as an
* {@link ProcessorOutputPort}, or an {@link ActivityOutputPort}. The input
* port can be an {@link EventHandlingInputPort} (such as an
* {@link ProcessorInputPort}, or an {@link ActivityInputPort}.
* <p>
* If an input and/or output port is an activity port, processors in the
* given dataflow will be searched for matching mappings, create the
* processor port and mapping if needed, before constructing the edits for
* adding the datalink.
*
* @param dataflow
* Dataflow (indirectly) containing ports
* @param outputPort
* An {@link EventForwardingOutputPort} or an
* {@link ActivityOutputPort}
* @param inputPort
* An {@link EventHandlingInputPort} or an
* {@link ActivityInputPort}
* @return A compound edit for creating and connecting the datalink and any
* neccessary processor ports and mappings
*/
public static Edit<?> getCreateAndConnectDatalinkEdit(Dataflow dataflow,
OutputPort outputPort, InputPort inputPort, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
EventHandlingInputPort sink = findEventHandlingInputPort(editList,
dataflow, inputPort, edits);
EventForwardingOutputPort source = findEventHandlingOutputPort(
editList, dataflow, outputPort, edits);
editList.add(getCreateAndConnectDatalinkEdit(dataflow, source, sink, edits));
return new CompoundEdit(editList);
}
/**
* Find a unique port name given a list of existing ports.
* <p>
* If needed, the returned port name will be prefixed with an underscore and a number,
* starting from 2. (The original being 'number 1')
* <p>
* Although not strictly needed by Taverna, for added user friendliness the
* case of the existing port names are ignored when checking for uniqueness.
*
* @see #uniqueProcessorName(String, Dataflow)
*
* @param suggestedPortName
* Port name suggested for new port
* @param existingPorts
* Collection of existing {@link Port}s
* @return A port name unique for the given collection of port
*/
public static String uniquePortName(String suggestedPortName,
Collection<? extends Port> existingPorts) {
// Make sure we have a unique port name
Set<String> existingNames = new HashSet<String>();
for (Port existingPort : existingPorts) {
existingNames.add(existingPort.getName().toLowerCase());
}
String candidateName = suggestedPortName;
long counter = 2;
while (existingNames.contains(candidateName.toLowerCase())) {
candidateName = suggestedPortName + "_" + counter++;
}
return candidateName;
}
public static Edit<?> getMoveDatalinkSinkEdit(Dataflow dataflow,
Datalink datalink, EventHandlingInputPort sink, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
editList.add(edits.getDisconnectDatalinkEdit(datalink));
if (datalink.getSink() instanceof ProcessorInputPort) {
editList
.add(getRemoveProcessorInputPortEdit((ProcessorInputPort) datalink
.getSink(), edits));
}
editList.add(getCreateAndConnectDatalinkEdit(dataflow, datalink
.getSource(), sink, edits));
return new CompoundEdit(editList);
}
public static Edit<?> getDisconnectDatalinkAndRemovePortsEdit(
Datalink datalink, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
editList.add(edits.getDisconnectDatalinkEdit(datalink));
if (datalink.getSource() instanceof ProcessorOutputPort) {
ProcessorOutputPort processorOutputPort = (ProcessorOutputPort) datalink
.getSource();
if (processorOutputPort.getOutgoingLinks().size() == 1) {
editList
.add(getRemoveProcessorOutputPortEdit(processorOutputPort, edits));
}
}
if (datalink.getSink() instanceof ProcessorInputPort) {
editList
.add(getRemoveProcessorInputPortEdit((ProcessorInputPort) datalink
.getSink(), edits));
}
return new CompoundEdit(editList);
}
public static Edit<?> getRemoveProcessorOutputPortEdit(
ProcessorOutputPort port, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
Processor processor = port.getProcessor();
editList.add(edits.getRemoveProcessorOutputPortEdit(
port.getProcessor(), port));
for (Activity<?> activity : processor.getActivityList()) {
editList.add(edits.getRemoveActivityOutputPortMappingEdit(activity,
port.getName()));
}
return new CompoundEdit(editList);
}
public static Edit<?> getRemoveProcessorInputPortEdit(
ProcessorInputPort port, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
Processor processor = port.getProcessor();
editList.add(edits.getRemoveProcessorInputPortEdit(port.getProcessor(),
port));
for (Activity<?> activity : processor.getActivityList()) {
editList.add(edits.getRemoveActivityInputPortMappingEdit(activity,
port.getName()));
}
return new CompoundEdit(editList);
}
public static Edit<?> getEnableDisabledActivityEdit(Processor processor, DisabledActivity disabledActivity, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
Activity<?> brokenActivity = disabledActivity.getActivity();
try {
Activity ra = brokenActivity.getClass().newInstance();
Object lastConfig = disabledActivity.getLastWorkingConfiguration();
if (lastConfig == null) {
lastConfig = disabledActivity.getActivityConfiguration();
}
ra.configure(lastConfig);
Map<String, String> portMapping = ra.getInputPortMapping();
Set<String> portNames = new HashSet<String>();
portNames.addAll(portMapping.keySet());
for (String portName : portNames) {
editList.add(edits.getRemoveActivityInputPortMappingEdit(ra, portName));
}
portMapping = ra.getOutputPortMapping();
portNames.clear();
portNames.addAll(portMapping.keySet());
for (String portName : portNames) {
editList.add(edits.getRemoveActivityOutputPortMappingEdit(ra, portName));
}
portMapping = disabledActivity.getInputPortMapping();
for (String portName : portMapping.keySet()) {
editList.add(edits.getAddActivityInputPortMappingEdit(ra, portName, portMapping.get(portName)));
}
portMapping = disabledActivity.getOutputPortMapping();
for (String portName : portMapping.keySet()) {
editList.add(edits.getAddActivityOutputPortMappingEdit(ra, portName, portMapping.get(portName)));
}
editList.add(edits.getRemoveActivityEdit(processor, disabledActivity));
editList.add(edits.getAddActivityEdit(processor, ra));
}
catch (ActivityConfigurationException ex) {
logger.error("Configuration exception ", ex);
return null;
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
}
return new CompoundEdit(editList);
}
public static ProcessorInputPort getProcessorInputPort(Processor processor,
Activity<?> activity, InputPort activityInputPort) {
ProcessorInputPort result = null;
for (Entry<String, String> mapEntry : activity.getInputPortMapping()
.entrySet()) {
if (mapEntry.getValue().equals(activityInputPort.getName())) {
for (ProcessorInputPort processorInputPort : processor
.getInputPorts()) {
if (processorInputPort.getName().equals(mapEntry.getKey())) {
result = processorInputPort;
break;
}
}
break;
}
}
return result;
}
public static ProcessorOutputPort getProcessorOutputPort(
Processor processor, Activity<?> activity,
OutputPort activityOutputPort) {
ProcessorOutputPort result = null;
for (Entry<String, String> mapEntry : activity.getOutputPortMapping()
.entrySet()) {
if (mapEntry.getValue().equals(activityOutputPort.getName())) {
for (ProcessorOutputPort processorOutputPort : processor
.getOutputPorts()) {
if (processorOutputPort.getName().equals(mapEntry.getKey())) {
result = processorOutputPort;
break;
}
}
break;
}
}
return result;
}
public static ActivityInputPort getActivityInputPort(Activity<?> activity,
String portName) {
ActivityInputPort activityInputPort = null;
for (ActivityInputPort inputPort : activity.getInputPorts()) {
if (inputPort.getName().equals(portName)) {
activityInputPort = inputPort;
break;
}
}
return activityInputPort;
}
public static OutputPort getActivityOutputPort(Activity<?> activity,
String portName) {
OutputPort activityOutputPort = null;
for (OutputPort outputPort : activity.getOutputPorts()) {
if (outputPort.getName().equals(portName)) {
activityOutputPort = outputPort;
break;
}
}
return activityOutputPort;
}
public static String getUniqueMergeInputPortName(Merge merge, String name,
int count) {
String uniqueName = name + count;
for (MergeInputPort mergeInputPort : merge.getInputPorts()) {
if (mergeInputPort.getName().equals(uniqueName)) {
return getUniqueMergeInputPortName(merge, name, ++count);
}
}
return uniqueName;
}
public static Collection<Processor> getProcessorsWithActivity(
Dataflow dataflow, Activity<?> activity) {
Set<Processor> processors = new HashSet<Processor>();
for (Processor processor : dataflow.getProcessors()) {
if (processor.getActivityList().contains(activity)) {
processors.add(processor);
}
}
return processors;
}
public static Collection<Processor> getProcessorsWithActivityInputPort(
Dataflow dataflow, ActivityInputPort inputPort) {
Set<Processor> processors = new HashSet<Processor>();
for (Processor processor : dataflow.getProcessors()) {
// Does it contain a nested workflow?
if (containsNestedWorkflow(processor)) {
// Get the nested workflow and check all its nested processors
Dataflow nestedWorkflow = ((NestedDataflow) processor
.getActivityList().get(0)).getNestedDataflow();
Collection<Processor> nested_processors = getProcessorsWithActivityInputPort(
nestedWorkflow, inputPort);
if (!nested_processors.isEmpty())
processors.addAll(nested_processors);
}
// Check all processor's activities (even if the processor contained
// a nested workflow,
// as its dataflow activity still contains input and output ports)
for (Activity<?> activity : processor.getActivityList()) {
if (activity.getInputPorts().contains(inputPort)) {
processors.add(processor);
}
}
}
return processors;
}
public static Collection<Processor> getProcessorsWithActivityOutputPort(
Dataflow dataflow, OutputPort outputPort) {
Set<Processor> processors = new HashSet<Processor>();
for (Processor processor : dataflow.getProcessors()) {
// Does it contain a nested workflow?
if (containsNestedWorkflow(processor)) {
// Get the nested workflow and check all its nested processors
Dataflow nestedWorkflow = ((NestedDataflow) processor
.getActivityList().get(0)).getNestedDataflow();
Collection<Processor> nested_processors = getProcessorsWithActivityOutputPort(
nestedWorkflow, outputPort);
if (!nested_processors.isEmpty())
processors.addAll(nested_processors);
}
// Check all processor's activities (even if the processor contained
// a nested workflow,
// as its dataflow activity still contains input and output ports)
for (Activity<?> activity : processor.getActivityList()) {
if (activity.getOutputPorts().contains(outputPort)) {
processors.add(processor);
}
}
}
return processors;
}
/**
* Get the TokenProcessingEntity (Processor, Merge or Dataflow) from the
* workflow that contains the given EventForwardingOutputPort. This can be
* an output port of a Processor or a Merge or an input port of a Dataflow
* that has an internal EventForwardingOutputPort attached to it.
*
* @param port
* @param workflow
* @return
*/
public static TokenProcessingEntity getTokenProcessingEntityWithEventForwardingOutputPort(
EventForwardingOutputPort port, Dataflow workflow) {
// First check the workflow's inputs
for (DataflowInputPort input : workflow.getInputPorts()) {
if (input.getInternalOutputPort().equals(port)) {
return workflow;
}
}
// Check workflow's merges
List<? extends Merge> merges = workflow.getMerges();
for (Merge merge : merges) {
if (merge.getOutputPort().equals(port)) {
return merge;
}
}
// Check workflow's processors
List<? extends Processor> processors = workflow.getProcessors();
for (Processor processor : processors) {
for (OutputPort output : processor.getOutputPorts()) {
if (output.equals(port)) {
return processor;
}
}
// If processor contains a nested workflow - descend into it
if (containsNestedWorkflow(processor)) {
Dataflow nestedWorkflow = ((NestedDataflow) processor
.getActivityList().get(0)).getNestedDataflow();
TokenProcessingEntity entity = getTokenProcessingEntityWithEventForwardingOutputPort(
port, nestedWorkflow);
if (entity != null) {
return entity;
}
}
}
return null;
}
/**
* Get the TokenProcessingEntity (Processor, Merge or Dataflow) from the
* workflow that contains the given target EventHandlingInputPort. This can
* be an input port of a Processor or a Merge or an output port of a
* Dataflow that has an internal EventHandlingInputPort attached to it.
*
* @param port
* @param workflow
* @return
*/
public static TokenProcessingEntity getTokenProcessingEntityWithEventHandlingInputPort(
EventHandlingInputPort port, Dataflow workflow) {
// First check the workflow's outputs
for (DataflowOutputPort output : workflow.getOutputPorts()) {
if (output.getInternalInputPort().equals(port)) {
return workflow;
}
}
// Check workflow's merges
List<? extends Merge> merges = workflow.getMerges();
for (Merge merge : merges) {
for (EventHandlingInputPort input : merge.getInputPorts()) {
if (input.equals(port)) {
return merge;
}
}
}
// Check workflow's processors
List<? extends Processor> processors = workflow.getProcessors();
for (Processor processor : processors) {
for (EventHandlingInputPort output : processor.getInputPorts()) {
if (output.equals(port)) {
return processor;
}
}
// If processor contains a nested workflow - descend into it
if (containsNestedWorkflow(processor)) {
Dataflow nestedWorkflow = ((NestedDataflow) processor
.getActivityList().get(0)).getNestedDataflow();
TokenProcessingEntity entity = getTokenProcessingEntityWithEventHandlingInputPort(
port, nestedWorkflow);
if (entity != null) {
return entity;
}
}
}
return null;
}
/**
* Returns true if processor contains a nested workflow.
*/
public static boolean containsNestedWorkflow(Processor processor) {
return ((!processor.getActivityList().isEmpty()) && processor
.getActivityList().get(0) instanceof NestedDataflow);
}
/**
* Find the first processor that contains an activity that has the given
* activity input port. See #get
*
* @param dataflow
* @param targetPort
* @return
*/
public static Processor getFirstProcessorWithActivityInputPort(
Dataflow dataflow, ActivityInputPort targetPort) {
Collection<Processor> processorsWithActivityPort = getProcessorsWithActivityInputPort(
dataflow, targetPort);
for (Processor processor : processorsWithActivityPort) {
return processor;
}
return null;
}
public static Processor getFirstProcessorWithActivityOutputPort(
Dataflow dataflow, ActivityOutputPort targetPort) {
Collection<Processor> processorsWithActivityPort = getProcessorsWithActivityOutputPort(
dataflow, targetPort);
for (Processor processor : processorsWithActivityPort) {
return processor;
}
return null;
}
/**
* Find a unique processor name for the supplied Dataflow, based upon the
* preferred name. If needed, an underscore and a numeric suffix is added to
* the preferred name, and incremented until it is unique, starting from 2.
* (The original being 'number 1')
* <p>
* Note that this method checks the uniqueness against the names of all
* {@link NamedWorkflowEntity}s, including {@link Merge}s.
* <p>
* Although not strictly needed by Taverna, for added user friendliness the
* case of the existing port names are ignored when checking for uniqueness.
*
* @param preferredName
* the preferred name for the Processor
* @param dataflow
* the dataflow for which the Processor name needs to be unique
* @return A unique processor name
*/
public static String uniqueProcessorName(String preferredName,
Dataflow dataflow) {
Set<String> existingNames = new HashSet<String>();
for (NamedWorkflowEntity entity : dataflow
.getEntities(NamedWorkflowEntity.class)) {
existingNames.add(entity.getLocalName().toLowerCase());
}
return uniqueObjectName(preferredName, existingNames);
}
/**
* Checks that the name does not have any characters that are invalid for a
* Taverna name.
*
* The name must contain only the chars[A-Za-z_0-9].
*
* @param name
* the original name
* @return the sanitised name
*/
public static String sanitiseName(String name) {
String result = name;
if (Pattern.matches("\\w++", name) == false) {
result = "";
for (char c : name.toCharArray()) {
if (Character.isLetterOrDigit(c) || c == '_') {
result += c;
} else {
result += "_";
}
}
}
return result;
}
public static String uniqueObjectName(String preferredName, Set<String> existingNames) {
String uniqueName = preferredName;
long suffix = 2;
while (existingNames.contains(uniqueName.toLowerCase())) {
uniqueName = preferredName + "_" + suffix++;
}
return uniqueName;
}
/**
* Add the identification of a Dataflow into its identification annotation chain (if necessary)
*
* @return Whether an identification needed to be added
*/
public static boolean addDataflowIdentification(Dataflow dataflow, String internalId, Edits edits) {
boolean added = false;
IdentificationAssertion ia = (IdentificationAssertion) (AnnotationTools.getAnnotation(dataflow, IdentificationAssertion.class));
if ((ia == null) || !ia.getIdentification().equals(internalId)) {
IdentificationAssertion newIa = new IdentificationAssertion();
newIa.setIdentification(internalId);
try {
AnnotationTools.addAnnotation(dataflow, newIa, edits).doEdit();
} catch (EditException e) {
added = false;
}
}
return added;
}
/**
* Return a path of processors where the last element is this processor
* and previous ones are nested processors that contain this one all the
* way to the top but excluding the top level workflow as this is only a
* list of processors.
*/
public static List<Processor> getNestedPathForProcessor(
Processor processor, Dataflow dataflow) {
for (Processor proc : dataflow.getProcessors()){
if (proc == processor){ // found it
List<Processor> list = new ArrayList<Processor>();
list.add(processor);
return list;
}
else if (Tools.containsNestedWorkflow(proc)){ // check inside this nested processor
List<Processor> nestedList = getNestedPathForProcessor(processor, ((NestedDataflow)proc.getActivityList().get(0)).getNestedDataflow());
if (nestedList == null){ // processor not found in this nested workflow
continue;
}
nestedList.add(0, proc); // add this nested processor to the list
return nestedList;
}
}
return null;
}
}
| workflowmodel-api/src/main/java/net/sf/taverna/t2/workflowmodel/utils/Tools.java | /*******************************************************************************
* Copyright (C) 2007 The University of Manchester
*
* Modifications to the initial code base are copyright of their
* respective authors, or their employers as appropriate.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
******************************************************************************/
package net.sf.taverna.t2.workflowmodel.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import net.sf.taverna.t2.annotation.annotationbeans.IdentificationAssertion;
import net.sf.taverna.t2.workflowmodel.CompoundEdit;
import net.sf.taverna.t2.workflowmodel.Condition;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workflowmodel.DataflowInputPort;
import net.sf.taverna.t2.workflowmodel.DataflowOutputPort;
import net.sf.taverna.t2.workflowmodel.Datalink;
import net.sf.taverna.t2.workflowmodel.Edit;
import net.sf.taverna.t2.workflowmodel.EditException;
import net.sf.taverna.t2.workflowmodel.Edits;
import net.sf.taverna.t2.workflowmodel.EventForwardingOutputPort;
import net.sf.taverna.t2.workflowmodel.EventHandlingInputPort;
import net.sf.taverna.t2.workflowmodel.InputPort;
import net.sf.taverna.t2.workflowmodel.Merge;
import net.sf.taverna.t2.workflowmodel.MergeInputPort;
import net.sf.taverna.t2.workflowmodel.MergeOutputPort;
import net.sf.taverna.t2.workflowmodel.NamedWorkflowEntity;
import net.sf.taverna.t2.workflowmodel.OutputPort;
import net.sf.taverna.t2.workflowmodel.Port;
import net.sf.taverna.t2.workflowmodel.Processor;
import net.sf.taverna.t2.workflowmodel.ProcessorInputPort;
import net.sf.taverna.t2.workflowmodel.ProcessorOutputPort;
import net.sf.taverna.t2.workflowmodel.TokenProcessingEntity;
import net.sf.taverna.t2.workflowmodel.processor.activity.Activity;
import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityConfigurationException;
import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityInputPort;
import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityOutputPort;
import net.sf.taverna.t2.workflowmodel.processor.activity.DisabledActivity;
import net.sf.taverna.t2.workflowmodel.processor.activity.NestedDataflow;
/**
* Various workflow model tools that can be helpful when constructing a
* dataflow.
* <p>
* Not to be confused with the @deprecated
* {@link net.sf.taverna.t2.workflowmodel.impl.Tools}
*
* @author David Withers
* @author Stian Soiland-Reyes
*
*/
public class Tools {
private static Logger logger = Logger.getLogger(Tools.class);
// private static Edits edits = new EditsImpl();
/**
* Find (and possibly create) an EventHandlingInputPort.
* <p>
* If the given inputPort is an instance of {@link EventHandlingInputPort},
* it is returned directly. If it is an ActivityInputPort - the owning
* processors (found by searching the dataflow) will be searced for a mapped
* input port. If this cannot be found, one will be created and mapped. The
* edits for this will be added to the editList and needs to be executed by
* the caller.
*
* @see #findEventHandlingOutputPort(List, Dataflow, OutputPort)
* @param editList
* List of {@link Edit}s to append any required edits (yet to be
* performed) to
* @param dataflow
* Dataflow containing the processors
* @param inputPort
* An EventHandlingInputPort or ActivityInputPort
* @return The found or created EventHandlingInputPort
*/
@SuppressWarnings("unchecked")
protected static EventHandlingInputPort findEventHandlingInputPort(
List<Edit<?>> editList, Dataflow dataflow, InputPort inputPort, Edits edits) {
if (inputPort instanceof EventHandlingInputPort) {
return (EventHandlingInputPort) inputPort;
} else if (!(inputPort instanceof ActivityInputPort)) {
throw new IllegalArgumentException("Unknown input port type for "
+ inputPort);
}
ActivityInputPort activityInput = (ActivityInputPort) inputPort;
Collection<Processor> processors = Tools
.getProcessorsWithActivityInputPort(dataflow, activityInput);
if (processors.isEmpty()) {
throw new IllegalArgumentException("Can't find ActivityInputPort "
+ activityInput.getName() + " in workflow " + dataflow);
}
// FIXME: Assumes only one matching processor
Processor processor = processors.iterator().next();
Activity activity = null;
for (Activity checkActivity : processor.getActivityList()) {
if (checkActivity.getInputPorts().contains(activityInput)) {
activity = checkActivity;
break;
}
}
if (activity == null) {
throw new IllegalArgumentException("Can't find activity for port "
+ activityInput.getName() + "within processor " + processor);
}
ProcessorInputPort input = Tools.getProcessorInputPort(processor,
activity, activityInput);
if (input != null) {
return input;
}
// port doesn't exist so create a processor port and map it
String processorPortName = uniquePortName(activityInput.getName(),
processor.getInputPorts());
ProcessorInputPort processorInputPort = edits.createProcessorInputPort(
processor, processorPortName, activityInput.getDepth());
editList.add(edits.getAddProcessorInputPortEdit(processor,
processorInputPort));
editList.add(edits.getAddActivityInputPortMappingEdit(activity,
processorPortName, activityInput.getName()));
return processorInputPort;
}
/**
* Find (and possibly create) an EventForwardingOutputPort.
* <p>
* If the given outputPort is an instance of
* {@link EventForwardingOutputPort}, it is returned directly. If it is an
* ActivityOutputPort - the owning processors (found by searching the
* dataflow) will be searced for a mapped output port. If this cannot be
* found, one will be created and mapped. The edits for this will be added
* to the editList and needs to be executed by the caller.
*
* @see #findEventHandlingInputPort(List, Dataflow, InputPort)
* @param editList
* List of {@link Edit}s to append any required edits (yet to be
* performed) to
* @param dataflow
* Dataflow containing the processors
* @param outputPort
* An EventForwardingOutputPort or ActivityOutputPort
* @return The found or created EventForwardingOutputPort
*/
@SuppressWarnings("unchecked")
protected static EventForwardingOutputPort findEventHandlingOutputPort(
List<Edit<?>> editList, Dataflow dataflow, OutputPort outputPort, Edits edits) {
if (outputPort instanceof EventForwardingOutputPort) {
return (EventForwardingOutputPort) outputPort;
} else if (!(outputPort instanceof ActivityOutputPort)) {
throw new IllegalArgumentException("Unknown output port type for "
+ outputPort);
}
ActivityOutputPort activityOutput = (ActivityOutputPort) outputPort;
Collection<Processor> processors = Tools
.getProcessorsWithActivityOutputPort(dataflow, activityOutput);
if (processors.isEmpty()) {
throw new IllegalArgumentException("Can't find ActivityOutputPort "
+ activityOutput.getName() + " in workflow " + dataflow);
}
// FIXME: Assumes only one matching processor
Processor processor = processors.iterator().next();
Activity activity = null;
for (Activity checkActivity : processor.getActivityList()) {
if (checkActivity.getOutputPorts().contains(activityOutput)) {
activity = checkActivity;
break;
}
}
if (activity == null) {
throw new IllegalArgumentException("Can't find activity for port "
+ activityOutput.getName() + "within processor "
+ processor);
}
ProcessorOutputPort processorOutputPort = Tools.getProcessorOutputPort(
processor, activity, activityOutput);
if (processorOutputPort != null) {
return processorOutputPort;
}
// port doesn't exist so create a processor port and map it
String processorPortName = uniquePortName(activityOutput.getName(),
processor.getOutputPorts());
processorOutputPort = edits.createProcessorOutputPort(processor,
processorPortName, activityOutput.getDepth(), activityOutput
.getGranularDepth());
editList.add(edits.getAddProcessorOutputPortEdit(processor,
processorOutputPort));
editList.add(edits.getAddActivityOutputPortMappingEdit(activity,
processorPortName, activityOutput.getName()));
return processorOutputPort;
}
/**
* Creates an Edit that creates a Datalink between a source and sink port
* and connects the Datalink.
*
* If the sink port already has a Datalink connected this method checks if a
* new Merge is required and creates and connects the required Datalinks.
*
* @param dataflow
* the Dataflow to add the Datalink to
* @param source
* the source of the Datalink
* @param sink
* the source of the Datalink
* @return an Edit that creates a Datalink between a source and sink port
* and connects the Datalink
*/
public static Edit<?> getCreateAndConnectDatalinkEdit(Dataflow dataflow,
EventForwardingOutputPort source, EventHandlingInputPort sink, Edits edits) {
Edit<?> edit = null;
Datalink incomingLink = sink.getIncomingLink();
if (incomingLink == null) {
Datalink datalink = edits.createDatalink(source, sink);
edit = edits.getConnectDatalinkEdit(datalink);
} else {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
Merge merge = null;
int counter = 0; // counter for merge input port names
if (incomingLink.getSource() instanceof MergeOutputPort) {
merge = ((MergeOutputPort) incomingLink.getSource()).getMerge();
} else {
merge = edits.createMerge(dataflow);
editList.add(edits.getAddMergeEdit(dataflow, merge));
editList.add(edits.getDisconnectDatalinkEdit(incomingLink));
MergeInputPort mergeInputPort = edits.createMergeInputPort(
merge, getUniqueMergeInputPortName(merge, incomingLink
.getSource().getName()
+ "To" + merge.getLocalName() + "_input",
counter++), incomingLink.getSink().getDepth());
editList.add(edits.getAddMergeInputPortEdit(merge,
mergeInputPort));
Datalink datalink = edits.createDatalink(incomingLink
.getSource(), mergeInputPort);
editList.add(edits.getConnectDatalinkEdit(datalink));
datalink = edits.createDatalink(merge.getOutputPort(),
incomingLink.getSink());
editList.add(edits.getConnectDatalinkEdit(datalink));
}
MergeInputPort mergeInputPort = edits.createMergeInputPort(merge,
getUniqueMergeInputPortName(merge, source.getName() + "To"
+ merge.getLocalName() + "_input", counter), sink
.getDepth());
editList.add(edits.getAddMergeInputPortEdit(merge, mergeInputPort));
Datalink datalink = edits.createDatalink(source, mergeInputPort);
editList.add(edits.getConnectDatalinkEdit(datalink));
edit = new CompoundEdit(editList);
}
return edit;
}
/**
* Get an {@link Edit} that will link the given output port to the given
* input port.
* <p>
* The output port can be an {@link EventForwardingOutputPort} (such as an
* {@link ProcessorOutputPort}, or an {@link ActivityOutputPort}. The input
* port can be an {@link EventHandlingInputPort} (such as an
* {@link ProcessorInputPort}, or an {@link ActivityInputPort}.
* <p>
* If an input and/or output port is an activity port, processors in the
* given dataflow will be searched for matching mappings, create the
* processor port and mapping if needed, before constructing the edits for
* adding the datalink.
*
* @param dataflow
* Dataflow (indirectly) containing ports
* @param outputPort
* An {@link EventForwardingOutputPort} or an
* {@link ActivityOutputPort}
* @param inputPort
* An {@link EventHandlingInputPort} or an
* {@link ActivityInputPort}
* @return A compound edit for creating and connecting the datalink and any
* neccessary processor ports and mappings
*/
public static Edit<?> getCreateAndConnectDatalinkEdit(Dataflow dataflow,
OutputPort outputPort, InputPort inputPort, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
EventHandlingInputPort sink = findEventHandlingInputPort(editList,
dataflow, inputPort, edits);
EventForwardingOutputPort source = findEventHandlingOutputPort(
editList, dataflow, outputPort, edits);
editList.add(getCreateAndConnectDatalinkEdit(dataflow, source, sink, edits));
return new CompoundEdit(editList);
}
/**
* Find a unique port name given a list of existing ports.
* <p>
* If needed, the returned port name will be prefixed with an underscore and a number,
* starting from 2. (The original being 'number 1')
* <p>
* Although not strictly needed by Taverna, for added user friendliness the
* case of the existing port names are ignored when checking for uniqueness.
*
* @see #uniqueProcessorName(String, Dataflow)
*
* @param suggestedPortName
* Port name suggested for new port
* @param existingPorts
* Collection of existing {@link Port}s
* @return A port name unique for the given collection of port
*/
public static String uniquePortName(String suggestedPortName,
Collection<? extends Port> existingPorts) {
// Make sure we have a unique port name
Set<String> existingNames = new HashSet<String>();
for (Port existingPort : existingPorts) {
existingNames.add(existingPort.getName().toLowerCase());
}
String candidateName = suggestedPortName;
long counter = 2;
while (existingNames.contains(candidateName.toLowerCase())) {
candidateName = suggestedPortName + "_" + counter++;
}
return candidateName;
}
public static Edit<?> getMoveDatalinkSinkEdit(Dataflow dataflow,
Datalink datalink, EventHandlingInputPort sink, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
editList.add(edits.getDisconnectDatalinkEdit(datalink));
if (datalink.getSink() instanceof ProcessorInputPort) {
editList
.add(getRemoveProcessorInputPortEdit((ProcessorInputPort) datalink
.getSink(), edits));
}
editList.add(getCreateAndConnectDatalinkEdit(dataflow, datalink
.getSource(), sink, edits));
return new CompoundEdit(editList);
}
public static Edit<?> getDisconnectDatalinkAndRemovePortsEdit(
Datalink datalink, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
editList.add(edits.getDisconnectDatalinkEdit(datalink));
if (datalink.getSource() instanceof ProcessorOutputPort) {
ProcessorOutputPort processorOutputPort = (ProcessorOutputPort) datalink
.getSource();
if (processorOutputPort.getOutgoingLinks().size() == 1) {
editList
.add(getRemoveProcessorOutputPortEdit(processorOutputPort, edits));
}
}
if (datalink.getSink() instanceof ProcessorInputPort) {
editList
.add(getRemoveProcessorInputPortEdit((ProcessorInputPort) datalink
.getSink(), edits));
}
return new CompoundEdit(editList);
}
public static Edit<?> getRemoveProcessorOutputPortEdit(
ProcessorOutputPort port, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
Processor processor = port.getProcessor();
editList.add(edits.getRemoveProcessorOutputPortEdit(
port.getProcessor(), port));
for (Activity<?> activity : processor.getActivityList()) {
editList.add(edits.getRemoveActivityOutputPortMappingEdit(activity,
port.getName()));
}
return new CompoundEdit(editList);
}
public static Edit<?> getRemoveProcessorInputPortEdit(
ProcessorInputPort port, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
Processor processor = port.getProcessor();
editList.add(edits.getRemoveProcessorInputPortEdit(port.getProcessor(),
port));
for (Activity<?> activity : processor.getActivityList()) {
editList.add(edits.getRemoveActivityInputPortMappingEdit(activity,
port.getName()));
}
return new CompoundEdit(editList);
}
public static Edit<?> getEnableDisabledActivityEdit(Processor processor, DisabledActivity disabledActivity, Edits edits) {
List<Edit<?>> editList = new ArrayList<Edit<?>>();
Activity<?> brokenActivity = disabledActivity.getActivity();
try {
Activity ra = brokenActivity.getClass().newInstance();
Object lastConfig = disabledActivity.getLastWorkingConfiguration();
if (lastConfig == null) {
lastConfig = disabledActivity.getActivityConfiguration();
}
ra.configure(lastConfig);
Map<String, String> portMapping = ra.getInputPortMapping();
Set<String> portNames = new HashSet<String>();
portNames.addAll(portMapping.keySet());
for (String portName : portNames) {
editList.add(edits.getRemoveActivityInputPortMappingEdit(ra, portName));
}
portMapping = ra.getOutputPortMapping();
portNames.clear();
portNames.addAll(portMapping.keySet());
for (String portName : portNames) {
editList.add(edits.getRemoveActivityOutputPortMappingEdit(ra, portName));
}
portMapping = disabledActivity.getInputPortMapping();
for (String portName : portMapping.keySet()) {
editList.add(edits.getAddActivityInputPortMappingEdit(ra, portName, portMapping.get(portName)));
}
portMapping = disabledActivity.getOutputPortMapping();
for (String portName : portMapping.keySet()) {
editList.add(edits.getAddActivityOutputPortMappingEdit(ra, portName, portMapping.get(portName)));
}
editList.add(edits.getRemoveActivityEdit(processor, disabledActivity));
editList.add(edits.getAddActivityEdit(processor, ra));
}
catch (ActivityConfigurationException ex) {
logger.error("Configuration exception ", ex);
return null;
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
}
return new CompoundEdit(editList);
}
public static ProcessorInputPort getProcessorInputPort(Processor processor,
Activity<?> activity, InputPort activityInputPort) {
ProcessorInputPort result = null;
for (Entry<String, String> mapEntry : activity.getInputPortMapping()
.entrySet()) {
if (mapEntry.getValue().equals(activityInputPort.getName())) {
for (ProcessorInputPort processorInputPort : processor
.getInputPorts()) {
if (processorInputPort.getName().equals(mapEntry.getKey())) {
result = processorInputPort;
break;
}
}
break;
}
}
return result;
}
public static ProcessorOutputPort getProcessorOutputPort(
Processor processor, Activity<?> activity,
OutputPort activityOutputPort) {
ProcessorOutputPort result = null;
for (Entry<String, String> mapEntry : activity.getOutputPortMapping()
.entrySet()) {
if (mapEntry.getValue().equals(activityOutputPort.getName())) {
for (ProcessorOutputPort processorOutputPort : processor
.getOutputPorts()) {
if (processorOutputPort.getName().equals(mapEntry.getKey())) {
result = processorOutputPort;
break;
}
}
break;
}
}
return result;
}
public static ActivityInputPort getActivityInputPort(Activity<?> activity,
String portName) {
ActivityInputPort activityInputPort = null;
for (ActivityInputPort inputPort : activity.getInputPorts()) {
if (inputPort.getName().equals(portName)) {
activityInputPort = inputPort;
break;
}
}
return activityInputPort;
}
public static OutputPort getActivityOutputPort(Activity<?> activity,
String portName) {
OutputPort activityOutputPort = null;
for (OutputPort outputPort : activity.getOutputPorts()) {
if (outputPort.getName().equals(portName)) {
activityOutputPort = outputPort;
break;
}
}
return activityOutputPort;
}
public static String getUniqueMergeInputPortName(Merge merge, String name,
int count) {
String uniqueName = name + count;
for (MergeInputPort mergeInputPort : merge.getInputPorts()) {
if (mergeInputPort.getName().equals(uniqueName)) {
return getUniqueMergeInputPortName(merge, name, ++count);
}
}
return uniqueName;
}
public static Collection<Processor> getProcessorsWithActivity(
Dataflow dataflow, Activity<?> activity) {
Set<Processor> processors = new HashSet<Processor>();
for (Processor processor : dataflow.getProcessors()) {
if (processor.getActivityList().contains(activity)) {
processors.add(processor);
}
}
return processors;
}
public static Collection<Processor> getProcessorsWithActivityInputPort(
Dataflow dataflow, ActivityInputPort inputPort) {
Set<Processor> processors = new HashSet<Processor>();
for (Processor processor : dataflow.getProcessors()) {
// Does it contain a nested workflow?
if (containsNestedWorkflow(processor)) {
// Get the nested workflow and check all its nested processors
Dataflow nestedWorkflow = ((NestedDataflow) processor
.getActivityList().get(0)).getNestedDataflow();
Collection<Processor> nested_processors = getProcessorsWithActivityInputPort(
nestedWorkflow, inputPort);
if (!nested_processors.isEmpty())
processors.addAll(nested_processors);
}
// Check all processor's activities (even if the processor contained
// a nested workflow,
// as its dataflow activity still contains input and output ports)
for (Activity<?> activity : processor.getActivityList()) {
if (activity.getInputPorts().contains(inputPort)) {
processors.add(processor);
}
}
}
return processors;
}
public static Collection<Processor> getProcessorsWithActivityOutputPort(
Dataflow dataflow, OutputPort outputPort) {
Set<Processor> processors = new HashSet<Processor>();
for (Processor processor : dataflow.getProcessors()) {
// Does it contain a nested workflow?
if (containsNestedWorkflow(processor)) {
// Get the nested workflow and check all its nested processors
Dataflow nestedWorkflow = ((NestedDataflow) processor
.getActivityList().get(0)).getNestedDataflow();
Collection<Processor> nested_processors = getProcessorsWithActivityOutputPort(
nestedWorkflow, outputPort);
if (!nested_processors.isEmpty())
processors.addAll(nested_processors);
}
// Check all processor's activities (even if the processor contained
// a nested workflow,
// as its dataflow activity still contains input and output ports)
for (Activity<?> activity : processor.getActivityList()) {
if (activity.getOutputPorts().contains(outputPort)) {
processors.add(processor);
}
}
}
return processors;
}
/**
* Get the TokenProcessingEntity (Processor, Merge or Dataflow) from the
* workflow that contains the given EventForwardingOutputPort. This can be
* an output port of a Processor or a Merge or an input port of a Dataflow
* that has an internal EventForwardingOutputPort attached to it.
*
* @param port
* @param workflow
* @return
*/
public static TokenProcessingEntity getTokenProcessingEntityWithEventForwardingOutputPort(
EventForwardingOutputPort port, Dataflow workflow) {
// First check the workflow's inputs
for (DataflowInputPort input : workflow.getInputPorts()) {
if (input.getInternalOutputPort().equals(port)) {
return workflow;
}
}
// Check workflow's merges
List<? extends Merge> merges = workflow.getMerges();
for (Merge merge : merges) {
if (merge.getOutputPort().equals(port)) {
return merge;
}
}
// Check workflow's processors
List<? extends Processor> processors = workflow.getProcessors();
for (Processor processor : processors) {
for (OutputPort output : processor.getOutputPorts()) {
if (output.equals(port)) {
return processor;
}
}
// If processor contains a nested workflow - descend into it
if (containsNestedWorkflow(processor)) {
Dataflow nestedWorkflow = ((NestedDataflow) processor
.getActivityList().get(0)).getNestedDataflow();
TokenProcessingEntity entity = getTokenProcessingEntityWithEventForwardingOutputPort(
port, nestedWorkflow);
if (entity != null) {
return entity;
}
}
}
return null;
}
/**
* Get the TokenProcessingEntity (Processor, Merge or Dataflow) from the
* workflow that contains the given target EventHandlingInputPort. This can
* be an input port of a Processor or a Merge or an output port of a
* Dataflow that has an internal EventHandlingInputPort attached to it.
*
* @param port
* @param workflow
* @return
*/
public static TokenProcessingEntity getTokenProcessingEntityWithEventHandlingInputPort(
EventHandlingInputPort port, Dataflow workflow) {
// First check the workflow's outputs
for (DataflowOutputPort output : workflow.getOutputPorts()) {
if (output.getInternalInputPort().equals(port)) {
return workflow;
}
}
// Check workflow's merges
List<? extends Merge> merges = workflow.getMerges();
for (Merge merge : merges) {
for (EventHandlingInputPort input : merge.getInputPorts()) {
if (input.equals(port)) {
return merge;
}
}
}
// Check workflow's processors
List<? extends Processor> processors = workflow.getProcessors();
for (Processor processor : processors) {
for (EventHandlingInputPort output : processor.getInputPorts()) {
if (output.equals(port)) {
return processor;
}
}
// If processor contains a nested workflow - descend into it
if (containsNestedWorkflow(processor)) {
Dataflow nestedWorkflow = ((NestedDataflow) processor
.getActivityList().get(0)).getNestedDataflow();
TokenProcessingEntity entity = getTokenProcessingEntityWithEventHandlingInputPort(
port, nestedWorkflow);
if (entity != null) {
return entity;
}
}
}
return null;
}
/**
* Returns true if processor contains a nested workflow.
*/
public static boolean containsNestedWorkflow(Processor processor) {
return ((!processor.getActivityList().isEmpty()) && processor
.getActivityList().get(0) instanceof NestedDataflow);
}
/**
* Find processors that a given processor can connect to downstream.
* <p>
* This is calculated as all processors in the dataflow, except the
* processor itself, and any processor <em>upstream</em>, following both
* data links and conditional links.
*
* @see #possibleUpStreamProcessors(Dataflow, Processor)
* @see #splitProcessors(Collection, Processor)
*
* @param dataflow
* Dataflow from where to find processors
* @param processor
* Processor which is to be connected
* @return A set of possible downstream processors
*/
public static Set<Processor> possibleDownStreamProcessors(
Dataflow dataflow, Processor processor) {
ProcessorSplit splitProcessors = splitProcessors(dataflow
.getProcessors(), processor);
Set<Processor> possibles = new HashSet<Processor>(splitProcessors
.getUnconnected());
possibles.addAll(splitProcessors.getDownStream());
return possibles;
}
/**
* Find processors that a given processor can connect to upstream.
* <p>
* This is calculated as all processors in the dataflow, except the
* processor itself, and any processor <em>downstream</em>, following both
* data links and conditional links.
*
* @see #possibleDownStreamProcessors(Dataflow, Processor)
* @see #splitProcessors(Collection, Processor)
*
* @param dataflow
* Dataflow from where to find processors
* @param processor
* Processor which is to be connected
* @return A set of possible downstream processors
*/
public static Set<Processor> possibleUpStreamProcessors(Dataflow dataflow,
Processor firstProcessor) {
ProcessorSplit splitProcessors = splitProcessors(dataflow
.getProcessors(), firstProcessor);
Set<Processor> possibles = new HashSet<Processor>(splitProcessors
.getUnconnected());
possibles.addAll(splitProcessors.getUpStream());
return possibles;
}
/**
*
* @param processors
* @param splitPoint
* @return
*/
public static ProcessorSplit splitProcessors(
Collection<? extends Processor> processors, TokenProcessingEntity splitPoint) {
Set<Processor> upStream = new HashSet<Processor>();
Set<Processor> downStream = new HashSet<Processor>();
Set<TokenProcessingEntity> queue = new HashSet<TokenProcessingEntity>();
queue.add(splitPoint);
// First let's go upstream
while (!queue.isEmpty()) {
TokenProcessingEntity investigate = queue.iterator().next();
queue.remove(investigate);
if (investigate instanceof Processor) {
Processor processor = (Processor) investigate;
List<? extends Condition> preConditions = processor
.getPreconditionList();
for (Condition condition : preConditions) {
Processor upstreamProc = condition.getControl();
if (!upStream.contains(upstreamProc)) {
upStream.add(upstreamProc);
queue.add(upstreamProc);
}
}
}
for (EventHandlingInputPort inputPort : investigate.getInputPorts()) {
Datalink incomingLink = inputPort.getIncomingLink();
if (incomingLink == null) {
continue;
}
EventForwardingOutputPort source = incomingLink.getSource();
if (source instanceof ProcessorOutputPort) {
Processor upstreamProc = ((ProcessorOutputPort) source)
.getProcessor();
if (!upStream.contains(upstreamProc)) {
upStream.add(upstreamProc);
queue.add(upstreamProc);
}
} else if (source instanceof MergeOutputPort) {
Merge merge = ((MergeOutputPort) source).getMerge();
queue.add(merge);
// The merge it self doesn't count as a processor
} else {
// Ignore
}
}
}
// Then downstream
queue.add(splitPoint);
while (!queue.isEmpty()) {
TokenProcessingEntity investigate = queue.iterator().next();
queue.remove(investigate);
if (investigate instanceof Processor) {
Processor processor = (Processor) investigate;
List<? extends Condition> controlledConditions = processor
.getControlledPreconditionList();
for (Condition condition : controlledConditions) {
Processor downstreamProc = condition.getTarget();
if (!downStream.contains(downstreamProc)) {
downStream.add(downstreamProc);
queue.add(downstreamProc);
}
}
}
for (EventForwardingOutputPort outputPort : investigate
.getOutputPorts()) {
for (Datalink datalink : outputPort.getOutgoingLinks()) {
EventHandlingInputPort sink = datalink.getSink();
if (sink instanceof ProcessorInputPort) {
Processor downstreamProcc = ((ProcessorInputPort) sink)
.getProcessor();
if (!downStream.contains(downstreamProcc)) {
downStream.add(downstreamProcc);
queue.add(downstreamProcc);
}
} else if (sink instanceof MergeInputPort) {
Merge merge = ((MergeInputPort) sink).getMerge();
queue.add(merge);
// The merge it self doesn't count as a processor
} else {
// Ignore dataflow ports
}
}
}
}
Set<Processor> undecided = new HashSet<Processor>(processors);
undecided.remove(splitPoint);
undecided.removeAll(upStream);
undecided.removeAll(downStream);
return new ProcessorSplit(splitPoint, upStream, downStream, undecided);
}
/**
* Find the first processor that contains an activity that has the given
* activity input port. See #get
*
* @param dataflow
* @param targetPort
* @return
*/
public static Processor getFirstProcessorWithActivityInputPort(
Dataflow dataflow, ActivityInputPort targetPort) {
Collection<Processor> processorsWithActivityPort = getProcessorsWithActivityInputPort(
dataflow, targetPort);
for (Processor processor : processorsWithActivityPort) {
return processor;
}
return null;
}
public static Processor getFirstProcessorWithActivityOutputPort(
Dataflow dataflow, ActivityOutputPort targetPort) {
Collection<Processor> processorsWithActivityPort = getProcessorsWithActivityOutputPort(
dataflow, targetPort);
for (Processor processor : processorsWithActivityPort) {
return processor;
}
return null;
}
/**
* Find a unique processor name for the supplied Dataflow, based upon the
* preferred name. If needed, an underscore and a numeric suffix is added to
* the preferred name, and incremented until it is unique, starting from 2.
* (The original being 'number 1')
* <p>
* Note that this method checks the uniqueness against the names of all
* {@link NamedWorkflowEntity}s, including {@link Merge}s.
* <p>
* Although not strictly needed by Taverna, for added user friendliness the
* case of the existing port names are ignored when checking for uniqueness.
*
* @param preferredName
* the preferred name for the Processor
* @param dataflow
* the dataflow for which the Processor name needs to be unique
* @return A unique processor name
*/
public static String uniqueProcessorName(String preferredName,
Dataflow dataflow) {
Set<String> existingNames = new HashSet<String>();
for (NamedWorkflowEntity entity : dataflow
.getEntities(NamedWorkflowEntity.class)) {
existingNames.add(entity.getLocalName().toLowerCase());
}
return uniqueObjectName(preferredName, existingNames);
}
/**
* Checks that the name does not have any characters that are invalid for a
* Taverna name.
*
* The name must contain only the chars[A-Za-z_0-9].
*
* @param name
* the original name
* @return the sanitised name
*/
public static String sanitiseName(String name) {
String result = name;
if (Pattern.matches("\\w++", name) == false) {
result = "";
for (char c : name.toCharArray()) {
if (Character.isLetterOrDigit(c) || c == '_') {
result += c;
} else {
result += "_";
}
}
}
return result;
}
public static String uniqueObjectName(String preferredName, Set<String> existingNames) {
String uniqueName = preferredName;
long suffix = 2;
while (existingNames.contains(uniqueName.toLowerCase())) {
uniqueName = preferredName + "_" + suffix++;
}
return uniqueName;
}
/**
* Add the identification of a Dataflow into its identification annotation chain (if necessary)
*
* @return Whether an identification needed to be added
*/
public static boolean addDataflowIdentification(Dataflow dataflow, String internalId, Edits edits) {
boolean added = false;
IdentificationAssertion ia = (IdentificationAssertion) (AnnotationTools.getAnnotation(dataflow, IdentificationAssertion.class));
if ((ia == null) || !ia.getIdentification().equals(internalId)) {
IdentificationAssertion newIa = new IdentificationAssertion();
newIa.setIdentification(internalId);
try {
AnnotationTools.addAnnotation(dataflow, newIa, edits).doEdit();
} catch (EditException e) {
added = false;
}
}
return added;
}
/**
* Result bean returned from
* {@link Tools#splitProcessors(Collection, Processor)}.
*
* @author Stian Soiland-Reyes
*
*/
public static class ProcessorSplit {
private final TokenProcessingEntity splitPoint;
private final Set<Processor> upStream;
private final Set<Processor> downStream;
private final Set<Processor> unconnected;
/**
* Processor that was used as a split point.
*
* @return Split point processor
*/
public TokenProcessingEntity getSplitPoint() {
return splitPoint;
}
/**
* Processors that are upstream from the split point.
*
* @return Upstream processors
*/
public Set<Processor> getUpStream() {
return upStream;
}
/**
* Processors that are downstream from the split point.
*
* @return Downstream processors
*/
public Set<Processor> getDownStream() {
return downStream;
}
/**
* Processors that are unconnected to the split point.
* <p>
* These are processors in the dataflow that are neither upstream,
* downstream or the split point itself.
* <p>
* Note that this does not imply a total graph separation, for instance
* processors in {@link #getUpStream()} might have some of these
* unconnected processors downstream, but not along the path to the
* {@link #getSplitPoint()}, or they could be upstream from any
* processor in {@link #getDownStream()}.
*
* @return Processors unconnected from the split point
*/
public Set<Processor> getUnconnected() {
return unconnected;
}
/**
* Construct a new processor split result.
*
* @param splitPoint
* Processor used as split point
* @param upStream
* Processors that are upstream from split point
* @param downStream
* Processors that are downstream from split point
* @param unconnected
* The rest of the processors, that are by definition
* unconnected to split point
*/
public ProcessorSplit(TokenProcessingEntity splitPoint, Set<Processor> upStream,
Set<Processor> downStream, Set<Processor> unconnected) {
this.splitPoint = splitPoint;
this.upStream = upStream;
this.downStream = downStream;
this.unconnected = unconnected;
}
}
/**
* Return a path of processors where the last element is this processor
* and previous ones are nested processors that contain this one all the
* way to the top but excluding the top level workflow as this is only a
* list of processors.
*/
public static List<Processor> getNestedPathForProcessor(
Processor processor, Dataflow dataflow) {
for (Processor proc : dataflow.getProcessors()){
if (proc == processor){ // found it
List<Processor> list = new ArrayList<Processor>();
list.add(processor);
return list;
}
else if (Tools.containsNestedWorkflow(proc)){ // check inside this nested processor
List<Processor> nestedList = getNestedPathForProcessor(processor, ((NestedDataflow)proc.getActivityList().get(0)).getNestedDataflow());
if (nestedList == null){ // processor not found in this nested workflow
continue;
}
nestedList.add(0, proc); // add this nested processor to the list
return nestedList;
}
}
return null;
}
}
| Moved splitProcessors, possibleDownStreamProcessors and
possibleupStreamProcessors to Scufl2Tools
git-svn-id: 7932981c62cbcd7a11cdd101fdc2d4466dded46a@15256 bf327186-88b3-11dd-a302-d386e5130c1c
| workflowmodel-api/src/main/java/net/sf/taverna/t2/workflowmodel/utils/Tools.java | Moved splitProcessors, possibleDownStreamProcessors and possibleupStreamProcessors to Scufl2Tools | <ide><path>orkflowmodel-api/src/main/java/net/sf/taverna/t2/workflowmodel/utils/Tools.java
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.Map.Entry;
<ide> import java.util.Set;
<del>import java.util.Map.Entry;
<ide> import java.util.regex.Pattern;
<del>
<del>import org.apache.log4j.Logger;
<ide>
<ide> import net.sf.taverna.t2.annotation.annotationbeans.IdentificationAssertion;
<ide> import net.sf.taverna.t2.workflowmodel.CompoundEdit;
<del>import net.sf.taverna.t2.workflowmodel.Condition;
<ide> import net.sf.taverna.t2.workflowmodel.Dataflow;
<ide> import net.sf.taverna.t2.workflowmodel.DataflowInputPort;
<ide> import net.sf.taverna.t2.workflowmodel.DataflowOutputPort;
<ide> import net.sf.taverna.t2.workflowmodel.processor.activity.DisabledActivity;
<ide> import net.sf.taverna.t2.workflowmodel.processor.activity.NestedDataflow;
<ide>
<add>import org.apache.log4j.Logger;
<add>
<ide> /**
<ide> * Various workflow model tools that can be helpful when constructing a
<ide> * dataflow.
<ide> return ((!processor.getActivityList().isEmpty()) && processor
<ide> .getActivityList().get(0) instanceof NestedDataflow);
<ide> }
<del>
<del> /**
<del> * Find processors that a given processor can connect to downstream.
<del> * <p>
<del> * This is calculated as all processors in the dataflow, except the
<del> * processor itself, and any processor <em>upstream</em>, following both
<del> * data links and conditional links.
<del> *
<del> * @see #possibleUpStreamProcessors(Dataflow, Processor)
<del> * @see #splitProcessors(Collection, Processor)
<del> *
<del> * @param dataflow
<del> * Dataflow from where to find processors
<del> * @param processor
<del> * Processor which is to be connected
<del> * @return A set of possible downstream processors
<del> */
<del> public static Set<Processor> possibleDownStreamProcessors(
<del> Dataflow dataflow, Processor processor) {
<del> ProcessorSplit splitProcessors = splitProcessors(dataflow
<del> .getProcessors(), processor);
<del> Set<Processor> possibles = new HashSet<Processor>(splitProcessors
<del> .getUnconnected());
<del> possibles.addAll(splitProcessors.getDownStream());
<del> return possibles;
<del> }
<del>
<del> /**
<del> * Find processors that a given processor can connect to upstream.
<del> * <p>
<del> * This is calculated as all processors in the dataflow, except the
<del> * processor itself, and any processor <em>downstream</em>, following both
<del> * data links and conditional links.
<del> *
<del> * @see #possibleDownStreamProcessors(Dataflow, Processor)
<del> * @see #splitProcessors(Collection, Processor)
<del> *
<del> * @param dataflow
<del> * Dataflow from where to find processors
<del> * @param processor
<del> * Processor which is to be connected
<del> * @return A set of possible downstream processors
<del> */
<del> public static Set<Processor> possibleUpStreamProcessors(Dataflow dataflow,
<del> Processor firstProcessor) {
<del> ProcessorSplit splitProcessors = splitProcessors(dataflow
<del> .getProcessors(), firstProcessor);
<del> Set<Processor> possibles = new HashSet<Processor>(splitProcessors
<del> .getUnconnected());
<del> possibles.addAll(splitProcessors.getUpStream());
<del> return possibles;
<del> }
<del>
<del> /**
<del> *
<del> * @param processors
<del> * @param splitPoint
<del> * @return
<del> */
<del> public static ProcessorSplit splitProcessors(
<del> Collection<? extends Processor> processors, TokenProcessingEntity splitPoint) {
<del> Set<Processor> upStream = new HashSet<Processor>();
<del> Set<Processor> downStream = new HashSet<Processor>();
<del> Set<TokenProcessingEntity> queue = new HashSet<TokenProcessingEntity>();
<del>
<del> queue.add(splitPoint);
<del>
<del> // First let's go upstream
<del> while (!queue.isEmpty()) {
<del> TokenProcessingEntity investigate = queue.iterator().next();
<del> queue.remove(investigate);
<del> if (investigate instanceof Processor) {
<del> Processor processor = (Processor) investigate;
<del> List<? extends Condition> preConditions = processor
<del> .getPreconditionList();
<del> for (Condition condition : preConditions) {
<del> Processor upstreamProc = condition.getControl();
<del> if (!upStream.contains(upstreamProc)) {
<del> upStream.add(upstreamProc);
<del> queue.add(upstreamProc);
<del> }
<del> }
<del> }
<del> for (EventHandlingInputPort inputPort : investigate.getInputPorts()) {
<del> Datalink incomingLink = inputPort.getIncomingLink();
<del> if (incomingLink == null) {
<del> continue;
<del> }
<del> EventForwardingOutputPort source = incomingLink.getSource();
<del> if (source instanceof ProcessorOutputPort) {
<del> Processor upstreamProc = ((ProcessorOutputPort) source)
<del> .getProcessor();
<del> if (!upStream.contains(upstreamProc)) {
<del> upStream.add(upstreamProc);
<del> queue.add(upstreamProc);
<del> }
<del> } else if (source instanceof MergeOutputPort) {
<del> Merge merge = ((MergeOutputPort) source).getMerge();
<del> queue.add(merge);
<del> // The merge it self doesn't count as a processor
<del> } else {
<del> // Ignore
<del> }
<del> }
<del> }
<del> // Then downstream
<del> queue.add(splitPoint);
<del> while (!queue.isEmpty()) {
<del> TokenProcessingEntity investigate = queue.iterator().next();
<del> queue.remove(investigate);
<del> if (investigate instanceof Processor) {
<del> Processor processor = (Processor) investigate;
<del> List<? extends Condition> controlledConditions = processor
<del> .getControlledPreconditionList();
<del> for (Condition condition : controlledConditions) {
<del> Processor downstreamProc = condition.getTarget();
<del> if (!downStream.contains(downstreamProc)) {
<del> downStream.add(downstreamProc);
<del> queue.add(downstreamProc);
<del> }
<del> }
<del> }
<del>
<del> for (EventForwardingOutputPort outputPort : investigate
<del> .getOutputPorts()) {
<del> for (Datalink datalink : outputPort.getOutgoingLinks()) {
<del> EventHandlingInputPort sink = datalink.getSink();
<del> if (sink instanceof ProcessorInputPort) {
<del> Processor downstreamProcc = ((ProcessorInputPort) sink)
<del> .getProcessor();
<del> if (!downStream.contains(downstreamProcc)) {
<del> downStream.add(downstreamProcc);
<del> queue.add(downstreamProcc);
<del> }
<del> } else if (sink instanceof MergeInputPort) {
<del> Merge merge = ((MergeInputPort) sink).getMerge();
<del> queue.add(merge);
<del> // The merge it self doesn't count as a processor
<del> } else {
<del> // Ignore dataflow ports
<del> }
<del> }
<del> }
<del> }
<del> Set<Processor> undecided = new HashSet<Processor>(processors);
<del> undecided.remove(splitPoint);
<del> undecided.removeAll(upStream);
<del> undecided.removeAll(downStream);
<del> return new ProcessorSplit(splitPoint, upStream, downStream, undecided);
<del> }
<del>
<add>
<ide> /**
<ide> * Find the first processor that contains an activity that has the given
<ide> * activity input port. See #get
<ide> }
<ide>
<ide> /**
<del> * Result bean returned from
<del> * {@link Tools#splitProcessors(Collection, Processor)}.
<del> *
<del> * @author Stian Soiland-Reyes
<del> *
<del> */
<del> public static class ProcessorSplit {
<del>
<del> private final TokenProcessingEntity splitPoint;
<del> private final Set<Processor> upStream;
<del> private final Set<Processor> downStream;
<del> private final Set<Processor> unconnected;
<del>
<del> /**
<del> * Processor that was used as a split point.
<del> *
<del> * @return Split point processor
<del> */
<del> public TokenProcessingEntity getSplitPoint() {
<del> return splitPoint;
<del> }
<del>
<del> /**
<del> * Processors that are upstream from the split point.
<del> *
<del> * @return Upstream processors
<del> */
<del> public Set<Processor> getUpStream() {
<del> return upStream;
<del> }
<del>
<del> /**
<del> * Processors that are downstream from the split point.
<del> *
<del> * @return Downstream processors
<del> */
<del> public Set<Processor> getDownStream() {
<del> return downStream;
<del> }
<del>
<del> /**
<del> * Processors that are unconnected to the split point.
<del> * <p>
<del> * These are processors in the dataflow that are neither upstream,
<del> * downstream or the split point itself.
<del> * <p>
<del> * Note that this does not imply a total graph separation, for instance
<del> * processors in {@link #getUpStream()} might have some of these
<del> * unconnected processors downstream, but not along the path to the
<del> * {@link #getSplitPoint()}, or they could be upstream from any
<del> * processor in {@link #getDownStream()}.
<del> *
<del> * @return Processors unconnected from the split point
<del> */
<del> public Set<Processor> getUnconnected() {
<del> return unconnected;
<del> }
<del>
<del> /**
<del> * Construct a new processor split result.
<del> *
<del> * @param splitPoint
<del> * Processor used as split point
<del> * @param upStream
<del> * Processors that are upstream from split point
<del> * @param downStream
<del> * Processors that are downstream from split point
<del> * @param unconnected
<del> * The rest of the processors, that are by definition
<del> * unconnected to split point
<del> */
<del> public ProcessorSplit(TokenProcessingEntity splitPoint, Set<Processor> upStream,
<del> Set<Processor> downStream, Set<Processor> unconnected) {
<del> this.splitPoint = splitPoint;
<del> this.upStream = upStream;
<del> this.downStream = downStream;
<del> this.unconnected = unconnected;
<del> }
<del>
<del> }
<del>
<del> /**
<ide> * Return a path of processors where the last element is this processor
<ide> * and previous ones are nested processors that contain this one all the
<ide> * way to the top but excluding the top level workflow as this is only a |
|
Java | lgpl-2.1 | ff2746e5e8147058148780fe1e37bc5f0dd7117f | 0 | viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.einsteintunnel.sensoryprocessing;
import ch.unizh.ini.jaer.projects.einsteintunnel.sensoryprocessing.BlurringTunnelTracker.Cluster;
import ch.unizh.ini.jaer.projects.einsteintunnel.sensoryprocessing.OSCutils.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
/**
*
* @author braendch
*/
public class ClusterOSCInterface {
public String DEFAULT_IP = "localhost";
public int DEFAULT_PORT = 9997;
public OSCutils utils ;
public ClusterOSCInterface(){
InetAddress address = null;
try {
address = InetAddress.getByName(DEFAULT_IP);
} catch (UnknownHostException ex) {
Logger.getLogger(ClusterOSCInterface.class.getName()).log(Level.SEVERE, null, ex);
}
utils = new OSCutils(address, DEFAULT_PORT);
}
public ClusterOSCInterface(int port){
InetAddress address = null;
try {
address = InetAddress.getByName("localhost");
} catch (UnknownHostException ex) {
Logger.getLogger(ClusterOSCInterface.class.getName()).log(Level.SEVERE, null, ex);
}
utils = new OSCutils(address, port);
}
public void sendActivity(short[] xHistogram){
Object args[] = new Object[xHistogram.length];
for(int i = 0; i<xHistogram.length; i++){
args[i] = new Float(xHistogram[i]);
}
utils.sendMessage("/jAER/histogram", args);
}
public void sendCluster(Cluster c){
Object[] clusterNumber = { new Integer(c.hashCode())};
OSCMessage msg1 = utils.new OSCMessage("/jAER/nr", clusterNumber);
Object[] clusterPosX = { new Float(c.getLocation().x)};
OSCMessage msg2 = utils.new OSCMessage("/jAER/pos/x", clusterPosX);
Object[] clusterPosY = { new Float(c.getLocation().y)};
OSCMessage msg3 = utils.new OSCMessage("/jAER/pos/y", clusterPosY);
Object[] clusterVelX = { new Float(c.getVelocityPPS().x)};
OSCMessage msg4 = utils.new OSCMessage("/jAER/vel/x", clusterVelX);
Object[] clusterVelY = { new Float(c.getVelocityPPS().y)};
OSCMessage msg5 = utils.new OSCMessage("/jAER/vel/y", clusterVelY);
Object[] clusterMass = { new Float(c.mass)};
OSCMessage msg6 = utils.new OSCMessage("/jAER/mass", clusterMass);
// create a timeStamped bundle of the messages
OSCPacket[] packets = {msg1, msg2, msg3, msg4, msg5, msg6};
Date newDate = new Date();
long time = newDate.getTime();
newDate.setTime(time);
OSCBundle bundle = utils.new OSCBundle(packets, newDate);
utils.sendBundle(bundle);
}
public void sendXPosition(float position){
Object[] args = {new Float(position)};
utils.sendMessage("/jAER/position/x", args);
}
public void sendYPosition(float position){
Object[] args = {new Float(position)};
utils.sendMessage("/jAER/position/y", args);
}
public void sendSpeed(float speed){
Object[] args = {new Float(speed)};
utils.sendMessage("/jAER/speed", args);
}
public void close(){
utils.socket.close();
}
}
| src/ch/unizh/ini/jaer/projects/einsteintunnel/sensoryprocessing/ClusterOSCInterface.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.einsteintunnel.sensoryprocessing;
import ch.unizh.ini.jaer.projects.einsteintunnel.sensoryprocessing.BlurringTunnelTracker.Cluster;
import ch.unizh.ini.jaer.projects.einsteintunnel.sensoryprocessing.OSCutils.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
/**
*
* @author braendch
*/
public class ClusterOSCInterface {
public int DEFAULT_PORT = 9997;
public OSCutils utils ;
public ClusterOSCInterface(){
InetAddress address = null;
try {
address = InetAddress.getByName("localhost");
} catch (UnknownHostException ex) {
Logger.getLogger(ClusterOSCInterface.class.getName()).log(Level.SEVERE, null, ex);
}
utils = new OSCutils(address, DEFAULT_PORT);
}
public ClusterOSCInterface(int port){
InetAddress address = null;
try {
address = InetAddress.getByName("localhost");
} catch (UnknownHostException ex) {
Logger.getLogger(ClusterOSCInterface.class.getName()).log(Level.SEVERE, null, ex);
}
utils = new OSCutils(address, port);
}
public void sendActivity(short[] xHistogram){
Object args[] = new Object[xHistogram.length];
for(int i = 0; i<xHistogram.length; i++){
args[i] = new Float(xHistogram[i]);
}
utils.sendMessage("/jAER/histogram", args);
}
public void sendCluster(Cluster c){
Object[] clusterNumber = { new Integer(c.hashCode())};
OSCMessage msg1 = utils.new OSCMessage("/jAER/nr", clusterNumber);
Object[] clusterPosX = { new Float(c.getLocation().x)};
OSCMessage msg2 = utils.new OSCMessage("/jAER/pos/x", clusterPosX);
Object[] clusterPosY = { new Float(c.getLocation().y)};
OSCMessage msg3 = utils.new OSCMessage("/jAER/pos/y", clusterPosY);
Object[] clusterVelX = { new Float(c.getVelocityPPS().x)};
OSCMessage msg4 = utils.new OSCMessage("/jAER/vel/x", clusterVelX);
Object[] clusterVelY = { new Float(c.getVelocityPPS().y)};
OSCMessage msg5 = utils.new OSCMessage("/jAER/vel/y", clusterVelY);
Object[] clusterMass = { new Float(c.mass)};
OSCMessage msg6 = utils.new OSCMessage("/jAER/mass", clusterMass);
// create a timeStamped bundle of the messages
OSCPacket[] packets = {msg1, msg2, msg3, msg4, msg5, msg6};
Date newDate = new Date();
long time = newDate.getTime();
newDate.setTime(time);
OSCBundle bundle = utils.new OSCBundle(packets, newDate);
utils.sendBundle(bundle);
}
public void sendXPosition(float position){
Object[] args = {new Float(position)};
utils.sendMessage("/jAER/position/x", args);
}
public void sendYPosition(float position){
Object[] args = {new Float(position)};
utils.sendMessage("/jAER/position/y", args);
}
public void sendSpeed(float speed){
Object[] args = {new Float(speed)};
utils.sendMessage("/jAER/speed", args);
}
public void close(){
utils.socket.close();
}
}
| Made IP public
git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@2516 b7f4320f-462c-0410-a916-d9f35bb82d52
| src/ch/unizh/ini/jaer/projects/einsteintunnel/sensoryprocessing/ClusterOSCInterface.java | Made IP public | <ide><path>rc/ch/unizh/ini/jaer/projects/einsteintunnel/sensoryprocessing/ClusterOSCInterface.java
<ide> */
<ide> public class ClusterOSCInterface {
<ide>
<add> public String DEFAULT_IP = "localhost";
<ide> public int DEFAULT_PORT = 9997;
<ide>
<ide> public OSCutils utils ;
<ide> public ClusterOSCInterface(){
<ide> InetAddress address = null;
<ide> try {
<del> address = InetAddress.getByName("localhost");
<add> address = InetAddress.getByName(DEFAULT_IP);
<ide> } catch (UnknownHostException ex) {
<ide> Logger.getLogger(ClusterOSCInterface.class.getName()).log(Level.SEVERE, null, ex);
<ide> } |
|
Java | mit | 045aade7007dda76bf7e9fa1ec3bbfb012e807b0 | 0 | iuridiniz/CheckMyECG,iuridiniz/CheckMyECG | package com.iuridiniz.checkmyecg.examiners;
import org.apache.commons.math3.util.Pair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.TreeMap;
/**
* Created by iuri on 27/11/15.
*/
public class EkgExaminer {
public enum Orientation {
UP, DOWN
};
public static final double ONE_SQUARE_X = 0.04;
public static final double ONE_SQUARE_Y = 0.1;
private final double[] time;
private final double[] voltage;
private LinkedList<Integer> __peaksPositions = null;
private final Orientation normalOrientation;
public final LinkedList<Integer> getPeaksPositions() {
if (__peaksPositions != null)
return __peaksPositions;
/* parse peaks */
__peaksPositions = new LinkedList<Integer>();
int direction = 0;
if (time.length < 3) {
return __peaksPositions;
}
for (int i = 0; i < time.length; i++) {
int new_direction;
double volt_diff;
if (i == 0) {
/* fisrt */
}
if (i+1 == time.length) {
/* last */
if (direction == 1) {
__peaksPositions.add(i);
}
continue;
}
volt_diff = voltage[i+1] - voltage[i];
new_direction = 0;
if (volt_diff < 0 ) {
new_direction = -1;
} else if (volt_diff > 0 ){
new_direction = 1;
}
if (new_direction != 0 && new_direction != direction) {
if (new_direction == 1) {
/* depression */
} else if (new_direction == -1){
/* peak */
__peaksPositions.add(i);
}
direction = new_direction;
}
}
/* return the median point */
for (int i=0; i<__peaksPositions.size(); i++) {
int start_pos = __peaksPositions.get(i);
int end_pos = __peaksPositions.get(i);
int pos = __peaksPositions.get(i);
if (pos == 0 || end_pos == time.length - 1) {
/* peek at start or at end */
} else {
/* backward start_pos to the first value lower point */
while (start_pos > 0 && voltage[start_pos-1] >= voltage[pos]) {
start_pos--;
};
/* forward end_pos to the first value lower point */
while (end_pos < time.length - 1 && voltage[end_pos+1] >= voltage[pos]) {
end_pos++;
};
/* change to median point */
int point = (Integer) (end_pos - start_pos)/2 + start_pos;
__peaksPositions.set(i, point);
}
}
return __peaksPositions;
}
public final TreeMap<Integer, Pair<Double, Double>> getPeaksPositionsAndCoefficients(double smoothness, /* linear coefficient */
double threshold) {
LinkedList<Integer> peaks = getPeaksPositions();
TreeMap<Integer, Pair<Double, Double>> result = new TreeMap<>();
for (int pos: peaks) {
/* get previous points */
int startPos = pos;
int endPos = pos;
if (pos == 0 || pos == time.length - 1) {
/* peek at start or at end */
} else {
/* backward startPos to the first value greater than threshold */
while (startPos > 0 && Math.abs(voltage[pos] - voltage[startPos]) < threshold) {
startPos--;
};
/* forward endPos to the first value greater than threshold */
while (endPos < (time.length - 1) && Math.abs(voltage[pos] - voltage[endPos]) < threshold) {
endPos++;
};
}
if (startPos != endPos) {
int pointLeft = startPos;
int pointRight = endPos;
double dxLeft, dyLeft;
double dxRight, dyRight;
double coefficientLeft, coefficientRight;
int meanPointLeft, meanPointRight;
double meanPoint;
meanPoint = ((double)pointRight - (double)pointLeft)/2.0 + pointLeft;
meanPointLeft = (int)Math.floor(meanPoint);
meanPointRight = (int)Math.ceil(meanPoint);
dxLeft = time[meanPointLeft] - time[pointLeft];
dyLeft = voltage[meanPointLeft] - voltage[pointLeft];
coefficientLeft = dyLeft/dxLeft;
dxRight = time[pointRight] - time[meanPointRight];
dyRight = voltage[pointRight] - voltage[meanPointRight];
coefficientRight = dyRight/dxRight;
if (coefficientLeft >= smoothness && -coefficientRight >=smoothness) {
result.put(pos, new Pair<Double, Double>(coefficientLeft, coefficientRight));
}
}
}
return result;
}
public final LinkedList<Integer> getPeaksPositions(double smoothness, /* linear coefficient */
double threshold) {
TreeMap<Integer, Pair<Double, Double>> posAndCo = getPeaksPositionsAndCoefficients(smoothness, threshold);
return new LinkedList<>(posAndCo.keySet());
}
public final LinkedList<Integer> getAcutePeaksPositions() {
return getPeaksPositions(1.0, ONE_SQUARE_Y);
}
public final TreeMap<Integer, Pair<Double, Double>> getAcutePeaksPositionsAndCoefficients() {
return getPeaksPositionsAndCoefficients(1.0, ONE_SQUARE_Y);
}
public EkgExaminer(double[] signalX, double[] signalY) {
this(signalX, signalY, Orientation.DOWN);
}
public EkgExaminer(double[] time, double[] voltage, Orientation o) {
this.time = time;
this.voltage = voltage;
if (time.length != voltage.length) {
throw new IllegalArgumentException("time.lenght must be equal to voltage.lenght");
}
this.normalOrientation = o;
}
public double getFrequency() {
final TreeMap<Integer, Pair<Double, Double>> coefficients = getAcutePeaksPositionsAndCoefficients();
Integer[] peaks = coefficients.keySet().toArray(new Integer[0]);
if (peaks.length < 4) {
/* insufficient points to determine the frequency */
return 0.0;
}
class MyPair extends Pair<Integer, Integer> implements Comparable{
final double diffTime;
final double diffCoefLeft;
final double diffCoefRight;
final double diffVolt;
int points = 0;
int coefPoints;
final int voltPoints;
public MyPair(Integer o1, Integer o2) {
super(o1, o2);
diffTime = Math.abs(time[o1] - time[o2]);
diffCoefLeft = Math.abs(coefficients.get(o1).getFirst() - coefficients.get(o2).getFirst());
diffCoefRight = Math.abs(coefficients.get(o1).getSecond() - coefficients.get(o2).getSecond());
diffVolt = Math.abs(voltage[o1] - voltage[o2]);
coefPoints = (int) (10.0/ diffCoefLeft);
points += coefPoints >50?50: coefPoints;
voltPoints = (int) (5.0/diffVolt);
points += voltPoints >100?100: voltPoints;
}
@Override
public int compareTo(Object o) {
return points - ((MyPair) o).points;
}
}
ArrayList<MyPair> a = new ArrayList<>();
for(int i = 0; i < peaks.length; i++) {
for (int j=i + 1;j< peaks.length; j++) {
MyPair p = new MyPair(peaks[i], peaks[j]);
a.add(p);
}
}
/* choose the best one */
Collections.sort(a);
Collections.reverse(a);
return 60.0/a.get(0).diffTime;
//return 60/a.get(0).diffTime;
}
}
| app/src/main/java/com/iuridiniz/checkmyecg/examiners/EkgExaminer.java | package com.iuridiniz.checkmyecg.examiners;
import org.apache.commons.math3.util.Pair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.TreeMap;
/**
* Created by iuri on 27/11/15.
*/
public class EkgExaminer {
public enum Orientation {
UP, DOWN
};
public static final double ONE_SQUARE_X = 0.04;
public static final double ONE_SQUARE_Y = 0.1;
private final double[] time;
private final double[] voltage;
private LinkedList<Integer> __peaksPositions = null;
private final Orientation normalOrientation;
public final LinkedList<Integer> getPeaksPositions() {
if (__peaksPositions != null)
return __peaksPositions;
/* parse peaks */
__peaksPositions = new LinkedList<Integer>();
int direction = 0;
if (time.length < 3) {
return __peaksPositions;
}
for (int i = 0; i < time.length; i++) {
int new_direction;
double volt_diff;
if (i == 0) {
/* fisrt */
}
if (i+1 == time.length) {
/* last */
if (direction == 1) {
__peaksPositions.add(i);
}
continue;
}
volt_diff = voltage[i+1] - voltage[i];
new_direction = 0;
if (volt_diff < 0 ) {
new_direction = -1;
} else if (volt_diff > 0 ){
new_direction = 1;
}
if (new_direction != 0 && new_direction != direction) {
if (new_direction == 1) {
/* depression */
} else if (new_direction == -1){
/* peak */
__peaksPositions.add(i);
}
direction = new_direction;
}
}
/* return the median point */
for (int i=0; i<__peaksPositions.size(); i++) {
int start_pos = __peaksPositions.get(i);
int pos = __peaksPositions.get(i);
if (pos == 0) {
/* peek at start */
} else {
/* backward start_pos to the first value lower than threshold */
while (start_pos > 0 && voltage[start_pos-1] >= voltage[pos]) {
start_pos--;
};
/* change to median point */
int point = (Integer) (pos - start_pos)/2 + start_pos;
__peaksPositions.set(i, point);
}
}
return __peaksPositions;
}
public final TreeMap<Integer, Double> getPeaksPositionsAndCoefficients(double smoothness, /* linear coefficient */
double threshold) {
LinkedList<Integer> peaks = getPeaksPositions();
TreeMap<Integer, Double> result = new TreeMap<>();
for (int pos: peaks) {
/* get previous points */
int start_pos = pos;
if (pos == 0) {
/* peek at start */
} else {
/* backward start_pos to the first value greather than threashold */
while (start_pos > 0 && (voltage[pos] - voltage[start_pos]) < threshold) {
start_pos--;
};
}
if (start_pos > 0) {
double dx = time[pos] - time[start_pos-1];
double dy = voltage[pos] - voltage[start_pos-1];
double coefficient = dy/dx;
if (coefficient >= smoothness) {
result.put(pos, coefficient);
}
}
}
return result;
}
public final LinkedList<Integer> getPeaksPositions(double smoothness, /* linear coefficient */
double threshold) {
TreeMap<Integer, Double> posAndCo = getPeaksPositionsAndCoefficients(smoothness, threshold);
return new LinkedList<>(posAndCo.keySet());
}
public final LinkedList<Integer> getAcutePeaksPositions() {
return getPeaksPositions(1.0, ONE_SQUARE_Y);
}
public final TreeMap<Integer, Double> getAcutePeaksPositionsAndCoefficients() {
return getPeaksPositionsAndCoefficients(1.0, ONE_SQUARE_Y);
}
public EkgExaminer(double[] signalX, double[] signalY) {
this(signalX, signalY, Orientation.DOWN);
}
public EkgExaminer(double[] time, double[] voltage, Orientation o) {
this.time = time;
this.voltage = voltage;
if (time.length != voltage.length) {
throw new IllegalArgumentException("time.lenght must be equal to voltage.lenght");
}
this.normalOrientation = o;
}
public double getFrequency() {
final TreeMap<Integer, Double> coefficients = getAcutePeaksPositionsAndCoefficients();
Integer[] peaks = coefficients.keySet().toArray(new Integer[0]);
if (peaks.length < 4) {
/* insufficient points to determine the frequency */
return 0.0;
}
class MyPair extends Pair<Integer, Integer> implements Comparable{
final double diffTime;
final double diffCoef;
final double diffVolt;
int points = 0;
int coefPoints;
final int voltPoints;
public MyPair(Integer o1, Integer o2) {
super(o1, o2);
diffTime = Math.abs(time[o1] - time[o2]);
diffCoef = Math.abs(coefficients.get(o1) - coefficients.get(o2));
diffVolt = Math.abs(voltage[o1] - voltage[o2]);
coefPoints = (int) (10.0/diffCoef);
points += coefPoints >50?50: coefPoints;
voltPoints = (int) (5.0/diffVolt);
points += voltPoints >100?100: voltPoints;
}
@Override
public int compareTo(Object o) {
return points - ((MyPair) o).points;
}
}
ArrayList<MyPair> a = new ArrayList<>();
for(int i = 0; i < peaks.length; i++) {
for (int j=i + 1;j< peaks.length; j++) {
MyPair p = new MyPair(peaks[i], peaks[j]);
a.add(p);
}
}
/* choose the best one */
Collections.sort(a);
Collections.reverse(a);
return 60.0/a.get(0).diffTime;
//return 60/a.get(0).diffTime;
}
}
| Getting the both linear coefficients (L and R)
| app/src/main/java/com/iuridiniz/checkmyecg/examiners/EkgExaminer.java | Getting the both linear coefficients (L and R) | <ide><path>pp/src/main/java/com/iuridiniz/checkmyecg/examiners/EkgExaminer.java
<ide> /* return the median point */
<ide> for (int i=0; i<__peaksPositions.size(); i++) {
<ide> int start_pos = __peaksPositions.get(i);
<add> int end_pos = __peaksPositions.get(i);
<ide> int pos = __peaksPositions.get(i);
<del> if (pos == 0) {
<del> /* peek at start */
<add> if (pos == 0 || end_pos == time.length - 1) {
<add> /* peek at start or at end */
<ide> } else {
<del> /* backward start_pos to the first value lower than threshold */
<add> /* backward start_pos to the first value lower point */
<ide> while (start_pos > 0 && voltage[start_pos-1] >= voltage[pos]) {
<ide> start_pos--;
<ide> };
<add> /* forward end_pos to the first value lower point */
<add> while (end_pos < time.length - 1 && voltage[end_pos+1] >= voltage[pos]) {
<add> end_pos++;
<add> };
<add>
<ide> /* change to median point */
<del> int point = (Integer) (pos - start_pos)/2 + start_pos;
<add> int point = (Integer) (end_pos - start_pos)/2 + start_pos;
<ide> __peaksPositions.set(i, point);
<ide> }
<ide> }
<ide> }
<ide>
<ide>
<del> public final TreeMap<Integer, Double> getPeaksPositionsAndCoefficients(double smoothness, /* linear coefficient */
<add> public final TreeMap<Integer, Pair<Double, Double>> getPeaksPositionsAndCoefficients(double smoothness, /* linear coefficient */
<ide> double threshold) {
<ide>
<ide> LinkedList<Integer> peaks = getPeaksPositions();
<del> TreeMap<Integer, Double> result = new TreeMap<>();
<add> TreeMap<Integer, Pair<Double, Double>> result = new TreeMap<>();
<ide>
<ide> for (int pos: peaks) {
<ide> /* get previous points */
<del> int start_pos = pos;
<del> if (pos == 0) {
<del> /* peek at start */
<add> int startPos = pos;
<add> int endPos = pos;
<add> if (pos == 0 || pos == time.length - 1) {
<add> /* peek at start or at end */
<ide> } else {
<del> /* backward start_pos to the first value greather than threashold */
<del> while (start_pos > 0 && (voltage[pos] - voltage[start_pos]) < threshold) {
<del> start_pos--;
<del> };
<del> }
<del> if (start_pos > 0) {
<del> double dx = time[pos] - time[start_pos-1];
<del> double dy = voltage[pos] - voltage[start_pos-1];
<del> double coefficient = dy/dx;
<del> if (coefficient >= smoothness) {
<del> result.put(pos, coefficient);
<add> /* backward startPos to the first value greater than threshold */
<add> while (startPos > 0 && Math.abs(voltage[pos] - voltage[startPos]) < threshold) {
<add> startPos--;
<add> };
<add> /* forward endPos to the first value greater than threshold */
<add> while (endPos < (time.length - 1) && Math.abs(voltage[pos] - voltage[endPos]) < threshold) {
<add> endPos++;
<add> };
<add>
<add> }
<add> if (startPos != endPos) {
<add> int pointLeft = startPos;
<add> int pointRight = endPos;
<add>
<add> double dxLeft, dyLeft;
<add> double dxRight, dyRight;
<add> double coefficientLeft, coefficientRight;
<add> int meanPointLeft, meanPointRight;
<add> double meanPoint;
<add>
<add> meanPoint = ((double)pointRight - (double)pointLeft)/2.0 + pointLeft;
<add> meanPointLeft = (int)Math.floor(meanPoint);
<add> meanPointRight = (int)Math.ceil(meanPoint);
<add>
<add> dxLeft = time[meanPointLeft] - time[pointLeft];
<add> dyLeft = voltage[meanPointLeft] - voltage[pointLeft];
<add> coefficientLeft = dyLeft/dxLeft;
<add>
<add> dxRight = time[pointRight] - time[meanPointRight];
<add> dyRight = voltage[pointRight] - voltage[meanPointRight];
<add>
<add> coefficientRight = dyRight/dxRight;
<add>
<add> if (coefficientLeft >= smoothness && -coefficientRight >=smoothness) {
<add> result.put(pos, new Pair<Double, Double>(coefficientLeft, coefficientRight));
<ide> }
<ide> }
<ide> }
<ide> public final LinkedList<Integer> getPeaksPositions(double smoothness, /* linear coefficient */
<ide> double threshold) {
<ide>
<del> TreeMap<Integer, Double> posAndCo = getPeaksPositionsAndCoefficients(smoothness, threshold);
<add> TreeMap<Integer, Pair<Double, Double>> posAndCo = getPeaksPositionsAndCoefficients(smoothness, threshold);
<ide> return new LinkedList<>(posAndCo.keySet());
<ide> }
<ide>
<ide> return getPeaksPositions(1.0, ONE_SQUARE_Y);
<ide> }
<ide>
<del> public final TreeMap<Integer, Double> getAcutePeaksPositionsAndCoefficients() {
<add> public final TreeMap<Integer, Pair<Double, Double>> getAcutePeaksPositionsAndCoefficients() {
<ide> return getPeaksPositionsAndCoefficients(1.0, ONE_SQUARE_Y);
<ide> }
<ide>
<ide>
<ide> public double getFrequency() {
<ide>
<del> final TreeMap<Integer, Double> coefficients = getAcutePeaksPositionsAndCoefficients();
<add> final TreeMap<Integer, Pair<Double, Double>> coefficients = getAcutePeaksPositionsAndCoefficients();
<ide> Integer[] peaks = coefficients.keySet().toArray(new Integer[0]);
<ide>
<ide> if (peaks.length < 4) {
<ide>
<ide> class MyPair extends Pair<Integer, Integer> implements Comparable{
<ide> final double diffTime;
<del> final double diffCoef;
<add> final double diffCoefLeft;
<add> final double diffCoefRight;
<ide> final double diffVolt;
<ide> int points = 0;
<ide> int coefPoints;
<ide> public MyPair(Integer o1, Integer o2) {
<ide> super(o1, o2);
<ide> diffTime = Math.abs(time[o1] - time[o2]);
<del> diffCoef = Math.abs(coefficients.get(o1) - coefficients.get(o2));
<add> diffCoefLeft = Math.abs(coefficients.get(o1).getFirst() - coefficients.get(o2).getFirst());
<add> diffCoefRight = Math.abs(coefficients.get(o1).getSecond() - coefficients.get(o2).getSecond());
<add>
<ide> diffVolt = Math.abs(voltage[o1] - voltage[o2]);
<ide>
<del> coefPoints = (int) (10.0/diffCoef);
<add> coefPoints = (int) (10.0/ diffCoefLeft);
<ide> points += coefPoints >50?50: coefPoints;
<ide>
<ide> voltPoints = (int) (5.0/diffVolt); |
|
Java | apache-2.0 | 5d978432dd9c89bd6c9f4d71411470bae0b109c4 | 0 | AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid | package me.devsaki.hentoid.services;
import android.app.IntentService;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.documentfile.provider.DocumentFile;
import com.annimon.stream.Optional;
import com.annimon.stream.Stream;
import org.greenrobot.eventbus.EventBus;
import org.threeten.bp.Instant;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.activities.bundles.ImportActivityBundle;
import me.devsaki.hentoid.database.CollectionDAO;
import me.devsaki.hentoid.database.ObjectBoxDAO;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.Group;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.database.domains.QueueRecord;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Grouping;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.enums.StatusContent;
import me.devsaki.hentoid.events.ProcessEvent;
import me.devsaki.hentoid.events.ServiceDestroyedEvent;
import me.devsaki.hentoid.json.ContentV1;
import me.devsaki.hentoid.json.DoujinBuilder;
import me.devsaki.hentoid.json.JsonContent;
import me.devsaki.hentoid.json.JsonContentCollection;
import me.devsaki.hentoid.json.URLBuilder;
import me.devsaki.hentoid.notification.import_.ImportCompleteNotification;
import me.devsaki.hentoid.notification.import_.ImportProgressNotification;
import me.devsaki.hentoid.notification.import_.ImportStartNotification;
import me.devsaki.hentoid.util.Consts;
import me.devsaki.hentoid.util.ContentHelper;
import me.devsaki.hentoid.util.FileHelper;
import me.devsaki.hentoid.util.ImageHelper;
import me.devsaki.hentoid.util.ImportHelper;
import me.devsaki.hentoid.util.JsonHelper;
import me.devsaki.hentoid.util.LogUtil;
import me.devsaki.hentoid.util.Preferences;
import me.devsaki.hentoid.util.exception.ParseException;
import me.devsaki.hentoid.util.notification.ServiceNotificationManager;
import timber.log.Timber;
/**
* Service responsible for importing an existing Hentoid library.
*
* @see UpdateCheckService
*/
public class ImportService extends IntentService {
private static final int NOTIFICATION_ID = 1;
public static final int STEP_GROUPS = 0;
public static final int STEP_1 = 1;
public static final int STEP_2_BOOK_FOLDERS = 2;
public static final int STEP_3_BOOKS = 3;
public static final int STEP_4_QUEUE = 4;
private static boolean running;
private ServiceNotificationManager notificationManager;
public ImportService() {
super(ImportService.class.getName());
}
public static Intent makeIntent(@NonNull Context context) {
return new Intent(context, ImportService.class);
}
public static boolean isRunning() {
return running;
}
@Override
public void onCreate() {
super.onCreate();
running = true;
notificationManager = new ServiceNotificationManager(this, NOTIFICATION_ID);
notificationManager.cancel();
notificationManager.startForeground(new ImportStartNotification());
Timber.w("Service created");
}
@Override
public void onDestroy() {
running = false;
if (notificationManager != null) notificationManager.cancel();
EventBus.getDefault().post(new ServiceDestroyedEvent(ServiceDestroyedEvent.Service.IMPORT));
Timber.w("Service destroyed");
super.onDestroy();
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
// True if the user has asked for a cleanup when calling import from Preferences
boolean doRename = false;
boolean doCleanAbsent = false;
boolean doCleanNoImages = false;
if (intent != null && intent.getExtras() != null) {
ImportActivityBundle.Parser parser = new ImportActivityBundle.Parser(intent.getExtras());
doRename = parser.getRefreshRename();
doCleanAbsent = parser.getRefreshCleanAbsent();
doCleanNoImages = parser.getRefreshCleanNoImages();
}
startImport(doRename, doCleanAbsent, doCleanNoImages);
}
private void eventProgress(int step, int nbBooks, int booksOK, int booksKO) {
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.PROGRESS, step, booksOK, booksKO, nbBooks));
}
private void eventComplete(int step, int nbBooks, int booksOK, int booksKO, DocumentFile cleanupLogFile) {
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.COMPLETE, step, booksOK, booksKO, nbBooks, cleanupLogFile));
}
private void trace(int priority, int chapter, List<LogUtil.LogEntry> memoryLog, String s, String... t) {
s = String.format(s, (Object[]) t);
Timber.log(priority, s);
boolean isError = (priority > Log.INFO);
if (null != memoryLog) memoryLog.add(new LogUtil.LogEntry(s, chapter, isError));
}
/**
* Import books from known source folders
*
* @param rename True if the user has asked for a folder renaming when calling import from Preferences
* @param cleanNoJSON True if the user has asked for a cleanup of folders with no JSONs when calling import from Preferences
* @param cleanNoImages True if the user has asked for a cleanup of folders with no images when calling import from Preferences
*/
private void startImport(boolean rename, boolean cleanNoJSON, boolean cleanNoImages) {
int booksOK = 0; // Number of books imported
int booksKO = 0; // Number of folders found with no valid book inside
int nbFolders = 0; // Number of folders found with no content but subfolders
Content content = null;
List<LogUtil.LogEntry> log = new ArrayList<>();
final FileHelper.NameFilter imageNames = displayName -> ImageHelper.isImageExtensionSupported(FileHelper.getExtension(displayName));
DocumentFile rootFolder = FileHelper.getFolderFromTreeUriString(this, Preferences.getStorageUri());
if (null == rootFolder) {
Timber.e("Root folder is not defined (%s)", Preferences.getStorageUri());
return;
}
ContentProviderClient client = this.getContentResolver().acquireContentProviderClient(Uri.parse(Preferences.getStorageUri()));
if (null == client) return;
List<DocumentFile> bookFolders = new ArrayList<>();
CollectionDAO dao = new ObjectBoxDAO(this);
try {
// 1st pass : Import groups JSON
// Flag existing groups for cleanup
dao.flagAllGroups(Grouping.CUSTOM);
DocumentFile groupsFile = FileHelper.findFile(this, rootFolder, client, Consts.GROUPS_JSON_FILE_NAME);
if (groupsFile != null) importGroups(groupsFile, dao, log);
else trace(Log.INFO, STEP_GROUPS, log, "No groups file found");
// 2nd pass : count subfolders of every site folder
List<DocumentFile> siteFolders = FileHelper.listFolders(this, rootFolder, client);
int foldersProcessed = 1;
for (DocumentFile f : siteFolders) {
bookFolders.addAll(FileHelper.listFolders(this, f, client));
eventProgress(STEP_2_BOOK_FOLDERS, siteFolders.size(), foldersProcessed++, 0);
}
eventComplete(STEP_2_BOOK_FOLDERS, siteFolders.size(), siteFolders.size(), 0, null);
notificationManager.startForeground(new ImportProgressNotification(this.getResources().getString(R.string.starting_import), 0, 0));
// 3rd pass : scan every folder for a JSON file or subdirectories
String enabled = getApplication().getResources().getString(R.string.enabled);
String disabled = getApplication().getResources().getString(R.string.disabled);
trace(Log.DEBUG, 0, log, "Import books starting - initial detected count : %s", bookFolders.size() + "");
trace(Log.INFO, 0, log, "Rename folders %s", (rename ? enabled : disabled));
trace(Log.INFO, 0, log, "Remove folders with no JSONs %s", (cleanNoJSON ? enabled : disabled));
trace(Log.INFO, 0, log, "Remove folders with no images %s", (cleanNoImages ? enabled : disabled));
// Flag DB content for cleanup
dao.flagAllInternalBooks();
dao.flagAllErrorBooksWithJson();
for (int i = 0; i < bookFolders.size(); i++) {
DocumentFile bookFolder = bookFolders.get(i);
// Detect the presence of images if the corresponding cleanup option has been enabled
if (cleanNoImages) {
List<DocumentFile> imageFiles = FileHelper.listFiles(this, bookFolder, client, imageNames);
List<DocumentFile> subfolders = FileHelper.listFolders(this, bookFolder, client);
if (imageFiles.isEmpty() && subfolders.isEmpty()) { // No supported images nor subfolders
booksKO++;
boolean success = bookFolder.delete();
trace(Log.INFO, STEP_1, log, "[Remove no image %s] Folder %s", success ? "OK" : "KO", bookFolder.getUri().toString());
continue;
}
}
// Find the corresponding flagged book in the library
Content existingFlaggedContent = dao.selectContentByFolderUri(bookFolder.getUri().toString(), true);
// Detect JSON and try to parse it
try {
content = importJson(bookFolder, client, dao);
if (content != null) {
// If the book exists and is flagged for deletion, delete it to make way for a new import (as intended)
if (existingFlaggedContent != null)
dao.deleteContent(existingFlaggedContent);
// If the very same book still exists in the DB at this point, it means it's present in the queue
// => don't import it even though it has a JSON file; it has been re-queued after being downloaded or viewed once
Content existingDuplicate = dao.selectContentBySourceAndUrl(content.getSite(), content.getUrl());
if (existingDuplicate != null && !existingDuplicate.isFlaggedForDeletion()) {
booksKO++;
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Import book KO! (already in queue) : %s", bookFolder.getUri().toString());
continue;
}
List<ImageFile> contentImages;
if (content.getImageFiles() != null)
contentImages = content.getImageFiles();
else contentImages = new ArrayList<>();
if (rename) {
String canonicalBookFolderName = ContentHelper.formatBookFolderName(content);
List<String> currentPathParts = bookFolder.getUri().getPathSegments();
String[] bookUriParts = currentPathParts.get(currentPathParts.size() - 1).split(":");
String[] bookPathParts = bookUriParts[bookUriParts.length - 1].split("/");
String bookFolderName = bookPathParts[bookPathParts.length - 1];
if (!canonicalBookFolderName.equalsIgnoreCase(bookFolderName)) {
if (renameFolder(bookFolder, content, client, canonicalBookFolderName)) {
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "[Rename OK] Folder %s renamed to %s", bookFolderName, canonicalBookFolderName);
} else {
trace(Log.WARN, STEP_2_BOOK_FOLDERS, log, "[Rename KO] Could not rename file %s to %s", bookFolderName, canonicalBookFolderName);
}
}
}
// Attach file Uri's to the book's images
List<DocumentFile> imageFiles = FileHelper.listFiles(this, bookFolder, client, imageNames);
if (!imageFiles.isEmpty()) { // No images described in the JSON -> recreate them
if (contentImages.isEmpty()) {
contentImages = ContentHelper.createImageListFromFiles(imageFiles);
content.setImageFiles(contentImages);
content.getCover().setUrl(content.getCoverImageUrl());
} else { // Existing images described in the JSON -> map them
contentImages = ContentHelper.matchFilesToImageList(imageFiles, contentImages);
// If no cover is defined, get it too
if (StatusContent.UNHANDLED_ERROR == content.getCover().getStatus()) {
Optional<DocumentFile> file = Stream.of(imageFiles).filter(f -> f.getName() != null && f.getName().startsWith(Consts.THUMB_FILE_NAME)).findFirst();
if (file.isPresent()) {
ImageFile cover = new ImageFile(0, content.getCoverImageUrl(), StatusContent.DOWNLOADED, content.getQtyPages());
cover.setName(Consts.THUMB_FILE_NAME);
cover.setFileUri(file.get().getUri().toString());
cover.setIsCover(true);
contentImages.add(0, cover);
}
}
content.setImageFiles(contentImages);
}
}
content.computeSize();
ContentHelper.addContent(dao, content);
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Import book OK : %s", bookFolder.getUri().toString());
} else { // JSON not found
List<DocumentFile> subfolders = FileHelper.listFolders(this, bookFolder, client);
if (!subfolders.isEmpty()) // Folder doesn't contain books but contains subdirectories
{
bookFolders.addAll(subfolders);
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Subfolders found in : %s", bookFolder.getUri().toString());
nbFolders++;
continue;
} else { // No JSON nor any subdirectory
trace(Log.WARN, STEP_2_BOOK_FOLDERS, log, "Import book KO! (no JSON found) : %s", bookFolder.getUri().toString());
// Deletes the folder if cleanup is active
if (cleanNoJSON) {
boolean success = bookFolder.delete();
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "[Remove no JSON %s] Folder %s", success ? "OK" : "KO", bookFolder.getUri().toString());
}
}
}
if (null == content) booksKO++;
else booksOK++;
} catch (ParseException jse) {
// If the book is still present in the DB, regenerate the JSON and unflag the book
if (existingFlaggedContent != null) {
try {
DocumentFile newJson = JsonHelper.jsonToFile(this, JsonContent.fromEntity(existingFlaggedContent), JsonContent.class, bookFolder);
existingFlaggedContent.setJsonUri(newJson.getUri().toString());
existingFlaggedContent.setFlaggedForDeletion(false);
dao.insertContent(existingFlaggedContent);
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Import book OK (JSON regenerated) : %s", bookFolder.getUri().toString());
booksOK++;
} catch (IOException ioe) {
Timber.w(ioe);
trace(Log.ERROR, STEP_2_BOOK_FOLDERS, log, "Import book ERROR while regenerating JSON : %s for Folder %s", jse.getMessage(), bookFolder.getUri().toString());
booksKO++;
}
} else { // If not, rebuild the book and regenerate the JSON according to stored data
try {
List<String> parentFolder = new ArrayList<>();
// Try and detect the site according to the parent folder
String[] parents = bookFolder.getUri().getPath().split("/"); // _not_ File.separator but the universal Uri separator
if (parents.length > 1) {
for (Site s : Site.values())
if (parents[parents.length - 2].equalsIgnoreCase(s.getFolder())) {
parentFolder.add(s.getFolder());
break;
}
}
// Scan the folder
Content storedContent = ImportHelper.scanBookFolder(this, bookFolder, client, parentFolder, StatusContent.DOWNLOADED, dao, null, null);
DocumentFile newJson = JsonHelper.jsonToFile(this, JsonContent.fromEntity(storedContent), JsonContent.class, bookFolder);
storedContent.setJsonUri(newJson.getUri().toString());
ContentHelper.addContent(dao, storedContent);
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Import book OK (Content regenerated) : %s", bookFolder.getUri().toString());
booksOK++;
} catch (IOException ioe) {
Timber.w(ioe);
trace(Log.ERROR, STEP_2_BOOK_FOLDERS, log, "Import book ERROR while regenerating Content : %s for Folder %s", jse.getMessage(), bookFolder.getUri().toString());
booksKO++;
}
}
} catch (Exception e) {
Timber.w(e);
if (null == content)
content = new Content().setTitle("none").setSite(Site.NONE).setUrl("");
booksKO++;
trace(Log.ERROR, STEP_2_BOOK_FOLDERS, log, "Import book ERROR : %s for Folder %s", e.getMessage(), bookFolder.getUri().toString());
}
String bookName = (null == bookFolder.getName()) ? "" : bookFolder.getName();
notificationManager.notify(new ImportProgressNotification(bookName, booksOK + booksKO, bookFolders.size() - nbFolders));
eventProgress(STEP_3_BOOKS, bookFolders.size() - nbFolders, booksOK, booksKO);
}
trace(Log.INFO, STEP_3_BOOKS, log, "Import books complete - %s OK; %s KO; %s final count", booksOK + "", booksKO + "", bookFolders.size() - nbFolders + "");
eventComplete(STEP_3_BOOKS, bookFolders.size(), booksOK, booksKO, null);
// 4th pass : Import queue JSON
DocumentFile queueFile = FileHelper.findFile(this, rootFolder, client, Consts.QUEUE_JSON_FILE_NAME);
if (queueFile != null) importQueue(queueFile, dao, log);
else trace(Log.INFO, STEP_4_QUEUE, log, "No queue file found");
} finally {
// Write log in root folder
DocumentFile logFile = LogUtil.writeLog(this, buildLogInfo(rename || cleanNoJSON || cleanNoImages, log));
// ContentProviderClient.close only available on API level 24+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
client.close();
else
client.release();
dao.deleteAllFlaggedBooks(true);
dao.deleteAllFlaggedGroups();
dao.cleanup();
eventComplete(STEP_4_QUEUE, bookFolders.size(), booksOK, booksKO, logFile);
notificationManager.notify(new ImportCompleteNotification(booksOK, booksKO));
}
stopForeground(true);
stopSelf();
}
private LogUtil.LogInfo buildLogInfo(boolean cleanup, @NonNull List<LogUtil.LogEntry> log) {
LogUtil.LogInfo logInfo = new LogUtil.LogInfo();
logInfo.setLogName(cleanup ? "Cleanup" : "Import");
logInfo.setFileName(cleanup ? "cleanup_log" : "import_log");
logInfo.setNoDataMessage("No content detected.");
logInfo.setLog(log);
return logInfo;
}
private boolean renameFolder(@NonNull DocumentFile folder, @NonNull final Content content, @NonNull ContentProviderClient client, @NonNull final String newName) {
try {
if (folder.renameTo(newName)) {
// 1- Update the book folder's URI
content.setStorageUri(folder.getUri().toString());
// 2- Update the JSON's URI
DocumentFile jsonFile = FileHelper.findFile(this, folder, client, Consts.JSON_FILE_NAME_V2);
if (jsonFile != null) content.setJsonUri(jsonFile.getUri().toString());
// 3- Update the image's URIs -> will be done by the next block back in startImport
return true;
}
} catch (Exception e) {
Timber.e(e);
}
return false;
}
private void importQueue(@NonNull DocumentFile queueFile, @NonNull CollectionDAO dao, @NonNull List<LogUtil.LogEntry> log) {
trace(Log.INFO, STEP_4_QUEUE, log, "Queue JSON found");
eventProgress(STEP_4_QUEUE, -1, 0, 0);
JsonContentCollection contentCollection = deserialiseCollectionJson(queueFile);
if (null != contentCollection) {
int queueSize = (int) dao.countAllQueueBooks();
List<Content> queuedContent = contentCollection.getQueue();
eventProgress(STEP_4_QUEUE, queuedContent.size(), 0, 0);
trace(Log.INFO, STEP_4_QUEUE, log, "Queue JSON deserialized : %s books detected", queuedContent.size() + "");
List<QueueRecord> lst = new ArrayList<>();
int count = 1;
for (Content c : queuedContent) {
// Only add at the end of the queue if it isn't a duplicate
Content duplicate = dao.selectContentBySourceAndUrl(c.getSite(), c.getUrl());
if (null == duplicate) {
long newContentId = ContentHelper.addContent(dao, c);
lst.add(new QueueRecord(newContentId, queueSize++));
}
eventProgress(STEP_4_QUEUE, queuedContent.size(), count++, 0);
}
dao.updateQueue(lst);
trace(Log.INFO, STEP_4_QUEUE, log, "Import queue succeeded");
} else {
trace(Log.INFO, STEP_4_QUEUE, log, "Import queue failed : Queue JSON unreadable");
}
}
private void importGroups(@NonNull DocumentFile groupsFile, @NonNull CollectionDAO dao, @NonNull List<LogUtil.LogEntry> log) {
trace(Log.INFO, STEP_GROUPS, log, "Custom groups JSON found");
eventProgress(STEP_GROUPS, -1, 0, 0);
JsonContentCollection contentCollection = deserialiseCollectionJson(groupsFile);
if (null != contentCollection) {
List<Group> groups = contentCollection.getCustomGroups();
eventProgress(STEP_GROUPS, groups.size(), 0, 0);
trace(Log.INFO, STEP_GROUPS, log, "Custom groups JSON deserialized : %s custom groups detected", groups.size() + "");
int count = 1;
for (Group g : groups) {
// Only add if it isn't a duplicate
Group duplicate = dao.selectGroupByName(Grouping.CUSTOM.getId(), g.name);
if (null == duplicate)
dao.insertGroup(g);
else { // If it is, unflag existing group
duplicate.setFlaggedForDeletion(false);
dao.insertGroup(duplicate);
}
eventProgress(STEP_GROUPS, groups.size(), count++, 0);
}
trace(Log.INFO, STEP_GROUPS, log, "Import custom groups succeeded");
} else {
trace(Log.INFO, STEP_GROUPS, log, "Import custom groups failed : Custom groups JSON unreadable");
}
}
private JsonContentCollection deserialiseCollectionJson(@NonNull DocumentFile jsonFile) {
JsonContentCollection result;
try {
result = JsonHelper.jsonToObject(this, jsonFile, JsonContentCollection.class);
} catch (IOException e) {
Timber.w(e);
return null;
}
return result;
}
@Nullable
private Content importJson(
@NonNull DocumentFile folder,
@NonNull ContentProviderClient client,
@NonNull CollectionDAO dao) throws ParseException {
DocumentFile file = FileHelper.findFile(this, folder, client, Consts.JSON_FILE_NAME_V2);
if (file != null) return importJsonV2(file, folder, dao);
file = FileHelper.findFile(this, folder, client, Consts.JSON_FILE_NAME);
if (file != null) return importJsonV1(file, folder);
file = FileHelper.findFile(this, folder, client, Consts.JSON_FILE_NAME_OLD);
if (file != null) return importJsonLegacy(file, folder);
return null;
}
@SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"})
private static List<Attribute> from(List<URLBuilder> urlBuilders, Site site) {
List<Attribute> attributes = null;
if (urlBuilders == null) {
return null;
}
if (!urlBuilders.isEmpty()) {
attributes = new ArrayList<>();
for (URLBuilder urlBuilder : urlBuilders) {
Attribute attribute = from(urlBuilder, AttributeType.TAG, site);
if (attribute != null) {
attributes.add(attribute);
}
}
}
return attributes;
}
@SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"})
private static Attribute from(URLBuilder urlBuilder, AttributeType type, Site site) {
if (urlBuilder == null) {
return null;
}
try {
if (urlBuilder.getDescription() == null) {
throw new ParseException("Problems loading attribute v2.");
}
return new Attribute(type, urlBuilder.getDescription(), urlBuilder.getId(), site);
} catch (Exception e) {
Timber.e(e, "Parsing URL to attribute");
return null;
}
}
@CheckResult
@SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"})
private Content importJsonLegacy(@NonNull final DocumentFile json, @NonNull final DocumentFile parentFolder) throws ParseException {
try {
DoujinBuilder doujinBuilder =
JsonHelper.jsonToObject(this, json, DoujinBuilder.class);
ContentV1 content = new ContentV1();
content.setUrl(doujinBuilder.getId());
content.setHtmlDescription(doujinBuilder.getDescription());
content.setTitle(doujinBuilder.getTitle());
content.setSeries(from(doujinBuilder.getSeries(),
AttributeType.SERIE, content.getSite()));
Attribute artist = from(doujinBuilder.getArtist(),
AttributeType.ARTIST, content.getSite());
List<Attribute> artists = null;
if (artist != null) {
artists = new ArrayList<>(1);
artists.add(artist);
}
content.setArtists(artists);
content.setCoverImageUrl(doujinBuilder.getUrlImageTitle());
content.setQtyPages(doujinBuilder.getQtyPages());
Attribute translator = from(doujinBuilder.getTranslator(),
AttributeType.TRANSLATOR, content.getSite());
List<Attribute> translators = null;
if (translator != null) {
translators = new ArrayList<>(1);
translators.add(translator);
}
content.setTranslators(translators);
content.setTags(from(doujinBuilder.getLstTags(), content.getSite()));
content.setLanguage(from(doujinBuilder.getLanguage(), AttributeType.LANGUAGE, content.getSite()));
content.setMigratedStatus();
content.setDownloadDate(Instant.now().toEpochMilli());
Content contentV2 = content.toV2Content();
contentV2.setStorageUri(parentFolder.getUri().toString());
DocumentFile newJson = JsonHelper.jsonToFile(this, JsonContent.fromEntity(contentV2), JsonContent.class, parentFolder);
contentV2.setJsonUri(newJson.getUri().toString());
return contentV2;
} catch (Exception e) {
Timber.e(e, "Error reading JSON (old) file");
throw new ParseException("Error reading JSON (old) file : " + e.getMessage());
}
}
@CheckResult
@SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"})
private Content importJsonV1(@NonNull final DocumentFile json, @NonNull final DocumentFile parentFolder) throws ParseException {
try {
ContentV1 content = JsonHelper.jsonToObject(this, json, ContentV1.class);
if (content.getStatus() != StatusContent.DOWNLOADED
&& content.getStatus() != StatusContent.ERROR) {
content.setMigratedStatus();
}
Content contentV2 = content.toV2Content();
contentV2.setStorageUri(parentFolder.getUri().toString());
DocumentFile newJson = JsonHelper.jsonToFile(this, JsonContent.fromEntity(contentV2), JsonContent.class, parentFolder);
contentV2.setJsonUri(newJson.getUri().toString());
return contentV2;
} catch (Exception e) {
Timber.e(e, "Error reading JSON (v1) file");
throw new ParseException("Error reading JSON (v1) file : " + e.getMessage());
}
}
@CheckResult
private Content importJsonV2(
@NonNull final DocumentFile json,
@NonNull final DocumentFile parentFolder,
@NonNull final CollectionDAO dao) throws ParseException {
try {
JsonContent content = JsonHelper.jsonToObject(this, json, JsonContent.class);
Content result = content.toEntity(dao);
result.setJsonUri(json.getUri().toString());
result.setStorageUri(parentFolder.getUri().toString());
if (result.getStatus() != StatusContent.DOWNLOADED
&& result.getStatus() != StatusContent.ERROR) {
result.setStatus(StatusContent.MIGRATED);
}
return result;
} catch (Exception e) {
Timber.e(e, "Error reading JSON (v2) file");
throw new ParseException("Error reading JSON (v2) file : " + e.getMessage(), e);
}
}
}
| app/src/main/java/me/devsaki/hentoid/services/ImportService.java | package me.devsaki.hentoid.services;
import android.app.IntentService;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.documentfile.provider.DocumentFile;
import com.annimon.stream.Optional;
import com.annimon.stream.Stream;
import org.greenrobot.eventbus.EventBus;
import org.threeten.bp.Instant;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.activities.bundles.ImportActivityBundle;
import me.devsaki.hentoid.database.CollectionDAO;
import me.devsaki.hentoid.database.ObjectBoxDAO;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.Group;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.database.domains.QueueRecord;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Grouping;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.enums.StatusContent;
import me.devsaki.hentoid.events.ProcessEvent;
import me.devsaki.hentoid.events.ServiceDestroyedEvent;
import me.devsaki.hentoid.json.ContentV1;
import me.devsaki.hentoid.json.DoujinBuilder;
import me.devsaki.hentoid.json.JsonContent;
import me.devsaki.hentoid.json.JsonContentCollection;
import me.devsaki.hentoid.json.URLBuilder;
import me.devsaki.hentoid.notification.import_.ImportCompleteNotification;
import me.devsaki.hentoid.notification.import_.ImportProgressNotification;
import me.devsaki.hentoid.notification.import_.ImportStartNotification;
import me.devsaki.hentoid.util.Consts;
import me.devsaki.hentoid.util.ContentHelper;
import me.devsaki.hentoid.util.FileHelper;
import me.devsaki.hentoid.util.ImageHelper;
import me.devsaki.hentoid.util.ImportHelper;
import me.devsaki.hentoid.util.JsonHelper;
import me.devsaki.hentoid.util.LogUtil;
import me.devsaki.hentoid.util.Preferences;
import me.devsaki.hentoid.util.exception.ParseException;
import me.devsaki.hentoid.util.notification.ServiceNotificationManager;
import timber.log.Timber;
/**
* Service responsible for importing an existing Hentoid library.
*
* @see UpdateCheckService
*/
public class ImportService extends IntentService {
private static final int NOTIFICATION_ID = 1;
public static final int STEP_GROUPS = 0;
public static final int STEP_1 = 1;
public static final int STEP_2_BOOK_FOLDERS = 2;
public static final int STEP_3_BOOKS = 3;
public static final int STEP_4_QUEUE = 4;
private static boolean running;
private ServiceNotificationManager notificationManager;
public ImportService() {
super(ImportService.class.getName());
}
public static Intent makeIntent(@NonNull Context context) {
return new Intent(context, ImportService.class);
}
public static boolean isRunning() {
return running;
}
@Override
public void onCreate() {
super.onCreate();
running = true;
notificationManager = new ServiceNotificationManager(this, NOTIFICATION_ID);
notificationManager.cancel();
notificationManager.startForeground(new ImportStartNotification());
Timber.w("Service created");
}
@Override
public void onDestroy() {
running = false;
if (notificationManager != null) notificationManager.cancel();
EventBus.getDefault().post(new ServiceDestroyedEvent(ServiceDestroyedEvent.Service.IMPORT));
Timber.w("Service destroyed");
super.onDestroy();
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
// True if the user has asked for a cleanup when calling import from Preferences
boolean doRename = false;
boolean doCleanAbsent = false;
boolean doCleanNoImages = false;
if (intent != null && intent.getExtras() != null) {
ImportActivityBundle.Parser parser = new ImportActivityBundle.Parser(intent.getExtras());
doRename = parser.getRefreshRename();
doCleanAbsent = parser.getRefreshCleanAbsent();
doCleanNoImages = parser.getRefreshCleanNoImages();
}
startImport(doRename, doCleanAbsent, doCleanNoImages);
}
private void eventProgress(int step, int nbBooks, int booksOK, int booksKO) {
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.PROGRESS, step, booksOK, booksKO, nbBooks));
}
private void eventComplete(int step, int nbBooks, int booksOK, int booksKO, DocumentFile cleanupLogFile) {
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.COMPLETE, step, booksOK, booksKO, nbBooks, cleanupLogFile));
}
private void trace(int priority, int chapter, List<LogUtil.LogEntry> memoryLog, String s, String... t) {
s = String.format(s, (Object[]) t);
Timber.log(priority, s);
boolean isError = (priority > Log.INFO);
if (null != memoryLog) memoryLog.add(new LogUtil.LogEntry(s, chapter, isError));
}
/**
* Import books from known source folders
*
* @param rename True if the user has asked for a folder renaming when calling import from Preferences
* @param cleanNoJSON True if the user has asked for a cleanup of folders with no JSONs when calling import from Preferences
* @param cleanNoImages True if the user has asked for a cleanup of folders with no images when calling import from Preferences
*/
private void startImport(boolean rename, boolean cleanNoJSON, boolean cleanNoImages) {
int booksOK = 0; // Number of books imported
int booksKO = 0; // Number of folders found with no valid book inside
int nbFolders = 0; // Number of folders found with no content but subfolders
Content content = null;
List<LogUtil.LogEntry> log = new ArrayList<>();
final FileHelper.NameFilter imageNames = displayName -> ImageHelper.isImageExtensionSupported(FileHelper.getExtension(displayName));
DocumentFile rootFolder = FileHelper.getFolderFromTreeUriString(this, Preferences.getStorageUri());
if (null == rootFolder) {
Timber.e("Root folder is not defined (%s)", Preferences.getStorageUri());
return;
}
ContentProviderClient client = this.getContentResolver().acquireContentProviderClient(Uri.parse(Preferences.getStorageUri()));
if (null == client) return;
List<DocumentFile> bookFolders = new ArrayList<>();
CollectionDAO dao = new ObjectBoxDAO(this);
try {
// 1st pass : Import groups JSON
// Flag existing groups for cleanup
dao.flagAllGroups(Grouping.CUSTOM);
DocumentFile groupsFile = FileHelper.findFile(this, rootFolder, client, Consts.QUEUE_JSON_FILE_NAME);
if (groupsFile != null) importGroups(groupsFile, dao, log);
else trace(Log.INFO, STEP_GROUPS, log, "No groups file found");
// 2nd pass : count subfolders of every site folder
List<DocumentFile> siteFolders = FileHelper.listFolders(this, rootFolder, client);
int foldersProcessed = 1;
for (DocumentFile f : siteFolders) {
bookFolders.addAll(FileHelper.listFolders(this, f, client));
eventProgress(STEP_2_BOOK_FOLDERS, siteFolders.size(), foldersProcessed++, 0);
}
eventComplete(STEP_2_BOOK_FOLDERS, siteFolders.size(), siteFolders.size(), 0, null);
notificationManager.startForeground(new ImportProgressNotification(this.getResources().getString(R.string.starting_import), 0, 0));
// 3rd pass : scan every folder for a JSON file or subdirectories
String enabled = getApplication().getResources().getString(R.string.enabled);
String disabled = getApplication().getResources().getString(R.string.disabled);
trace(Log.DEBUG, 0, log, "Import books starting - initial detected count : %s", bookFolders.size() + "");
trace(Log.INFO, 0, log, "Rename folders %s", (rename ? enabled : disabled));
trace(Log.INFO, 0, log, "Remove folders with no JSONs %s", (cleanNoJSON ? enabled : disabled));
trace(Log.INFO, 0, log, "Remove folders with no images %s", (cleanNoImages ? enabled : disabled));
// Flag DB content for cleanup
dao.flagAllInternalBooks();
dao.flagAllErrorBooksWithJson();
for (int i = 0; i < bookFolders.size(); i++) {
DocumentFile bookFolder = bookFolders.get(i);
// Detect the presence of images if the corresponding cleanup option has been enabled
if (cleanNoImages) {
List<DocumentFile> imageFiles = FileHelper.listFiles(this, bookFolder, client, imageNames);
List<DocumentFile> subfolders = FileHelper.listFolders(this, bookFolder, client);
if (imageFiles.isEmpty() && subfolders.isEmpty()) { // No supported images nor subfolders
booksKO++;
boolean success = bookFolder.delete();
trace(Log.INFO, STEP_1, log, "[Remove no image %s] Folder %s", success ? "OK" : "KO", bookFolder.getUri().toString());
continue;
}
}
// Find the corresponding flagged book in the library
Content existingFlaggedContent = dao.selectContentByFolderUri(bookFolder.getUri().toString(), true);
// Detect JSON and try to parse it
try {
content = importJson(bookFolder, client, dao);
if (content != null) {
// If the book exists and is flagged for deletion, delete it to make way for a new import (as intended)
if (existingFlaggedContent != null)
dao.deleteContent(existingFlaggedContent);
// If the very same book still exists in the DB at this point, it means it's present in the queue
// => don't import it even though it has a JSON file; it has been re-queued after being downloaded or viewed once
Content existingDuplicate = dao.selectContentBySourceAndUrl(content.getSite(), content.getUrl());
if (existingDuplicate != null && !existingDuplicate.isFlaggedForDeletion()) {
booksKO++;
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Import book KO! (already in queue) : %s", bookFolder.getUri().toString());
continue;
}
List<ImageFile> contentImages;
if (content.getImageFiles() != null)
contentImages = content.getImageFiles();
else contentImages = new ArrayList<>();
if (rename) {
String canonicalBookFolderName = ContentHelper.formatBookFolderName(content);
List<String> currentPathParts = bookFolder.getUri().getPathSegments();
String[] bookUriParts = currentPathParts.get(currentPathParts.size() - 1).split(":");
String[] bookPathParts = bookUriParts[bookUriParts.length - 1].split("/");
String bookFolderName = bookPathParts[bookPathParts.length - 1];
if (!canonicalBookFolderName.equalsIgnoreCase(bookFolderName)) {
if (renameFolder(bookFolder, content, client, canonicalBookFolderName)) {
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "[Rename OK] Folder %s renamed to %s", bookFolderName, canonicalBookFolderName);
} else {
trace(Log.WARN, STEP_2_BOOK_FOLDERS, log, "[Rename KO] Could not rename file %s to %s", bookFolderName, canonicalBookFolderName);
}
}
}
// Attach file Uri's to the book's images
List<DocumentFile> imageFiles = FileHelper.listFiles(this, bookFolder, client, imageNames);
if (!imageFiles.isEmpty()) { // No images described in the JSON -> recreate them
if (contentImages.isEmpty()) {
contentImages = ContentHelper.createImageListFromFiles(imageFiles);
content.setImageFiles(contentImages);
content.getCover().setUrl(content.getCoverImageUrl());
} else { // Existing images described in the JSON -> map them
contentImages = ContentHelper.matchFilesToImageList(imageFiles, contentImages);
// If no cover is defined, get it too
if (StatusContent.UNHANDLED_ERROR == content.getCover().getStatus()) {
Optional<DocumentFile> file = Stream.of(imageFiles).filter(f -> f.getName() != null && f.getName().startsWith(Consts.THUMB_FILE_NAME)).findFirst();
if (file.isPresent()) {
ImageFile cover = new ImageFile(0, content.getCoverImageUrl(), StatusContent.DOWNLOADED, content.getQtyPages());
cover.setName(Consts.THUMB_FILE_NAME);
cover.setFileUri(file.get().getUri().toString());
cover.setIsCover(true);
contentImages.add(0, cover);
}
}
content.setImageFiles(contentImages);
}
}
content.computeSize();
ContentHelper.addContent(dao, content);
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Import book OK : %s", bookFolder.getUri().toString());
} else { // JSON not found
List<DocumentFile> subfolders = FileHelper.listFolders(this, bookFolder, client);
if (!subfolders.isEmpty()) // Folder doesn't contain books but contains subdirectories
{
bookFolders.addAll(subfolders);
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Subfolders found in : %s", bookFolder.getUri().toString());
nbFolders++;
continue;
} else { // No JSON nor any subdirectory
trace(Log.WARN, STEP_2_BOOK_FOLDERS, log, "Import book KO! (no JSON found) : %s", bookFolder.getUri().toString());
// Deletes the folder if cleanup is active
if (cleanNoJSON) {
boolean success = bookFolder.delete();
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "[Remove no JSON %s] Folder %s", success ? "OK" : "KO", bookFolder.getUri().toString());
}
}
}
if (null == content) booksKO++;
else booksOK++;
} catch (ParseException jse) {
// If the book is still present in the DB, regenerate the JSON and unflag the book
if (existingFlaggedContent != null) {
try {
DocumentFile newJson = JsonHelper.jsonToFile(this, JsonContent.fromEntity(existingFlaggedContent), JsonContent.class, bookFolder);
existingFlaggedContent.setJsonUri(newJson.getUri().toString());
existingFlaggedContent.setFlaggedForDeletion(false);
dao.insertContent(existingFlaggedContent);
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Import book OK (JSON regenerated) : %s", bookFolder.getUri().toString());
booksOK++;
} catch (IOException ioe) {
Timber.w(ioe);
trace(Log.ERROR, STEP_2_BOOK_FOLDERS, log, "Import book ERROR while regenerating JSON : %s for Folder %s", jse.getMessage(), bookFolder.getUri().toString());
booksKO++;
}
} else { // If not, rebuild the book and regenerate the JSON according to stored data
try {
List<String> parentFolder = new ArrayList<>();
// Try and detect the site according to the parent folder
String[] parents = bookFolder.getUri().getPath().split("/"); // _not_ File.separator but the universal Uri separator
if (parents.length > 1) {
for (Site s : Site.values())
if (parents[parents.length - 2].equalsIgnoreCase(s.getFolder())) {
parentFolder.add(s.getFolder());
break;
}
}
// Scan the folder
Content storedContent = ImportHelper.scanBookFolder(this, bookFolder, client, parentFolder, StatusContent.DOWNLOADED, dao, null, null);
DocumentFile newJson = JsonHelper.jsonToFile(this, JsonContent.fromEntity(storedContent), JsonContent.class, bookFolder);
storedContent.setJsonUri(newJson.getUri().toString());
ContentHelper.addContent(dao, storedContent);
trace(Log.INFO, STEP_2_BOOK_FOLDERS, log, "Import book OK (Content regenerated) : %s", bookFolder.getUri().toString());
booksOK++;
} catch (IOException ioe) {
Timber.w(ioe);
trace(Log.ERROR, STEP_2_BOOK_FOLDERS, log, "Import book ERROR while regenerating Content : %s for Folder %s", jse.getMessage(), bookFolder.getUri().toString());
booksKO++;
}
}
} catch (Exception e) {
Timber.w(e);
if (null == content)
content = new Content().setTitle("none").setSite(Site.NONE).setUrl("");
booksKO++;
trace(Log.ERROR, STEP_2_BOOK_FOLDERS, log, "Import book ERROR : %s for Folder %s", e.getMessage(), bookFolder.getUri().toString());
}
String bookName = (null == bookFolder.getName()) ? "" : bookFolder.getName();
notificationManager.notify(new ImportProgressNotification(bookName, booksOK + booksKO, bookFolders.size() - nbFolders));
eventProgress(STEP_3_BOOKS, bookFolders.size() - nbFolders, booksOK, booksKO);
}
trace(Log.INFO, STEP_3_BOOKS, log, "Import books complete - %s OK; %s KO; %s final count", booksOK + "", booksKO + "", bookFolders.size() - nbFolders + "");
eventComplete(STEP_3_BOOKS, bookFolders.size(), booksOK, booksKO, null);
// 4th pass : Import queue JSON
DocumentFile queueFile = FileHelper.findFile(this, rootFolder, client, Consts.QUEUE_JSON_FILE_NAME);
if (queueFile != null) importQueue(queueFile, dao, log);
else trace(Log.INFO, STEP_4_QUEUE, log, "No queue file found");
} finally {
// Write log in root folder
DocumentFile logFile = LogUtil.writeLog(this, buildLogInfo(rename || cleanNoJSON || cleanNoImages, log));
// ContentProviderClient.close only available on API level 24+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
client.close();
else
client.release();
dao.deleteAllFlaggedBooks(true);
dao.deleteAllFlaggedGroups();
dao.cleanup();
eventComplete(STEP_4_QUEUE, bookFolders.size(), booksOK, booksKO, logFile);
notificationManager.notify(new ImportCompleteNotification(booksOK, booksKO));
}
stopForeground(true);
stopSelf();
}
private LogUtil.LogInfo buildLogInfo(boolean cleanup, @NonNull List<LogUtil.LogEntry> log) {
LogUtil.LogInfo logInfo = new LogUtil.LogInfo();
logInfo.setLogName(cleanup ? "Cleanup" : "Import");
logInfo.setFileName(cleanup ? "cleanup_log" : "import_log");
logInfo.setNoDataMessage("No content detected.");
logInfo.setLog(log);
return logInfo;
}
private boolean renameFolder(@NonNull DocumentFile folder, @NonNull final Content content, @NonNull ContentProviderClient client, @NonNull final String newName) {
try {
if (folder.renameTo(newName)) {
// 1- Update the book folder's URI
content.setStorageUri(folder.getUri().toString());
// 2- Update the JSON's URI
DocumentFile jsonFile = FileHelper.findFile(this, folder, client, Consts.JSON_FILE_NAME_V2);
if (jsonFile != null) content.setJsonUri(jsonFile.getUri().toString());
// 3- Update the image's URIs -> will be done by the next block back in startImport
return true;
}
} catch (Exception e) {
Timber.e(e);
}
return false;
}
private void importQueue(@NonNull DocumentFile queueFile, @NonNull CollectionDAO dao, @NonNull List<LogUtil.LogEntry> log) {
trace(Log.INFO, STEP_4_QUEUE, log, "Queue JSON found");
eventProgress(STEP_4_QUEUE, -1, 0, 0);
JsonContentCollection contentCollection = deserialiseCollectionJson(queueFile);
if (null != contentCollection) {
int queueSize = (int) dao.countAllQueueBooks();
List<Content> queuedContent = contentCollection.getQueue();
eventProgress(STEP_4_QUEUE, queuedContent.size(), 0, 0);
trace(Log.INFO, STEP_4_QUEUE, log, "Queue JSON deserialized : %s books detected", queuedContent.size() + "");
List<QueueRecord> lst = new ArrayList<>();
int count = 1;
for (Content c : queuedContent) {
// Only add at the end of the queue if it isn't a duplicate
Content duplicate = dao.selectContentBySourceAndUrl(c.getSite(), c.getUrl());
if (null == duplicate) {
long newContentId = ContentHelper.addContent(dao, c);
lst.add(new QueueRecord(newContentId, queueSize++));
}
eventProgress(STEP_4_QUEUE, queuedContent.size(), count++, 0);
}
dao.updateQueue(lst);
trace(Log.INFO, STEP_4_QUEUE, log, "Import queue succeeded");
} else {
trace(Log.INFO, STEP_4_QUEUE, log, "Import queue failed : Queue JSON unreadable");
}
}
private void importGroups(@NonNull DocumentFile groupsFile, @NonNull CollectionDAO dao, @NonNull List<LogUtil.LogEntry> log) {
trace(Log.INFO, STEP_GROUPS, log, "Custom groups JSON found");
eventProgress(STEP_GROUPS, -1, 0, 0);
JsonContentCollection contentCollection = deserialiseCollectionJson(groupsFile);
if (null != contentCollection) {
List<Group> groups = contentCollection.getCustomGroups();
eventProgress(STEP_GROUPS, groups.size(), 0, 0);
trace(Log.INFO, STEP_GROUPS, log, "Custom groups JSON deserialized : %s custom groups detected", groups.size() + "");
int count = 1;
for (Group g : groups) {
// Only add if it isn't a duplicate
Group duplicate = dao.selectGroupByName(Grouping.CUSTOM.getId(), g.name);
if (null == duplicate)
dao.insertGroup(g);
else { // If it is, unflag existing group
duplicate.setFlaggedForDeletion(false);
dao.insertGroup(duplicate);
}
eventProgress(STEP_GROUPS, groups.size(), count++, 0);
}
trace(Log.INFO, STEP_GROUPS, log, "Import custom groups succeeded");
} else {
trace(Log.INFO, STEP_GROUPS, log, "Import custom groups failed : Custom groups JSON unreadable");
}
}
private JsonContentCollection deserialiseCollectionJson(@NonNull DocumentFile jsonFile) {
JsonContentCollection result;
try {
result = JsonHelper.jsonToObject(this, jsonFile, JsonContentCollection.class);
} catch (IOException e) {
Timber.w(e);
return null;
}
return result;
}
@Nullable
private Content importJson(
@NonNull DocumentFile folder,
@NonNull ContentProviderClient client,
@NonNull CollectionDAO dao) throws ParseException {
DocumentFile file = FileHelper.findFile(this, folder, client, Consts.JSON_FILE_NAME_V2);
if (file != null) return importJsonV2(file, folder, dao);
file = FileHelper.findFile(this, folder, client, Consts.JSON_FILE_NAME);
if (file != null) return importJsonV1(file, folder);
file = FileHelper.findFile(this, folder, client, Consts.JSON_FILE_NAME_OLD);
if (file != null) return importJsonLegacy(file, folder);
return null;
}
@SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"})
private static List<Attribute> from(List<URLBuilder> urlBuilders, Site site) {
List<Attribute> attributes = null;
if (urlBuilders == null) {
return null;
}
if (!urlBuilders.isEmpty()) {
attributes = new ArrayList<>();
for (URLBuilder urlBuilder : urlBuilders) {
Attribute attribute = from(urlBuilder, AttributeType.TAG, site);
if (attribute != null) {
attributes.add(attribute);
}
}
}
return attributes;
}
@SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"})
private static Attribute from(URLBuilder urlBuilder, AttributeType type, Site site) {
if (urlBuilder == null) {
return null;
}
try {
if (urlBuilder.getDescription() == null) {
throw new ParseException("Problems loading attribute v2.");
}
return new Attribute(type, urlBuilder.getDescription(), urlBuilder.getId(), site);
} catch (Exception e) {
Timber.e(e, "Parsing URL to attribute");
return null;
}
}
@CheckResult
@SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"})
private Content importJsonLegacy(@NonNull final DocumentFile json, @NonNull final DocumentFile parentFolder) throws ParseException {
try {
DoujinBuilder doujinBuilder =
JsonHelper.jsonToObject(this, json, DoujinBuilder.class);
ContentV1 content = new ContentV1();
content.setUrl(doujinBuilder.getId());
content.setHtmlDescription(doujinBuilder.getDescription());
content.setTitle(doujinBuilder.getTitle());
content.setSeries(from(doujinBuilder.getSeries(),
AttributeType.SERIE, content.getSite()));
Attribute artist = from(doujinBuilder.getArtist(),
AttributeType.ARTIST, content.getSite());
List<Attribute> artists = null;
if (artist != null) {
artists = new ArrayList<>(1);
artists.add(artist);
}
content.setArtists(artists);
content.setCoverImageUrl(doujinBuilder.getUrlImageTitle());
content.setQtyPages(doujinBuilder.getQtyPages());
Attribute translator = from(doujinBuilder.getTranslator(),
AttributeType.TRANSLATOR, content.getSite());
List<Attribute> translators = null;
if (translator != null) {
translators = new ArrayList<>(1);
translators.add(translator);
}
content.setTranslators(translators);
content.setTags(from(doujinBuilder.getLstTags(), content.getSite()));
content.setLanguage(from(doujinBuilder.getLanguage(), AttributeType.LANGUAGE, content.getSite()));
content.setMigratedStatus();
content.setDownloadDate(Instant.now().toEpochMilli());
Content contentV2 = content.toV2Content();
contentV2.setStorageUri(parentFolder.getUri().toString());
DocumentFile newJson = JsonHelper.jsonToFile(this, JsonContent.fromEntity(contentV2), JsonContent.class, parentFolder);
contentV2.setJsonUri(newJson.getUri().toString());
return contentV2;
} catch (Exception e) {
Timber.e(e, "Error reading JSON (old) file");
throw new ParseException("Error reading JSON (old) file : " + e.getMessage());
}
}
@CheckResult
@SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"})
private Content importJsonV1(@NonNull final DocumentFile json, @NonNull final DocumentFile parentFolder) throws ParseException {
try {
ContentV1 content = JsonHelper.jsonToObject(this, json, ContentV1.class);
if (content.getStatus() != StatusContent.DOWNLOADED
&& content.getStatus() != StatusContent.ERROR) {
content.setMigratedStatus();
}
Content contentV2 = content.toV2Content();
contentV2.setStorageUri(parentFolder.getUri().toString());
DocumentFile newJson = JsonHelper.jsonToFile(this, JsonContent.fromEntity(contentV2), JsonContent.class, parentFolder);
contentV2.setJsonUri(newJson.getUri().toString());
return contentV2;
} catch (Exception e) {
Timber.e(e, "Error reading JSON (v1) file");
throw new ParseException("Error reading JSON (v1) file : " + e.getMessage());
}
}
@CheckResult
private Content importJsonV2(
@NonNull final DocumentFile json,
@NonNull final DocumentFile parentFolder,
@NonNull final CollectionDAO dao) throws ParseException {
try {
JsonContent content = JsonHelper.jsonToObject(this, json, JsonContent.class);
Content result = content.toEntity(dao);
result.setJsonUri(json.getUri().toString());
result.setStorageUri(parentFolder.getUri().toString());
if (result.getStatus() != StatusContent.DOWNLOADED
&& result.getStatus() != StatusContent.ERROR) {
result.setStatus(StatusContent.MIGRATED);
}
return result;
} catch (Exception e) {
Timber.e(e, "Error reading JSON (v2) file");
throw new ParseException("Error reading JSON (v2) file : " + e.getMessage(), e);
}
}
}
| Fix groups filename
| app/src/main/java/me/devsaki/hentoid/services/ImportService.java | Fix groups filename | <ide><path>pp/src/main/java/me/devsaki/hentoid/services/ImportService.java
<ide> // Flag existing groups for cleanup
<ide> dao.flagAllGroups(Grouping.CUSTOM);
<ide>
<del> DocumentFile groupsFile = FileHelper.findFile(this, rootFolder, client, Consts.QUEUE_JSON_FILE_NAME);
<add> DocumentFile groupsFile = FileHelper.findFile(this, rootFolder, client, Consts.GROUPS_JSON_FILE_NAME);
<ide> if (groupsFile != null) importGroups(groupsFile, dao, log);
<ide> else trace(Log.INFO, STEP_GROUPS, log, "No groups file found");
<ide> |
|
Java | apache-2.0 | 408855b270816b05ab1fe0c4518b5d37a09538cd | 0 | hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services | package org.sagebionetworks.repo.web.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URL;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sagebionetworks.evaluation.model.Evaluation;
import org.sagebionetworks.evaluation.model.EvaluationStatus;
import org.sagebionetworks.repo.manager.NodeManager;
import org.sagebionetworks.repo.manager.UserManager;
import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.PaginatedResults;
import org.sagebionetworks.repo.model.Project;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.dao.FileHandleDao;
import org.sagebionetworks.repo.model.dao.WikiPageKey;
import org.sagebionetworks.repo.model.file.FileHandleResults;
import org.sagebionetworks.repo.model.file.PreviewFileHandle;
import org.sagebionetworks.repo.model.file.S3FileHandle;
import org.sagebionetworks.repo.model.jdo.KeyFactory;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage;
import org.sagebionetworks.repo.web.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class V2WikiControllerTest {
@Autowired
private EntityServletTestHelper entityServletHelper;
@Autowired
private UserManager userManager;
@Autowired
private NodeManager nodeManager;
@Autowired
private FileHandleDao fileMetadataDao;
private Long adminUserId;
private String adminUserIdString;
private Project entity;
private Evaluation evaluation;
private List<WikiPageKey> toDelete;
private S3FileHandle handleOne;
private S3FileHandle markdown;
private S3FileHandle markdownTwo;
private PreviewFileHandle handleTwo;
@Before
public void before() throws Exception{
// get user IDs
adminUserId = BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId();
adminUserIdString = adminUserId.toString();
toDelete = new LinkedList<WikiPageKey>();
// Create a file handle
handleOne = new S3FileHandle();
handleOne.setCreatedBy(adminUserIdString);
handleOne.setCreatedOn(new Date());
handleOne.setBucketName("bucket");
handleOne.setKey("mainFileKey");
handleOne.setEtag("etag");
handleOne.setFileName("foo.bar");
handleOne = fileMetadataDao.createFile(handleOne);
// Create a preview
handleTwo = new PreviewFileHandle();
handleTwo.setCreatedBy(adminUserIdString);
handleTwo.setCreatedOn(new Date());
handleTwo.setBucketName("bucket");
handleTwo.setKey("previewFileKey");
handleTwo.setEtag("etag");
handleTwo.setFileName("bar.txt");
handleTwo = fileMetadataDao.createFile(handleTwo);
// Set two as the preview of one
fileMetadataDao.setPreviewId(handleOne.getId(), handleTwo.getId());
markdown = new S3FileHandle();
markdown.setCreatedBy(adminUserIdString);
markdown.setCreatedOn(new Date());
markdown.setBucketName("bucket");
markdown.setKey("markdownKey");
markdown.setEtag("etag");
markdown.setFileName("markdown");
markdown = fileMetadataDao.createFile(markdown);
markdownTwo = new S3FileHandle();
markdownTwo.setCreatedBy(adminUserIdString);
markdownTwo.setCreatedOn(new Date());
markdownTwo.setBucketName("bucket");
markdownTwo.setKey("markdownKey2");
markdownTwo.setEtag("etag2");
markdownTwo.setFileName("markdown2");
markdownTwo = fileMetadataDao.createFile(markdownTwo);
}
@After
public void after() throws Exception{
for(WikiPageKey key: toDelete){
entityServletHelper.deleteV2WikiPage(key, adminUserId);
}
if(evaluation != null){
try {
entityServletHelper.deleteEvaluation(evaluation.getId(), adminUserId);
} catch (Exception e) {}
}
if(entity != null){
UserInfo userInfo = userManager.getUserInfo(adminUserId);
nodeManager.delete(userInfo, entity.getId());
}
if(handleOne != null && handleOne.getId() != null){
fileMetadataDao.delete(handleOne.getId());
}
if(handleTwo != null && handleTwo.getId() != null){
fileMetadataDao.delete(handleTwo.getId());
}
if(markdown != null && markdown.getId() != null) {
fileMetadataDao.delete(markdown.getId());
}
if(markdownTwo != null && markdownTwo.getId() != null) {
fileMetadataDao.delete(markdownTwo.getId());
}
}
@Test
public void testEntityWikiCRUD() throws Exception {
// create an entity
entity = new Project();
entity.setEntityType(Project.class.getName());
entity = (Project) entityServletHelper.createEntity(entity, adminUserId, null);
// Test all wiki CRUD for an entity
doWikiCRUDForOwnerObject(entity.getId(), ObjectType.ENTITY);
}
@Test
public void testCompetitionWikiCRUD() throws Exception {
// create an entity
evaluation = new Evaluation();
evaluation.setName("testCompetitionWikiCRUD");
evaluation.setContentSource(KeyFactory.SYN_ROOT_ID);
evaluation.setDescription("a test descrption");
evaluation.setStatus(EvaluationStatus.OPEN);
evaluation = entityServletHelper.createEvaluation(evaluation, adminUserId);
// Test all wiki CRUD for an entity
doWikiCRUDForOwnerObject(evaluation.getId(), ObjectType.EVALUATION);
}
/**
* Perform all Wiki CRUD for a given owner. This allows the same test to be run for each owner type.
* @param ownerId
* @param ownerType
* @throws Exception
*/
private void doWikiCRUDForOwnerObject(String ownerId, ObjectType ownerType) throws Exception{
// Create a wiki page
V2WikiPage wiki = new V2WikiPage();
wiki.setTitle("testCreateEntityWikiRoundTrip-"+ownerId+"-"+ownerType);
wiki.setMarkdownFileHandleId(markdown.getId());
wiki.setAttachmentFileHandleIds(new LinkedList<String>());
wiki = entityServletHelper.createV2WikiPage(adminUserId, ownerId, ownerType, wiki);
assertNotNull(wiki);
assertNotNull(wiki.getId());
WikiPageKey key = new WikiPageKey(ownerId, ownerType, wiki.getId());
toDelete.add(key);
assertNotNull(wiki.getEtag());
assertNotNull(ownerId, wiki.getModifiedBy());
assertNotNull(ownerId, wiki.getCreatedBy());
URL markdownPresigned = entityServletHelper.getV2WikiMarkdownFileURL(adminUserId, key, null, null);
assertNotNull(markdownPresigned);
assertTrue(markdownPresigned.toString().indexOf("markdownKey") > 0);
PaginatedResults<V2WikiHistorySnapshot> startHistory = entityServletHelper.getV2WikiHistory(key, adminUserId, new Long(0), new Long(10));
assertNotNull(startHistory);
List<V2WikiHistorySnapshot> firstSnapshot = startHistory.getResults();
assertNotNull(firstSnapshot);
assertEquals(1, firstSnapshot.size());
// Results are ordered, descending
// First snapshot is the most recent modification/highest version
assertEquals("0", firstSnapshot.get(0).getVersion());
// Get the wiki page.
V2WikiPage clone = entityServletHelper.getV2WikiPage(key, adminUserId, null);
assertNotNull(clone);
System.out.println(clone);
assertEquals(wiki, clone);
V2WikiPage getFirstVersion = entityServletHelper.getV2WikiPage(key, adminUserId, new Long(0));
assertEquals(wiki, getFirstVersion);
// Get the root wiki
V2WikiPage root = entityServletHelper.getRootV2WikiPage(ownerId, ownerType, adminUserId);
// The root should match the clone
assertEquals(clone, root);
// Update the wiki
clone.setMarkdownFileHandleId(markdownTwo.getId());
clone.getAttachmentFileHandleIds().add(handleOne.getId());
clone.setTitle("Version 1 title");
String currentEtag = clone.getEtag();
V2WikiPage cloneUpdated = entityServletHelper.updateWikiPage(adminUserId, ownerId, ownerType, clone);
assertNotNull(cloneUpdated);
assertEquals("Version 1 title", cloneUpdated.getTitle());
assertEquals(cloneUpdated.getMarkdownFileHandleId(), markdownTwo.getId());
assertEquals(cloneUpdated.getAttachmentFileHandleIds().size(), 1);
assertEquals(cloneUpdated.getAttachmentFileHandleIds().get(0), handleOne.getId());
assertFalse("The etag should have changed from the update", currentEtag.equals(cloneUpdated.getEtag()));
// Update one more time
cloneUpdated.getAttachmentFileHandleIds().add(handleTwo.getId());
cloneUpdated.setTitle("Version 2 title");
String currentEtag2 = cloneUpdated.getEtag();
V2WikiPage cloneUpdated2 = entityServletHelper.updateWikiPage(adminUserId, ownerId, ownerType, cloneUpdated);
assertNotNull(cloneUpdated2);
assertEquals(cloneUpdated2.getMarkdownFileHandleId(), markdownTwo.getId());
assertEquals(cloneUpdated2.getAttachmentFileHandleIds().size(), 2);
assertEquals(cloneUpdated2.getTitle(), "Version 2 title");
assertFalse("The etag should have changed from the update", currentEtag2.equals(cloneUpdated2.getEtag()));
URL markdownPresignedUpdated = entityServletHelper.getV2WikiMarkdownFileURL(adminUserId, key, new Long(0), null);
assertNotNull(markdownPresignedUpdated);
assertTrue(markdownPresignedUpdated.toString().indexOf("markdownKey") > 0);
Boolean redirectMarkdown = Boolean.FALSE;
markdownPresignedUpdated = entityServletHelper.getV2WikiMarkdownFileURL(adminUserId, key, new Long(0), redirectMarkdown);
assertNotNull(markdownPresignedUpdated);
assertTrue(markdownPresignedUpdated.toString().indexOf("markdownKey") > 0);
// Get history (there should be three snapshots returned)
PaginatedResults<V2WikiHistorySnapshot> historyResults = entityServletHelper.getV2WikiHistory(key, adminUserId, new Long(0), new Long(10));
assertNotNull(historyResults);
List<V2WikiHistorySnapshot> snapshots = historyResults.getResults();
assertNotNull(snapshots);
assertEquals(3, snapshots.size());
// Results are ordered, descending
// First snapshot is the most recent modification/highest version
assertEquals("2", snapshots.get(0).getVersion());
assertEquals("1", snapshots.get(1).getVersion());
assertEquals("0", snapshots.get(2).getVersion());
// First version should have no file handles
FileHandleResults oldHandles = entityServletHelper.getV2WikiFileHandles(adminUserId, key, new Long(0));
assertNotNull(oldHandles);
assertNotNull(oldHandles.getList());
assertEquals(0, oldHandles.getList().size());
Long versionToRestore = new Long(1);
// Get an older version
V2WikiPage versionOne = entityServletHelper.getV2WikiPage(key, adminUserId, versionToRestore);
assertEquals(markdownTwo.getId(), versionOne.getMarkdownFileHandleId());
assertEquals(1, versionOne.getAttachmentFileHandleIds().size());
// Get its attachment's URL
URL versionOneAttachment = entityServletHelper.getV2WikiAttachmentFileURL(adminUserId, key, handleOne.getFileName(), null, new Long(1));
assertNotNull(versionOneAttachment);
assertTrue(versionOneAttachment.toString().indexOf("mainFileKey") > 0);
assertEquals("Version 1 title", versionOne.getTitle());
assertEquals(cloneUpdated.getModifiedOn(), versionOne.getModifiedOn());
// Restore wiki to version 1 which had markdownTwo and one file attachment, and a title of "Version 1 title"
String currentEtag3 = cloneUpdated2.getEtag();
V2WikiPage restored = entityServletHelper.restoreWikiPage(adminUserId, ownerId, ownerType, cloneUpdated2, versionToRestore);
assertNotNull(restored);
assertFalse("The etag should have changed from the restore", currentEtag3.equals(restored.getEtag()));
assertEquals(cloneUpdated2.getCreatedBy(), restored.getCreatedBy());
assertEquals(cloneUpdated2.getCreatedOn(), restored.getCreatedOn());
assertEquals(restored.getMarkdownFileHandleId(), markdownTwo.getId());
assertEquals(restored.getAttachmentFileHandleIds().size(), 1);
assertEquals(clone.getTitle(), restored.getTitle());
// Add a child wiki
V2WikiPage child = new V2WikiPage();
child.setTitle("Child");
child.setMarkdownFileHandleId(markdown.getId());
child.setParentWikiId(wiki.getId());
child.setAttachmentFileHandleIds(new LinkedList<String>());
// Note, we are adding a file handle with a preview.
// Both the S3FileHandle and its Preview should be returned from getWikiFileHandles()
child.getAttachmentFileHandleIds().add(handleOne.getId());
// Create child!
child = entityServletHelper.createV2WikiPage(adminUserId, ownerId, ownerType, child);
assertNotNull(child);
assertNotNull(child.getId());
WikiPageKey childKey = new WikiPageKey(ownerId, ownerType, child.getId());
toDelete.add(childKey);
// List the hierarchy
PaginatedResults<V2WikiHeader> paginated = entityServletHelper.getV2WikiHeaderTree(adminUserId, ownerId, ownerType);
assertNotNull(paginated);
assertNotNull(paginated.getResults());
assertEquals(2, paginated.getResults().size());
// check the root header.
V2WikiHeader rootHeader = paginated.getResults().get(0);
assertEquals(clone.getId(), rootHeader.getId());
assertEquals(clone.getTitle(), rootHeader.getTitle());
assertEquals(null, rootHeader.getParentId());
// Check the child header
V2WikiHeader childHeader = paginated.getResults().get(1);
assertEquals(child.getId(), childHeader.getId());
assertEquals(child.getTitle(), childHeader.getTitle());
assertEquals(wiki.getId(), childHeader.getParentId());
// Check that we can get the FileHandles
FileHandleResults handles = entityServletHelper.getV2WikiFileHandles(adminUserId, childKey, null);
assertNotNull(handles);
assertNotNull(handles.getList());
assertEquals(2, handles.getList().size());
// The first should be the S3FileHandle, the second should be the Preview.
assertEquals(handleOne.getId(), handles.getList().get(0).getId());
assertEquals(handleTwo.getId(), handles.getList().get(1).getId());
// Get the presigned URL for the first file
URL presigned = entityServletHelper.getV2WikiAttachmentFileURL(adminUserId, childKey, handleOne.getFileName(), null, null);
assertNotNull(presigned);
assertTrue(presigned.toString().indexOf("mainFileKey") > 0);
System.out.println(presigned);
// Get the preview presigned URL.
presigned = entityServletHelper.getV2WikiAttachmentPreviewFileURL(adminUserId, childKey, handleOne.getFileName(), null, null);
assertNotNull(presigned);
assertTrue(presigned.toString().indexOf("previewFileKey") > 0);
System.out.println(presigned);
// Make sure we can get the URLs without a redirect
Boolean redirect = Boolean.FALSE;
presigned = entityServletHelper.getV2WikiAttachmentFileURL(adminUserId, childKey, handleOne.getFileName(), redirect, null);
assertNotNull(presigned);
assertTrue(presigned.toString().indexOf("mainFileKey") > 0);
System.out.println(presigned);
// again without the redirct
presigned = entityServletHelper.getV2WikiAttachmentPreviewFileURL(adminUserId, childKey, handleOne.getFileName(), redirect, null);
assertNotNull(presigned);
assertTrue(presigned.toString().indexOf("previewFileKey") > 0);
System.out.println(presigned);
// Now delete the wiki
entityServletHelper.deleteV2WikiPage(key, adminUserId);
try {
entityServletHelper.getV2WikiPage(key, adminUserId, null);
fail("The wiki should have been deleted");
} catch (NotFoundException e) {
// this is expected
}
// the child should be delete as well
try {
entityServletHelper.getV2WikiPage(childKey, adminUserId, null);
fail("The wiki should have been deleted");
} catch (NotFoundException e) {
// this is expected
}
}
}
| services/repository/src/test/java/org/sagebionetworks/repo/web/controller/V2WikiControllerTest.java | package org.sagebionetworks.repo.web.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URL;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sagebionetworks.evaluation.model.Evaluation;
import org.sagebionetworks.evaluation.model.EvaluationStatus;
import org.sagebionetworks.repo.manager.NodeManager;
import org.sagebionetworks.repo.manager.UserManager;
import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.PaginatedResults;
import org.sagebionetworks.repo.model.Project;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.dao.FileHandleDao;
import org.sagebionetworks.repo.model.dao.WikiPageKey;
import org.sagebionetworks.repo.model.file.FileHandleResults;
import org.sagebionetworks.repo.model.file.PreviewFileHandle;
import org.sagebionetworks.repo.model.file.S3FileHandle;
import org.sagebionetworks.repo.model.jdo.KeyFactory;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage;
import org.sagebionetworks.repo.web.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class V2WikiControllerTest {
@Autowired
private EntityServletTestHelper entityServletHelper;
@Autowired
private UserManager userManager;
@Autowired
private NodeManager nodeManager;
@Autowired
private FileHandleDao fileMetadataDao;
private Long adminUserId;
private String adminUserIdString;
private Project entity;
private Evaluation evaluation;
private List<WikiPageKey> toDelete;
private S3FileHandle handleOne;
private S3FileHandle markdown;
private S3FileHandle markdownTwo;
private PreviewFileHandle handleTwo;
@Before
public void before() throws Exception{
// get user IDs
adminUserId = BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId();
adminUserIdString = adminUserId.toString();
toDelete = new LinkedList<WikiPageKey>();
// Create a file handle
handleOne = new S3FileHandle();
handleOne.setCreatedBy(adminUserIdString);
handleOne.setCreatedOn(new Date());
handleOne.setBucketName("bucket");
handleOne.setKey("mainFileKey");
handleOne.setEtag("etag");
handleOne.setFileName("foo.bar");
handleOne = fileMetadataDao.createFile(handleOne);
// Create a preview
handleTwo = new PreviewFileHandle();
handleTwo.setCreatedBy(adminUserIdString);
handleTwo.setCreatedOn(new Date());
handleTwo.setBucketName("bucket");
handleTwo.setKey("previewFileKey");
handleTwo.setEtag("etag");
handleTwo.setFileName("bar.txt");
handleTwo = fileMetadataDao.createFile(handleTwo);
// Set two as the preview of one
fileMetadataDao.setPreviewId(handleOne.getId(), handleTwo.getId());
markdown = new S3FileHandle();
markdown.setCreatedBy(adminUserIdString);
markdown.setCreatedOn(new Date());
markdown.setBucketName("bucket");
markdown.setKey("markdownKey");
markdown.setEtag("etag");
markdown.setFileName("markdown");
markdown = fileMetadataDao.createFile(markdown);
markdownTwo = new S3FileHandle();
markdownTwo.setCreatedBy(adminUserIdString);
markdownTwo.setCreatedOn(new Date());
markdownTwo.setBucketName("bucket");
markdownTwo.setKey("markdownKey2");
markdownTwo.setEtag("etag2");
markdownTwo.setFileName("markdown2");
markdownTwo = fileMetadataDao.createFile(markdownTwo);
}
@After
public void after() throws Exception{
for(WikiPageKey key: toDelete){
entityServletHelper.deleteV2WikiPage(key, adminUserId);
}
if(evaluation != null){
try {
entityServletHelper.deleteEvaluation(evaluation.getId(), adminUserId);
} catch (Exception e) {}
}
if(entity != null){
UserInfo userInfo = userManager.getUserInfo(adminUserId);
nodeManager.delete(userInfo, entity.getId());
}
if(handleOne != null && handleOne.getId() != null){
fileMetadataDao.delete(handleOne.getId());
}
if(handleTwo != null && handleTwo.getId() != null){
fileMetadataDao.delete(handleTwo.getId());
}
if(markdown != null && markdown.getId() != null) {
fileMetadataDao.delete(markdown.getId());
}
if(markdownTwo != null && markdownTwo.getId() != null) {
fileMetadataDao.delete(markdownTwo.getId());
}
}
@Test
public void testEntityWikiCRUD() throws Exception {
// create an entity
entity = new Project();
entity.setEntityType(Project.class.getName());
entity = (Project) entityServletHelper.createEntity(entity, adminUserId, null);
// Test all wiki CRUD for an entity
doWikiCRUDForOwnerObject(entity.getId(), ObjectType.ENTITY);
}
@Test
public void testCompetitionWikiCRUD() throws Exception {
// create an entity
evaluation = new Evaluation();
evaluation.setName("testCompetitionWikiCRUD");
evaluation.setContentSource(KeyFactory.SYN_ROOT_ID);
evaluation.setDescription("a test descrption");
evaluation.setStatus(EvaluationStatus.OPEN);
evaluation = entityServletHelper.createEvaluation(evaluation, adminUserId);
// Test all wiki CRUD for an entity
doWikiCRUDForOwnerObject(evaluation.getId(), ObjectType.EVALUATION);
}
/**
* Perform all Wiki CRUD for a given owner. This allows the same test to be run for each owner type.
* @param ownerId
* @param ownerType
* @throws Exception
*/
private void doWikiCRUDForOwnerObject(String ownerId, ObjectType ownerType) throws Exception{
// Create a wiki page
V2WikiPage wiki = new V2WikiPage();
wiki.setTitle("testCreateEntityWikiRoundTrip-"+ownerId+"-"+ownerType);
wiki.setMarkdownFileHandleId(markdown.getId());
wiki.setAttachmentFileHandleIds(new LinkedList<String>());
wiki = entityServletHelper.createV2WikiPage(adminUserId, ownerId, ownerType, wiki);
assertNotNull(wiki);
assertNotNull(wiki.getId());
WikiPageKey key = new WikiPageKey(ownerId, ownerType, wiki.getId());
toDelete.add(key);
assertNotNull(wiki.getEtag());
assertNotNull(ownerId, wiki.getModifiedBy());
assertNotNull(ownerId, wiki.getCreatedBy());
URL markdownPresigned = entityServletHelper.getV2WikiMarkdownFileURL(adminUserId, key, null, null);
assertNotNull(markdownPresigned);
assertTrue(markdownPresigned.toString().indexOf("markdownKey") > 0);
PaginatedResults<V2WikiHistorySnapshot> startHistory = entityServletHelper.getV2WikiHistory(key, adminUserId, new Long(0), new Long(10));
assertNotNull(startHistory);
List<V2WikiHistorySnapshot> firstSnapshot = startHistory.getResults();
assertNotNull(firstSnapshot);
assertEquals(1, firstSnapshot.size());
// Results are ordered, descending
// First snapshot is the most recent modification/highest version
assertEquals("0", firstSnapshot.get(0).getVersion());
// Get the wiki page.
V2WikiPage clone = entityServletHelper.getV2WikiPage(key, adminUserId, null);
assertNotNull(clone);
System.out.println(clone);
assertEquals(wiki, clone);
V2WikiPage getFirstVersion = entityServletHelper.getV2WikiPage(key, adminUserId, new Long(0));
assertEquals(wiki, getFirstVersion);
// Get the root wiki
V2WikiPage root = entityServletHelper.getRootV2WikiPage(ownerId, ownerType, adminUserId);
// The root should match the clone
assertEquals(clone, root);
// Update the wiki
clone.setMarkdownFileHandleId(markdownTwo.getId());
clone.getAttachmentFileHandleIds().add(handleOne.getId());
clone.setTitle("Version 1 title");
String currentEtag = clone.getEtag();
V2WikiPage cloneUpdated = entityServletHelper.updateWikiPage(adminUserId, ownerId, ownerType, clone);
assertNotNull(cloneUpdated);
assertEquals("Version 1 title", cloneUpdated.getTitle());
assertEquals(cloneUpdated.getMarkdownFileHandleId(), markdownTwo.getId());
assertEquals(cloneUpdated.getAttachmentFileHandleIds().size(), 1);
assertEquals(cloneUpdated.getAttachmentFileHandleIds().get(0), handleOne.getId());
assertFalse("The etag should have changed from the update", currentEtag.equals(cloneUpdated.getEtag()));
// Update one more time
cloneUpdated.getAttachmentFileHandleIds().add(handleTwo.getId());
cloneUpdated.setTitle("Version 2 title");
String currentEtag2 = cloneUpdated.getEtag();
V2WikiPage cloneUpdated2 = entityServletHelper.updateWikiPage(adminUserId, ownerId, ownerType, cloneUpdated);
assertNotNull(cloneUpdated2);
assertEquals(cloneUpdated2.getMarkdownFileHandleId(), markdownTwo.getId());
assertEquals(cloneUpdated2.getAttachmentFileHandleIds().size(), 2);
assertEquals(cloneUpdated2.getTitle(), "Version 2 title");
assertFalse("The etag should have changed from the update", currentEtag2.equals(cloneUpdated2.getEtag()));
URL markdownPresignedUpdated = entityServletHelper.getV2WikiMarkdownFileURL(adminUserId, key, new Long(0), null);
assertNotNull(markdownPresignedUpdated);
assertTrue(markdownPresignedUpdated.toString().indexOf("markdownKey") > 0);
Boolean redirectMarkdown = Boolean.FALSE;
markdownPresignedUpdated = entityServletHelper.getV2WikiMarkdownFileURL(adminUserId, key, new Long(0), redirectMarkdown);
assertNotNull(markdownPresignedUpdated);
assertTrue(markdownPresignedUpdated.toString().indexOf("markdownKey") > 0);
// Get history (there should be three snapshots returned)
PaginatedResults<V2WikiHistorySnapshot> historyResults = entityServletHelper.getV2WikiHistory(key, adminUserId, new Long(0), new Long(10));
assertNotNull(historyResults);
List<V2WikiHistorySnapshot> snapshots = historyResults.getResults();
assertNotNull(snapshots);
assertEquals(3, snapshots.size());
// Results are ordered, descending
// First snapshot is the most recent modification/highest version
assertEquals("2", snapshots.get(0).getVersion());
assertEquals("1", snapshots.get(1).getVersion());
assertEquals("0", snapshots.get(2).getVersion());
// First version should have no file handles
FileHandleResults oldHandles = entityServletHelper.getV2WikiFileHandles(adminUserId, key, new Long(0));
assertNotNull(oldHandles);
assertNotNull(oldHandles.getList());
assertEquals(0, oldHandles.getList().size());
Long versionToRestore = new Long(1);
// Get an older version
V2WikiPage versionOne = entityServletHelper.getV2WikiPage(key, adminUserId, versionToRestore);
assertEquals(markdownTwo.getId(), versionOne.getMarkdownFileHandleId());
assertEquals(1, versionOne.getAttachmentFileHandleIds().size());
// Get its attachment's URL
URL versionOneAttachment = entityServletHelper.getV2WikiAttachmentFileURL(userName, key, handleOne.getFileName(), null, new Long(1));
assertNotNull(versionOneAttachment);
assertTrue(versionOneAttachment.toString().indexOf("mainFileKey") > 0);
assertEquals("Version 1 title", versionOne.getTitle());
assertEquals(cloneUpdated.getModifiedOn(), versionOne.getModifiedOn());
// Restore wiki to version 1 which had markdownTwo and one file attachment, and a title of "Version 1 title"
String currentEtag3 = cloneUpdated2.getEtag();
V2WikiPage restored = entityServletHelper.restoreWikiPage(adminUserId, ownerId, ownerType, cloneUpdated2, versionToRestore);
assertNotNull(restored);
assertFalse("The etag should have changed from the restore", currentEtag3.equals(restored.getEtag()));
assertEquals(cloneUpdated2.getCreatedBy(), restored.getCreatedBy());
assertEquals(cloneUpdated2.getCreatedOn(), restored.getCreatedOn());
assertEquals(restored.getMarkdownFileHandleId(), markdownTwo.getId());
assertEquals(restored.getAttachmentFileHandleIds().size(), 1);
assertEquals(clone.getTitle(), restored.getTitle());
// Add a child wiki
V2WikiPage child = new V2WikiPage();
child.setTitle("Child");
child.setMarkdownFileHandleId(markdown.getId());
child.setParentWikiId(wiki.getId());
child.setAttachmentFileHandleIds(new LinkedList<String>());
// Note, we are adding a file handle with a preview.
// Both the S3FileHandle and its Preview should be returned from getWikiFileHandles()
child.getAttachmentFileHandleIds().add(handleOne.getId());
// Create child!
child = entityServletHelper.createV2WikiPage(adminUserId, ownerId, ownerType, child);
assertNotNull(child);
assertNotNull(child.getId());
WikiPageKey childKey = new WikiPageKey(ownerId, ownerType, child.getId());
toDelete.add(childKey);
// List the hierarchy
PaginatedResults<V2WikiHeader> paginated = entityServletHelper.getV2WikiHeaderTree(adminUserId, ownerId, ownerType);
assertNotNull(paginated);
assertNotNull(paginated.getResults());
assertEquals(2, paginated.getResults().size());
// check the root header.
V2WikiHeader rootHeader = paginated.getResults().get(0);
assertEquals(clone.getId(), rootHeader.getId());
assertEquals(clone.getTitle(), rootHeader.getTitle());
assertEquals(null, rootHeader.getParentId());
// Check the child header
V2WikiHeader childHeader = paginated.getResults().get(1);
assertEquals(child.getId(), childHeader.getId());
assertEquals(child.getTitle(), childHeader.getTitle());
assertEquals(wiki.getId(), childHeader.getParentId());
// Check that we can get the FileHandles
FileHandleResults handles = entityServletHelper.getV2WikiFileHandles(adminUserId, childKey, null);
assertNotNull(handles);
assertNotNull(handles.getList());
assertEquals(2, handles.getList().size());
// The first should be the S3FileHandle, the second should be the Preview.
assertEquals(handleOne.getId(), handles.getList().get(0).getId());
assertEquals(handleTwo.getId(), handles.getList().get(1).getId());
// Get the presigned URL for the first file
URL presigned = entityServletHelper.getV2WikiAttachmentFileURL(adminUserId, childKey, handleOne.getFileName(), null, null);
assertNotNull(presigned);
assertTrue(presigned.toString().indexOf("mainFileKey") > 0);
System.out.println(presigned);
// Get the preview presigned URL.
presigned = entityServletHelper.getV2WikiAttachmentPreviewFileURL(adminUserId, childKey, handleOne.getFileName(), null, null);
assertNotNull(presigned);
assertTrue(presigned.toString().indexOf("previewFileKey") > 0);
System.out.println(presigned);
// Make sure we can get the URLs without a redirect
Boolean redirect = Boolean.FALSE;
presigned = entityServletHelper.getV2WikiAttachmentFileURL(adminUserId, childKey, handleOne.getFileName(), redirect, null);
assertNotNull(presigned);
assertTrue(presigned.toString().indexOf("mainFileKey") > 0);
System.out.println(presigned);
// again without the redirct
presigned = entityServletHelper.getV2WikiAttachmentPreviewFileURL(adminUserId, childKey, handleOne.getFileName(), redirect, null);
assertNotNull(presigned);
assertTrue(presigned.toString().indexOf("previewFileKey") > 0);
System.out.println(presigned);
// Now delete the wiki
entityServletHelper.deleteV2WikiPage(key, adminUserId);
try {
entityServletHelper.getV2WikiPage(key, adminUserId, null);
fail("The wiki should have been deleted");
} catch (NotFoundException e) {
// this is expected
}
// the child should be delete as well
try {
entityServletHelper.getV2WikiPage(childKey, adminUserId, null);
fail("The wiki should have been deleted");
} catch (NotFoundException e) {
// this is expected
}
}
}
| Fix compilation error
| services/repository/src/test/java/org/sagebionetworks/repo/web/controller/V2WikiControllerTest.java | Fix compilation error | <ide><path>ervices/repository/src/test/java/org/sagebionetworks/repo/web/controller/V2WikiControllerTest.java
<ide> assertEquals(markdownTwo.getId(), versionOne.getMarkdownFileHandleId());
<ide> assertEquals(1, versionOne.getAttachmentFileHandleIds().size());
<ide> // Get its attachment's URL
<del> URL versionOneAttachment = entityServletHelper.getV2WikiAttachmentFileURL(userName, key, handleOne.getFileName(), null, new Long(1));
<add> URL versionOneAttachment = entityServletHelper.getV2WikiAttachmentFileURL(adminUserId, key, handleOne.getFileName(), null, new Long(1));
<ide> assertNotNull(versionOneAttachment);
<ide> assertTrue(versionOneAttachment.toString().indexOf("mainFileKey") > 0);
<ide> |
|
Java | mit | 2464732114c4c5b59fc966f20ae9e41c7ddb2346 | 0 | saxman/android-map_list,androidcodegeeks/android-map_list,chathudan/android-map_list | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.google.maplist;
import com.google.android.gms.maps.model.LatLng;
public class MapLocation {
public String name;
public LatLng center;
@SuppressWarnings("unused")
public MapLocation() {}
public MapLocation(String name, double lat, double lng) {
this.name = name;
this.center = new LatLng(lat, lng);
}
}
| app/src/main/java/com/example/google/maplist/MapLocation.java | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.google.maplist;
import com.google.android.gms.maps.model.LatLng;
public class MapLocation {
public String name;
public LatLng center;
public MapLocation(String name, double lat, double lng) {
this.name = name;
this.center = new LatLng(lat, lng);
}
}
| Added default constructor to allow for subclassing
| app/src/main/java/com/example/google/maplist/MapLocation.java | Added default constructor to allow for subclassing | <ide><path>pp/src/main/java/com/example/google/maplist/MapLocation.java
<ide> public String name;
<ide> public LatLng center;
<ide>
<add> @SuppressWarnings("unused")
<add> public MapLocation() {}
<add>
<ide> public MapLocation(String name, double lat, double lng) {
<ide> this.name = name;
<ide> this.center = new LatLng(lat, lng); |
|
Java | apache-2.0 | 6556c779dfe583063a23fa5a2cfc03750fba697d | 0 | SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.examples.todolist.tasks;
/**
* Provides constants for the Tasks context.
*/
public final class TasksContext {
/** The name of the Tasks context. */
public static final String NAME = "Tasks";
/** Prevents instantiation of this utility class. */
private TasksContext() {
}
}
| tasks/src/main/java/io/spine/examples/todolist/tasks/TasksContext.java | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.examples.todolist.tasks;
/**
* Provides constants for the Tasks context.
*/
public class TasksContext {
/** The name of the Tasks context. */
public static final String NAME = "Tasks";
/** Prevents instantiation of this utility class. */
private TasksContext() {
}
}
| Make class final
| tasks/src/main/java/io/spine/examples/todolist/tasks/TasksContext.java | Make class final | <ide><path>asks/src/main/java/io/spine/examples/todolist/tasks/TasksContext.java
<ide> /**
<ide> * Provides constants for the Tasks context.
<ide> */
<del>public class TasksContext {
<add>public final class TasksContext {
<ide>
<ide> /** The name of the Tasks context. */
<ide> public static final String NAME = "Tasks"; |
|
Java | apache-2.0 | error: pathspec 'java/BestTimeBuySellStock.java' did not match any file(s) known to git
| 863cb40ed536eb76ea4e0fc1419872a8803f3bbf | 1 | robertzm/algotest | public class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if(len <= 1){
return 0;
}
int bday = 0, sday = 0, fday = 0;
for(int i = 1; i < len; i ++){
if(prices[i] > prices[sday]){
sday = i;
}
if((prices[i] - prices[fday]) > (prices[sday] - prices[bday])){
bday = fday;
sday = i;
}
if(prices[i] < prices[fday]){
fday = i;
}
}
return (int)(prices[sday] - prices[bday]);
}
} | java/BestTimeBuySellStock.java | Q121 Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given
stock on day i.
If you were only permitted to complete at most one transaction (ie, buy
one and sell one share of the stock), design an algorithm to find the
maximum profit.
| java/BestTimeBuySellStock.java | Q121 Best Time to Buy and Sell Stock | <ide><path>ava/BestTimeBuySellStock.java
<add>public class Solution {
<add> public int maxProfit(int[] prices) {
<add> int len = prices.length;
<add> if(len <= 1){
<add> return 0;
<add> }
<add> int bday = 0, sday = 0, fday = 0;
<add> for(int i = 1; i < len; i ++){
<add> if(prices[i] > prices[sday]){
<add> sday = i;
<add> }
<add> if((prices[i] - prices[fday]) > (prices[sday] - prices[bday])){
<add> bday = fday;
<add> sday = i;
<add> }
<add> if(prices[i] < prices[fday]){
<add> fday = i;
<add> }
<add>
<add> }
<add> return (int)(prices[sday] - prices[bday]);
<add> }
<add>} |
|
Java | agpl-3.0 | ef2aed5c53cb2e2826527b0f4271dbeed6b0171f | 0 | githubfun/rstudio,jzhu8803/rstudio,maligulzar/Rstudio-instrumented,jar1karp/rstudio,piersharding/rstudio,maligulzar/Rstudio-instrumented,JanMarvin/rstudio,sfloresm/rstudio,sfloresm/rstudio,more1/rstudio,nvoron23/rstudio,suribes/rstudio,edrogers/rstudio,vbelakov/rstudio,githubfun/rstudio,tbarrongh/rstudio,tbarrongh/rstudio,jzhu8803/rstudio,brsimioni/rstudio,JanMarvin/rstudio,nvoron23/rstudio,nvoron23/rstudio,thklaus/rstudio,jar1karp/rstudio,john-r-mcpherson/rstudio,sfloresm/rstudio,jrnold/rstudio,pssguy/rstudio,maligulzar/Rstudio-instrumented,githubfun/rstudio,githubfun/rstudio,jrnold/rstudio,john-r-mcpherson/rstudio,more1/rstudio,sfloresm/rstudio,jrnold/rstudio,more1/rstudio,vbelakov/rstudio,vbelakov/rstudio,piersharding/rstudio,piersharding/rstudio,brsimioni/rstudio,suribes/rstudio,jar1karp/rstudio,JanMarvin/rstudio,tbarrongh/rstudio,jrnold/rstudio,edrogers/rstudio,brsimioni/rstudio,jzhu8803/rstudio,maligulzar/Rstudio-instrumented,JanMarvin/rstudio,suribes/rstudio,jrnold/rstudio,thklaus/rstudio,more1/rstudio,pssguy/rstudio,piersharding/rstudio,john-r-mcpherson/rstudio,brsimioni/rstudio,thklaus/rstudio,jrnold/rstudio,maligulzar/Rstudio-instrumented,brsimioni/rstudio,piersharding/rstudio,jrnold/rstudio,suribes/rstudio,more1/rstudio,piersharding/rstudio,maligulzar/Rstudio-instrumented,jar1karp/rstudio,jzhu8803/rstudio,pssguy/rstudio,tbarrongh/rstudio,john-r-mcpherson/rstudio,vbelakov/rstudio,sfloresm/rstudio,vbelakov/rstudio,githubfun/rstudio,nvoron23/rstudio,sfloresm/rstudio,JanMarvin/rstudio,thklaus/rstudio,githubfun/rstudio,jzhu8803/rstudio,jrnold/rstudio,pssguy/rstudio,suribes/rstudio,jrnold/rstudio,sfloresm/rstudio,brsimioni/rstudio,jzhu8803/rstudio,tbarrongh/rstudio,edrogers/rstudio,jar1karp/rstudio,JanMarvin/rstudio,john-r-mcpherson/rstudio,maligulzar/Rstudio-instrumented,JanMarvin/rstudio,piersharding/rstudio,edrogers/rstudio,maligulzar/Rstudio-instrumented,more1/rstudio,githubfun/rstudio,thklaus/rstudio,more1/rstudio,suribes/rstudio,JanMarvin/rstudio,edrogers/rstudio,thklaus/rstudio,vbelakov/rstudio,nvoron23/rstudio,jar1karp/rstudio,jzhu8803/rstudio,pssguy/rstudio,vbelakov/rstudio,john-r-mcpherson/rstudio,thklaus/rstudio,pssguy/rstudio,brsimioni/rstudio,suribes/rstudio,john-r-mcpherson/rstudio,pssguy/rstudio,pssguy/rstudio,jzhu8803/rstudio,more1/rstudio,maligulzar/Rstudio-instrumented,nvoron23/rstudio,jar1karp/rstudio,suribes/rstudio,thklaus/rstudio,john-r-mcpherson/rstudio,githubfun/rstudio,sfloresm/rstudio,edrogers/rstudio,edrogers/rstudio,brsimioni/rstudio,tbarrongh/rstudio,piersharding/rstudio,piersharding/rstudio,edrogers/rstudio,JanMarvin/rstudio,nvoron23/rstudio,tbarrongh/rstudio,jar1karp/rstudio,vbelakov/rstudio,jar1karp/rstudio,tbarrongh/rstudio | /*
* RCompletionManager.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.console.shell.assist;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.inject.Inject;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.Invalidation;
import org.rstudio.core.client.Rectangle;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.KeyboardShortcut;
import org.rstudio.core.client.events.SelectionCommitEvent;
import org.rstudio.core.client.events.SelectionCommitHandler;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.GlobalProgressDelayer;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations;
import org.rstudio.studio.client.common.codetools.RCompletionType;
import org.rstudio.studio.client.common.filetypes.DocumentMode;
import org.rstudio.studio.client.common.filetypes.FileTypeRegistry;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.codesearch.CodeSearchOracle;
import org.rstudio.studio.client.workbench.codesearch.model.FunctionDefinition;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionRequester.CompletionResult;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionRequester.QualifiedName;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorLineWithCursorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorUtil;
import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay;
import org.rstudio.studio.client.workbench.views.source.editors.text.NavigableSourceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.RCompletionContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.CodeModel;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.DplyrJoinContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.RInfixData;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.TokenCursor;
import org.rstudio.studio.client.workbench.views.source.editors.text.r.RCompletionToolTip;
import org.rstudio.studio.client.workbench.views.source.events.CodeBrowserNavigationEvent;
import org.rstudio.studio.client.workbench.views.source.model.RnwCompletionContext;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class RCompletionManager implements CompletionManager
{
// globally suppress F1 and F2 so no default browser behavior takes those
// keystrokes (e.g. Help in Chrome)
static
{
Event.addNativePreviewHandler(new NativePreviewHandler() {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{
if (event.getTypeInt() == Event.ONKEYDOWN)
{
int keyCode = event.getNativeEvent().getKeyCode();
if ((keyCode == 112 || keyCode == 113) &&
KeyboardShortcut.NONE ==
KeyboardShortcut.getModifierValue(event.getNativeEvent()))
{
event.getNativeEvent().preventDefault();
}
}
}
});
}
public RCompletionManager(InputEditorDisplay input,
NavigableSourceEditor navigableSourceEditor,
CompletionPopupDisplay popup,
CodeToolsServerOperations server,
InitCompletionFilter initFilter,
RCompletionContext rContext,
RnwCompletionContext rnwContext,
DocDisplay docDisplay,
boolean isConsole)
{
RStudioGinjector.INSTANCE.injectMembers(this);
input_ = input ;
navigableSourceEditor_ = navigableSourceEditor;
popup_ = popup ;
server_ = server ;
requester_ = new CompletionRequester(server_, rnwContext, navigableSourceEditor);
initFilter_ = initFilter ;
rContext_ = rContext;
rnwContext_ = rnwContext;
docDisplay_ = docDisplay;
isConsole_ = isConsole;
sigTip_ = new RCompletionToolTip(docDisplay_);
suggestTimer_ = new SuggestionTimer();
input_.addBlurHandler(new BlurHandler() {
public void onBlur(BlurEvent event)
{
if (!ignoreNextInputBlur_)
invalidatePendingRequests() ;
ignoreNextInputBlur_ = false ;
}
}) ;
input_.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
invalidatePendingRequests();
}
});
popup_.addSelectionCommitHandler(new SelectionCommitHandler<QualifiedName>() {
public void onSelectionCommit(SelectionCommitEvent<QualifiedName> event)
{
assert context_ != null : "onSelection called but handler is null" ;
if (context_ != null)
context_.onSelection(event.getSelectedItem()) ;
}
}) ;
popup_.addSelectionHandler(new SelectionHandler<QualifiedName>() {
public void onSelection(SelectionEvent<QualifiedName> event)
{
lastSelectedItem_ = event.getSelectedItem();
if (popup_.isHelpVisible())
context_.showHelp(lastSelectedItem_);
else
showHelpDeferred(context_, lastSelectedItem_, 600);
}
}) ;
popup_.addMouseDownHandler(new MouseDownHandler() {
public void onMouseDown(MouseDownEvent event)
{
ignoreNextInputBlur_ = true ;
}
});
popup_.addSelectionHandler(new SelectionHandler<QualifiedName>() {
@Override
public void onSelection(SelectionEvent<QualifiedName> event)
{
docDisplay_.setPopupVisible(true);
}
});
popup_.addCloseHandler(new CloseHandler<PopupPanel>()
{
@Override
public void onClose(CloseEvent<PopupPanel> event)
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
docDisplay_.setPopupVisible(false);
}
});
}
});
}
@Inject
public void initialize(GlobalDisplay globalDisplay,
FileTypeRegistry fileTypeRegistry,
EventBus eventBus,
HelpStrategy helpStrategy,
UIPrefs uiPrefs)
{
globalDisplay_ = globalDisplay;
fileTypeRegistry_ = fileTypeRegistry;
eventBus_ = eventBus;
helpStrategy_ = helpStrategy;
uiPrefs_ = uiPrefs;
}
public void close()
{
popup_.hide();
}
public void codeCompletion()
{
if (initFilter_ == null || initFilter_.shouldComplete(null))
beginSuggest(true, false, true);
}
public void goToHelp()
{
InputEditorLineWithCursorPosition linePos =
InputEditorUtil.getLineWithCursorPosition(input_);
server_.getHelpAtCursor(
linePos.getLine(), linePos.getPosition(),
new SimpleRequestCallback<Void>("Help"));
}
public void goToFunctionDefinition()
{
// determine current line and cursor position
InputEditorLineWithCursorPosition lineWithPos =
InputEditorUtil.getLineWithCursorPosition(input_);
// lookup function definition at this location
// delayed progress indicator
final GlobalProgressDelayer progress = new GlobalProgressDelayer(
globalDisplay_, 1000, "Searching for function definition...");
server_.getFunctionDefinition(
lineWithPos.getLine(),
lineWithPos.getPosition(),
new ServerRequestCallback<FunctionDefinition>() {
@Override
public void onResponseReceived(FunctionDefinition def)
{
// dismiss progress
progress.dismiss();
// if we got a hit
if (def.getFunctionName() != null)
{
// search locally if a function navigator was provided
if (navigableSourceEditor_ != null)
{
// try to search for the function locally
SourcePosition position =
navigableSourceEditor_.findFunctionPositionFromCursor(
def.getFunctionName());
if (position != null)
{
navigableSourceEditor_.navigateToPosition(position,
true);
return; // we're done
}
}
// if we didn't satisfy the request using a function
// navigator and we got a file back from the server then
// navigate to the file/loc
if (def.getFile() != null)
{
fileTypeRegistry_.editFile(def.getFile(),
def.getPosition());
}
// if we didn't get a file back see if we got a
// search path definition
else if (def.getSearchPathFunctionDefinition() != null)
{
eventBus_.fireEvent(new CodeBrowserNavigationEvent(
def.getSearchPathFunctionDefinition()));
}
}
}
@Override
public void onError(ServerError error)
{
progress.dismiss();
globalDisplay_.showErrorMessage("Error Searching for Function",
error.getUserMessage());
}
});
}
public boolean previewKeyDown(NativeEvent event)
{
suggestTimer_.cancel();
if (sigTip_ != null)
if (sigTip_.previewKeyDown(event))
return true;
/**
* KEYS THAT MATTER
*
* When popup not showing:
* Tab - attempt completion (handled in Console.java)
*
* When popup showing:
* Esc - dismiss popup
* Enter/Tab/Right-arrow - accept current selection
* Up-arrow/Down-arrow - change selected item
* Left-arrow - dismiss popup
* [identifier] - narrow suggestions--or if we're lame, just dismiss
* All others - dismiss popup
*/
nativeEvent_ = event;
int keycode = event.getKeyCode();
int modifier = KeyboardShortcut.getModifierValue(event);
if (!popup_.isShowing())
{
if (CompletionUtils.isCompletionRequest(event, modifier))
{
if (initFilter_ == null || initFilter_.shouldComplete(event))
{
// If we're in markdown mode, only autocomplete in '```{r',
// '[](', or '`r |' contexts
if (DocumentMode.isCursorInMarkdownMode(docDisplay_))
{
String currentLine = docDisplay_.getCurrentLineUpToCursor();
if (!(Pattern.create("^```{[rR]").test(currentLine) ||
Pattern.create(".*\\[.*\\]\\(").test(currentLine) ||
(Pattern.create(".*`r").test(currentLine) &&
StringUtil.countMatches(currentLine, '`') % 2 == 1)))
return false;
}
// If we're in tex mode, only provide completions in chunks
if (DocumentMode.isCursorInTexMode(docDisplay_))
{
String currentLine = docDisplay_.getCurrentLineUpToCursor();
if (!Pattern.create("^<<").test(currentLine))
return false;
}
return beginSuggest(true, false, true);
}
}
else if (keycode == 112 // F1
&& modifier == KeyboardShortcut.NONE)
{
goToHelp();
}
else if (keycode == 113 // F2
&& modifier == KeyboardShortcut.NONE)
{
goToFunctionDefinition();
}
}
else
{
switch (keycode)
{
// chrome on ubuntu now sends this before every keydown
// so we need to explicitly ignore it. see:
// https://github.com/ivaynberg/select2/issues/2482
case KeyCodes.KEY_WIN_IME:
return false ;
case KeyCodes.KEY_SHIFT:
case KeyCodes.KEY_CTRL:
case KeyCodes.KEY_ALT:
case KeyCodes.KEY_MAC_FF_META:
case KeyCodes.KEY_WIN_KEY_LEFT_META:
return false ; // bare modifiers should do nothing
}
if (modifier == KeyboardShortcut.NONE)
{
if (keycode == KeyCodes.KEY_ESCAPE)
{
invalidatePendingRequests() ;
return true ;
}
// NOTE: It is possible for the popup to still be showing, but
// showing offscreen with no values. We only grab these keys
// when the popup is both showing, and has completions.
// This functionality is here to ensure backspace works properly;
// e.g "stats::rna" -> "stats::rn" brings completions if the user
// had originally requested completions at e.g. "stats::".
if (popup_.hasCompletions() && !popup_.isOffscreen())
{
if (keycode == KeyCodes.KEY_ENTER)
{
QualifiedName value = popup_.getSelectedValue() ;
if (value != null)
{
context_.onSelection(value) ;
return true ;
}
}
else if (keycode == KeyCodes.KEY_TAB ||
keycode == KeyCodes.KEY_RIGHT)
{
QualifiedName value = popup_.getSelectedValue() ;
if (value != null)
{
if (value.type == RCompletionType.DIRECTORY)
context_.suggestOnAccept_ = true;
context_.onSelection(value);
return true;
}
}
else if (keycode == KeyCodes.KEY_UP)
return popup_.selectPrev() ;
else if (keycode == KeyCodes.KEY_DOWN)
return popup_.selectNext() ;
else if (keycode == KeyCodes.KEY_PAGEUP)
return popup_.selectPrevPage() ;
else if (keycode == KeyCodes.KEY_PAGEDOWN)
return popup_.selectNextPage() ;
else if (keycode == KeyCodes.KEY_HOME)
return popup_.selectFirst() ;
else if (keycode == KeyCodes.KEY_END)
return popup_.selectLast() ;
else if (keycode == KeyCodes.KEY_LEFT)
{
invalidatePendingRequests() ;
return true ;
}
if (keycode == 112) // F1
{
context_.showHelpTopic() ;
return true ;
}
else if (keycode == 113) // F2
{
goToFunctionDefinition();
return true;
}
}
}
if (canContinueCompletions(event))
return false;
// if we insert a '/', we're probably forming a directory --
// pop up completions
if (keycode == 191 && modifier == KeyboardShortcut.NONE)
{
input_.insertCode("/");
return beginSuggest(true, true, false);
}
// continue showing completions on backspace
if (keycode == KeyCodes.KEY_BACKSPACE && modifier == KeyboardShortcut.NONE)
{
int cursorColumn = input_.getCursorPosition().getColumn();
String currentLine = docDisplay_.getCurrentLine();
// only suggest if the character previous to the cursor is an R identifier
// also halt suggestions if we're about to remove the only character on the line
if (cursorColumn > 0)
{
char ch = currentLine.charAt(cursorColumn - 2);
char prevCh = currentLine.charAt(cursorColumn - 3);
boolean isAcceptableCharSequence = isValidForRIdentifier(ch) ||
(ch == ':' && prevCh == ':') ||
ch == '$' ||
ch == '@' ||
ch == '/'; // for file completions
if (currentLine.length() > 0 &&
cursorColumn > 0 &&
isAcceptableCharSequence)
{
// manually remove the previous character
InputEditorSelection selection = input_.getSelection();
InputEditorPosition start = selection.getStart().movePosition(-1, true);
InputEditorPosition end = selection.getStart();
if (currentLine.charAt(cursorColumn) == ')' && currentLine.charAt(cursorColumn - 1) == '(')
{
// flush cache as old completions no longer relevant
requester_.flushCache();
end = selection.getStart().movePosition(1, true);
}
input_.setSelection(new InputEditorSelection(start, end));
input_.replaceSelection("", false);
return beginSuggest(false, false, false);
}
}
else
{
invalidatePendingRequests();
return true;
}
}
invalidatePendingRequests();
return false ;
}
return false ;
}
private boolean isValidForRIdentifier(char c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c == '.') ||
(c == '_');
}
private boolean checkCanAutoPopup(char c, int lookbackLimit)
{
String currentLine = docDisplay_.getCurrentLine();
Position cursorPos = input_.getCursorPosition();
int cursorColumn = cursorPos.getColumn();
// Don't auto-popup when the cursor is within a string
if (docDisplay_.isCursorInSingleLineString())
return false;
// Grab the current token on the line
String currentToken = StringUtil.getToken(
currentLine, cursorColumn, "^[a-zA-Z0-9._'\"`]$", false, false);
// Don't auto-popup for common keywords + symbols
String[] keywords = {
"for", "if", "in", "function", "while", "repeat",
"break", "switch", "return", "library", "require",
"TRUE", "FALSE"
};
for (String keyword : keywords)
if (currentToken.length() <= keyword.length() &&
keyword.substring(0, currentToken.length()).equals(currentToken))
return false;
boolean canAutoPopup =
(currentLine.length() > lookbackLimit - 1 && isValidForRIdentifier(c));
if (isConsole_ && !uiPrefs_.alwaysCompleteInConsole().getValue())
canAutoPopup = false;
if (canAutoPopup)
{
for (int i = 0; i < lookbackLimit; i++)
{
if (!isValidForRIdentifier(currentLine.charAt(cursorColumn - i - 1)))
{
canAutoPopup = false;
break;
}
}
}
return canAutoPopup;
}
public boolean previewKeyPress(char c)
{
suggestTimer_.cancel();
if (popup_.isShowing())
{
// If insertion of this character completes an available suggestion,
// and is not a prefix match of any other suggestion, then implicitly
// apply that.
QualifiedName selectedItem =
popup_.getSelectedValue();
if (selectedItem != null &&
selectedItem.name.equals(token_ + c))
{
String fullToken = token_ + c;
// Find prefix matches -- there should only be one if we really
// want this behaviour (ie the current selection)
int prefixMatchCount = 0;
QualifiedName[] items = popup_.getItems();
for (int i = 0; i < items.length; i++)
{
if (items[i].name.startsWith(fullToken))
{
++prefixMatchCount;
if (prefixMatchCount > 1)
break;
}
}
if (prefixMatchCount == 1)
{
// We place the completion list offscreen to ensure that
// backspace events are handled later.
popup_.placeOffscreen();
return false;
}
}
if (isValidForRIdentifier(c))
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(false, true, false);
}
});
}
if (c == ':')
{
suggestTimer_.schedule(false, true, false);
}
}
else
{
// Bail if we're not in R mode
if (!DocumentMode.isCursorInRMode(docDisplay_))
return false;
// Perform an auto-popup if a set number of R identifier characters
// have been inserted (but only if the user has allowed it in prefs)
boolean autoPopupEnabled = uiPrefs_.codeComplete().getValue().equals(
UIPrefsAccessor.COMPLETION_ALWAYS);
if (!autoPopupEnabled)
return false;
// Check for a valid number of R identifier characters for autopopup
boolean canAutoPopup = checkCanAutoPopup(c, 4);
char prevChar = docDisplay_.getCurrentLine().charAt(
input_.getCursorPosition().getColumn() - 1);
// Automatically popup completions after certain function calls
if (c == '(' && !isLineInComment(docDisplay_.getCurrentLine()))
{
String token = StringUtil.getToken(
docDisplay_.getCurrentLine(),
input_.getCursorPosition().getColumn(),
"[a-zA-Z0-9._]",
false,
true);
QualifiedName lastSelectedItem = popup_.getLastSelectedValue();
if (lastSelectedItem != null)
{
if (lastSelectedItem.name.equals(token))
displaySignatureToolTip(lastSelectedItem);
}
if (token.matches("^(library|require|requireNamespace|data)\\s*$"))
canAutoPopup = true;
}
if (
(canAutoPopup) ||
(c == ':' && prevChar == ':') ||
(c == '$') ||
(c == '@') ||
isSweaveCompletion(c))
{
// Delay suggestion to avoid auto-popup while the user is typing
suggestTimer_.schedule(true, true, false);
}
else if (CompletionUtils.handleEncloseSelection(input_, c))
{
return true;
}
}
return false ;
}
@SuppressWarnings("unused")
private boolean isRoxygenTagValidHere()
{
if (input_.getText().matches("\\s*#+'.*"))
{
String linePart = input_.getText().substring(0, input_.getSelection().getStart().getPosition());
if (linePart.matches("\\s*#+'\\s*"))
return true;
}
return false;
}
private boolean isSweaveCompletion(char c)
{
if (rnwContext_ == null || (c != ',' && c != ' ' && c != '='))
return false;
int optionsStart = rnwContext_.getRnwOptionsStart(
input_.getText(),
input_.getSelection().getStart().getPosition());
if (optionsStart < 0)
{
return false;
}
String linePart = input_.getText().substring(
optionsStart,
input_.getSelection().getStart().getPosition());
return c != ' ' || linePart.matches(".*,\\s*");
}
private static boolean canContinueCompletions(NativeEvent event)
{
if (event.getAltKey()
|| event.getCtrlKey()
|| event.getMetaKey())
{
return false ;
}
int keyCode = event.getKeyCode() ;
if (keyCode >= 'a' && keyCode <= 'z')
return true ;
if (keyCode >= 'A' && keyCode <= 'Z')
return true ;
if (keyCode == ' ')
return true ;
if (keyCode == 189) // dash
return true ;
if (keyCode == 189 && event.getShiftKey()) // underscore
return true ;
if (event.getShiftKey())
return false ;
if (keyCode >= '0' && keyCode <= '9')
return true ;
if (keyCode == 190) // period
return true ;
return false ;
}
private void invalidatePendingRequests()
{
invalidatePendingRequests(true, true);
}
private void invalidatePendingRequests(boolean flushCache,
boolean hidePopup)
{
invalidation_.invalidate();
if (hidePopup && popup_.isShowing())
{
popup_.hide();
popup_.clearHelp(false);
}
if (flushCache)
requester_.flushCache() ;
}
// Things we need to form an appropriate autocompletion:
//
// 1. The token to the left of the cursor,
// 2. The associated function call (if any -- for arguments),
// 3. The associated data for a `[` call (if any -- completions from data object),
// 4. The associated data for a `[[` call (if any -- completions from data object)
class AutocompletionContext {
// Be sure to sync these with 'SessionCodeTools.R'!
public static final int TYPE_UNKNOWN = 0;
public static final int TYPE_FUNCTION = 1;
public static final int TYPE_SINGLE_BRACKET = 2;
public static final int TYPE_DOUBLE_BRACKET = 3;
public static final int TYPE_NAMESPACE_EXPORTED = 4;
public static final int TYPE_NAMESPACE_ALL = 5;
public static final int TYPE_DOLLAR = 6;
public static final int TYPE_AT = 7;
public static final int TYPE_FILE = 8;
public static final int TYPE_CHUNK = 9;
public static final int TYPE_ROXYGEN = 10;
public static final int TYPE_HELP = 11;
public static final int TYPE_ARGUMENT = 12;
public AutocompletionContext(
String token,
List<String> assocData,
List<Integer> dataType,
List<Integer> numCommas,
String functionCallString)
{
token_ = token;
assocData_ = assocData;
dataType_ = dataType;
numCommas_ = numCommas;
functionCallString_ = functionCallString;
}
public AutocompletionContext(
String token,
ArrayList<String> assocData,
ArrayList<Integer> dataType)
{
token_ = token;
assocData_ = assocData;
dataType_ = dataType;
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext(
String token,
String assocData,
int dataType)
{
token_ = token;
assocData_ = Arrays.asList(assocData);
dataType_ = Arrays.asList(dataType);
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext(
String token,
int dataType)
{
token_ = token;
assocData_ = Arrays.asList("");
dataType_ = Arrays.asList(dataType);
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext()
{
token_ = "";
assocData_ = new ArrayList<String>();
dataType_ = new ArrayList<Integer>();
numCommas_ = new ArrayList<Integer>();
functionCallString_ = "";
}
public String getToken()
{
return token_;
}
public void setToken(String token)
{
this.token_ = token;
}
public List<String> getAssocData()
{
return assocData_;
}
public void setAssocData(List<String> assocData)
{
this.assocData_ = assocData;
}
public List<Integer> getDataType()
{
return dataType_;
}
public void setDataType(List<Integer> dataType)
{
this.dataType_ = dataType;
}
public List<Integer> getNumCommas()
{
return numCommas_;
}
public void setNumCommas(List<Integer> numCommas)
{
this.numCommas_ = numCommas;
}
public String getFunctionCallString()
{
return functionCallString_;
}
public void setFunctionCallString(String functionCallString)
{
this.functionCallString_ = functionCallString;
}
public void add(String assocData, Integer dataType, Integer numCommas)
{
assocData_.add(assocData);
dataType_.add(dataType);
numCommas_.add(numCommas);
}
public void add(String assocData, Integer dataType)
{
add(assocData, dataType, 0);
}
public void add(String assocData)
{
add(assocData, AutocompletionContext.TYPE_UNKNOWN, 0);
}
private String token_;
private List<String> assocData_;
private List<Integer> dataType_;
private List<Integer> numCommas_;
private String functionCallString_;
}
private boolean isLineInRoxygenComment(String line)
{
return line.matches("^\\s*#+'\\s*[^\\s].*");
}
private boolean isLineInComment(String line)
{
return StringUtil.stripBalancedQuotes(line).contains("#");
}
/**
* If false, the suggest operation was aborted
*/
private boolean beginSuggest(boolean flushCache,
boolean implicit,
boolean canAutoInsert)
{
suggestTimer_.cancel();
if (!input_.isSelectionCollapsed())
return false ;
invalidatePendingRequests(flushCache, false);
InputEditorSelection selection = input_.getSelection() ;
if (selection == null)
return false;
int cursorCol = selection.getStart().getPosition();
String firstLine = input_.getText().substring(0, cursorCol);
// never autocomplete in (non-roxygen) comments, or at the start
// of roxygen comments (e.g. at "#' |")
if (isLineInComment(firstLine) && !isLineInRoxygenComment(firstLine))
return false;
// don't auto-complete with tab on lines with only whitespace,
// if the insertion character was a tab (unless the user has opted in)
if (!uiPrefs_.allowTabMultilineCompletion().getValue())
{
if (nativeEvent_ != null &&
nativeEvent_.getKeyCode() == KeyCodes.KEY_TAB)
if (firstLine.matches("^\\s*$"))
return false;
}
AutocompletionContext context = getAutocompletionContext();
context_ = new CompletionRequestContext(invalidation_.getInvalidationToken(),
selection,
canAutoInsert);
RInfixData infixData = RInfixData.create();
AceEditor editor = (AceEditor) docDisplay_;
if (editor != null)
{
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
TokenCursor cursor = codeModel.getTokenCursor();
if (cursor.moveToPosition(input_.getCursorPosition()))
{
String token = "";
if (cursor.currentType() == "identifier")
token = cursor.currentValue();
String cursorPos = "left";
if (cursor.currentValue() == "=")
cursorPos = "right";
TokenCursor clone = cursor.cloneCursor();
if (clone.moveToPreviousToken())
if (clone.currentValue() == "=")
cursorPos = "right";
// Try to get a dplyr join completion
DplyrJoinContext joinContext =
codeModel.getDplyrJoinContextFromInfixChain(cursor);
// If that failed, try a non-infix lookup
if (joinContext == null)
{
String joinString =
getDplyrJoinString(editor, cursor);
if (!StringUtil.isNullOrEmpty(joinString))
{
requester_.getDplyrJoinCompletionsString(
token,
joinString,
cursorPos,
implicit,
context_);
return true;
}
}
else
{
requester_.getDplyrJoinCompletions(
joinContext,
implicit,
context_);
return true;
}
// Try to see if there's an object name we should use to supplement
// completions
if (cursor.moveToPosition(input_.getCursorPosition()))
infixData = codeModel.getDataFromInfixChain(cursor);
}
}
String filePath = getSourceDocumentPath();
if (filePath == null)
filePath = "";
requester_.getCompletions(
context.getToken(),
context.getAssocData(),
context.getDataType(),
context.getNumCommas(),
context.getFunctionCallString(),
infixData.getDataName(),
infixData.getAdditionalArgs(),
infixData.getExcludeArgs(),
infixData.getExcludeArgsFromObject(),
filePath,
implicit,
context_);
return true ;
}
private String getDplyrJoinString(
AceEditor editor,
TokenCursor cursor)
{
while (true)
{
int commaCount = cursor.findOpeningBracketCountCommas("(", true);
if (commaCount == -1)
break;
if (!cursor.moveToPreviousToken())
return "";
if (!cursor.currentValue().matches(".*join$"))
continue;
if (commaCount < 2)
return "";
Position start = cursor.currentPosition();
if (!cursor.moveToNextToken())
return "";
if (!cursor.fwdToMatchingToken())
return "";
Position end = cursor.currentPosition();
end.setColumn(end.getColumn() + 1);
return editor.getTextForRange(Range.fromPoints(
start, end));
}
return "";
}
private void addAutocompletionContextForFile(AutocompletionContext context,
String line)
{
int index = Math.max(line.lastIndexOf('"'), line.lastIndexOf('\''));
String token = line.substring(index + 1);
context.add(token, AutocompletionContext.TYPE_FILE);
context.setToken(token);
}
private AutocompletionContext getAutocompletionContextForFileMarkdownLink(
String line)
{
int index = line.lastIndexOf('(');
String token = line.substring(index + 1);
AutocompletionContext result = new AutocompletionContext(
token,
token,
AutocompletionContext.TYPE_FILE);
// NOTE: we overload the meaning of the function call string for file
// completions, to signal whether we should generate files relative to
// the current working directory, or to the file being used for
// completions
result.setFunctionCallString("useFile");
return result;
}
private void addAutocompletionContextForNamespace(
String token,
AutocompletionContext context)
{
String[] splat = token.split(":{2,3}");
String left = "";
if (splat.length <= 0)
{
left = "";
}
else
{
left = splat[0];
}
int type = token.contains(":::") ?
AutocompletionContext.TYPE_NAMESPACE_ALL :
AutocompletionContext.TYPE_NAMESPACE_EXPORTED;
context.add(left, type);
}
private boolean addAutocompletionContextForDollar(AutocompletionContext context)
{
// Establish an evaluation context by looking backwards
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return false;
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
codeModel.tokenizeUpToRow(input_.getCursorPosition().getRow());
TokenCursor cursor = codeModel.getTokenCursor();
if (!cursor.moveToPosition(input_.getCursorPosition()))
return false;
// Move back to the '$'
while (cursor.currentValue() != "$" && cursor.currentValue() != "@")
if (!cursor.moveToPreviousToken())
return false;
int type = cursor.currentValue() == "$" ?
AutocompletionContext.TYPE_DOLLAR :
AutocompletionContext.TYPE_AT;
// Put a cursor here
TokenCursor contextEndCursor = cursor.cloneCursor();
// We allow for arbitrary elements previous, so we want to get e.g.
//
// env::foo()$bar()[1]$baz
// Get the string forming the context
//
//
// If this fails, we still want to report an empty evaluation context
// (the completion is still occurring in a '$' context, so we do want
// to exclude completions from other scopes)
String data = "";
if (cursor.moveToPreviousToken() && cursor.findStartOfEvaluationContext())
{
data = editor.getTextForRange(Range.fromPoints(
cursor.currentPosition(),
contextEndCursor.currentPosition()));
}
context.add(data, type);
return true;
}
private AutocompletionContext getAutocompletionContext()
{
AutocompletionContext context = new AutocompletionContext();
String firstLine = input_.getText();
int row = input_.getCursorPosition().getRow();
// trim to cursor position
firstLine = firstLine.substring(0, input_.getCursorPosition().getColumn());
// If we're in Markdown mode and have an appropriate string, try to get
// file completions
if (DocumentMode.isCursorInMarkdownMode(docDisplay_) &&
firstLine.matches(".*\\[.*\\]\\(.*"))
return getAutocompletionContextForFileMarkdownLink(firstLine);
// Get the token at the cursor position
String token = firstLine.replaceAll(".*[^a-zA-Z0-9._:$@-]", "");
// If we're completing an object within a string, assume it's a
// file-system completion. Note that we may need other contextual information
// to decide if e.g. we only want directories.
String firstLineStripped = StringUtil.stripBalancedQuotes(
StringUtil.stripRComment(firstLine));
boolean isFileCompletion = false;
if (firstLineStripped.indexOf('\'') != -1 ||
firstLineStripped.indexOf('"') != -1)
{
isFileCompletion = true;
addAutocompletionContextForFile(context, firstLine);
}
// If this line starts with '```{', then we're completing chunk options
// pass the whole line as a token
if (firstLine.startsWith("```{") || firstLine.startsWith("<<"))
return new AutocompletionContext(firstLine, AutocompletionContext.TYPE_CHUNK);
// If this line starts with a '?', assume it's a help query
if (firstLine.matches("^\\s*[?].*"))
return new AutocompletionContext(token, AutocompletionContext.TYPE_HELP);
// escape early for roxygen
if (firstLine.matches("\\s*#+'.*"))
return new AutocompletionContext(
token, AutocompletionContext.TYPE_ROXYGEN);
// If the token has '$' or '@', add in the autocompletion context --
// note that we still need parent contexts to give more information
// about the appropriate completion
if (token.contains("$") || token.contains("@"))
addAutocompletionContextForDollar(context);
// If the token has '::' or ':::', add that context. Note that
// we still need outer contexts (so that e.g., if we try
// 'debug(stats::rnorm)' we know not to auto-insert parens)
if (token.contains("::"))
addAutocompletionContextForNamespace(token, context);
// If this is not a file completion, we need to further strip and
// then set the token. Note that the token will have already been
// set if this is a file completion.
token = token.replaceAll(".*[$@:]", "");
if (!isFileCompletion)
context.setToken(token);
// access to the R Code model
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return context;
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
// We might need to grab content from further up in the document than
// the current cursor position -- so tokenize ahead.
codeModel.tokenizeUpToRow(row + 100);
// Make a token cursor and place it at the first token previous
// to the cursor.
TokenCursor tokenCursor = codeModel.getTokenCursor();
if (!tokenCursor.moveToPosition(input_.getCursorPosition()))
return context;
TokenCursor startCursor = tokenCursor.cloneCursor();
// If this is an argument, return auto-completions tuned to that argument
TokenCursor argsCursor = startCursor.cloneCursor();
if (argsCursor.currentType() == "identifier")
argsCursor.moveToPreviousToken();
if (argsCursor.currentValue() == "=")
{
if (argsCursor.moveToPreviousToken())
{
return new AutocompletionContext(
token,
argsCursor.currentValue(),
AutocompletionContext.TYPE_ARGUMENT);
}
}
// Find an opening '(' or '[' -- this provides the function or object
// for completion.
int initialNumCommas = 0;
if (tokenCursor.currentValue() != "(" && tokenCursor.currentValue() != "[")
{
int commaCount = tokenCursor.findOpeningBracketCountCommas(
new String[]{ "[", "(" }, true);
if (commaCount == -1)
{
commaCount = tokenCursor.findOpeningBracketCountCommas("[", false);
if (commaCount == -1)
return context;
else
initialNumCommas = commaCount;
}
else
{
initialNumCommas = commaCount;
}
}
// Figure out whether we're looking at '(', '[', or '[[',
// and place the token cursor on the first token preceding.
TokenCursor endOfDecl = tokenCursor.cloneCursor();
int initialDataType = AutocompletionContext.TYPE_UNKNOWN;
if (tokenCursor.currentValue() == "(")
{
initialDataType = AutocompletionContext.TYPE_FUNCTION;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else if (tokenCursor.currentValue() == "[")
{
if (!tokenCursor.moveToPreviousToken())
return context;
if (tokenCursor.currentValue() == "[")
{
if (!endOfDecl.moveToPreviousToken())
return context;
initialDataType = AutocompletionContext.TYPE_DOUBLE_BRACKET;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else
{
initialDataType = AutocompletionContext.TYPE_SINGLE_BRACKET;
}
}
// Get the string marking the function or data
if (!tokenCursor.findStartOfEvaluationContext())
return context;
// Try to get the function call string -- either there's
// an associated closing paren we can use, or we should just go up
// to the current cursor position
// default case: use start cursor
Position endPos = startCursor.currentPosition();
endPos.setColumn(endPos.getColumn() + startCursor.currentValue().length());
// try to look forward for closing paren
if (endOfDecl.currentValue() == "(")
{
TokenCursor closingParenCursor = endOfDecl.cloneCursor();
if (closingParenCursor.fwdToMatchingToken())
{
endPos = closingParenCursor.currentPosition();
endPos.setColumn(endPos.getColumn() + 1);
}
}
// We can now set the function call string
// We strip the current token so that the matched.call work later on
// can properly resolve the current argument
Position startPosition = startCursor.currentPosition();
if (startCursor.currentValue() == "(")
startPosition.setColumn(startPosition.getColumn() + 1);
String beforeText = editor.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
startPosition));
Position afterTokenPos = startCursor.currentPosition();
if (startCursor.currentType() == "identifier")
afterTokenPos.setColumn(afterTokenPos.getColumn() +
startCursor.currentValue().length());
String afterText = editor.getTextForRange(Range.fromPoints(
afterTokenPos, endPos));
context.setFunctionCallString(
(beforeText + afterText).trim());
String initialData =
docDisplay_.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
endOfDecl.currentPosition())).trim();
// And the first context
context.add(initialData, initialDataType, initialNumCommas);
// Get the rest of the single-bracket contexts for completions as well
String assocData;
int dataType;
int numCommas;
while (true)
{
int commaCount = tokenCursor.findOpeningBracketCountCommas("[", false);
if (commaCount == -1)
break;
numCommas = commaCount;
TokenCursor declEnd = tokenCursor.cloneCursor();
if (!tokenCursor.moveToPreviousToken())
return context;
if (tokenCursor.currentValue() == "[")
{
if (!declEnd.moveToPreviousToken())
return context;
dataType = AutocompletionContext.TYPE_DOUBLE_BRACKET;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else
{
dataType = AutocompletionContext.TYPE_SINGLE_BRACKET;
}
tokenCursor.findStartOfEvaluationContext();
assocData =
docDisplay_.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
declEnd.currentPosition())).trim();
context.add(assocData, dataType, numCommas);
}
return context;
}
public Comparator<QualifiedName> createFuzzyComparator(String query)
{
final String queryLower = query.toLowerCase();
return new Comparator<QualifiedName>() {
@Override
public int compare(final QualifiedName lhs,
final QualifiedName rhs)
{
int lhsScore = CodeSearchOracle.scoreMatch(
lhs.name,
queryLower,
false);
int rhsScore = CodeSearchOracle.scoreMatch(
rhs.name,
queryLower,
false);
if (lhsScore == rhsScore)
{
return lhs.name.length() - rhs.name.length();
}
else
{
return lhsScore < rhsScore ? -1 : 1;
}
}
};
}
/**
* It's important that we create a new instance of this each time.
* It maintains state that is associated with a completion request.
*/
private final class CompletionRequestContext extends
ServerRequestCallback<CompletionResult>
{
public CompletionRequestContext(Invalidation.Token token,
InputEditorSelection selection,
boolean canAutoAccept)
{
invalidationToken_ = token ;
selection_ = selection ;
canAutoAccept_ = canAutoAccept;
}
public void showHelp(QualifiedName selectedItem)
{
helpStrategy_.showHelp(selectedItem, popup_);
}
public void showHelpTopic()
{
helpStrategy_.showHelpTopic(popup_.getSelectedValue());
}
@Override
public void onError(ServerError error)
{
if (invalidationToken_.isInvalid())
return ;
RCompletionManager.this.popup_.showErrorMessage(
error.getUserMessage(),
new PopupPositioner(input_.getCursorBounds(), popup_)) ;
}
@Override
public void onResponseReceived(CompletionResult completions)
{
if (invalidationToken_.isInvalid())
return ;
// Only display the top completions
final QualifiedName[] results =
completions.completions.toArray(new QualifiedName[0]);
if (results.length == 0)
{
popup_.clearCompletions();
boolean lastInputWasTab =
(nativeEvent_ != null && nativeEvent_.getKeyCode() == KeyCodes.KEY_TAB);
boolean lineIsWhitespace = docDisplay_.getCurrentLine().matches("^\\s*$");
if (lastInputWasTab && lineIsWhitespace)
{
docDisplay_.insertCode("\t");
return;
}
if (canAutoAccept_)
{
popup_.showErrorMessage(
"(No matches)",
new PopupPositioner(input_.getCursorBounds(), popup_));
}
else
{
// Show an empty popup message offscreen -- this is a hack to
// ensure that we can get completion results on backspace after a
// failed completion, e.g. 'stats::rna' -> 'stats::rn'
popup_.placeOffscreen();
}
return ;
}
// If there is only one result and the name is identical to the
// current token, then don't display anything
if (results.length == 1 &&
completions.token.equals(results[0].name))
{
return;
}
// Move range to beginning of token; we want to place the popup there.
final String token = completions.token ;
Rectangle rect = input_.getPositionBounds(
selection_.getStart().movePosition(-token.length(), true));
token_ = token;
suggestOnAccept_ = completions.suggestOnAccept;
overrideInsertParens_ = completions.dontInsertParens;
if (results.length == 1
&& canAutoAccept_
&& results[0].type != RCompletionType.DIRECTORY)
{
onSelection(results[0]);
}
else
{
popup_.showCompletionValues(
results,
new PopupPositioner(rect, popup_),
false);
}
}
private void onSelection(QualifiedName qname)
{
suggestTimer_.cancel();
final String value = qname.name ;
if (invalidationToken_.isInvalid())
return;
requester_.flushCache() ;
helpStrategy_.clearCache();
if (value == null)
{
assert false : "Selected comp value is null" ;
return ;
}
applyValue(qname);
if (suggestOnAccept_ || qname.name.endsWith(":"))
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(true, true, false);
}
});
}
else
{
popup_.hide() ;
popup_.clearHelp(false);
popup_.setHelpVisible(false);
}
}
// For input of the form 'something$foo' or 'something@bar', quote the
// element following '@' if it's a non-syntactic R symbol; otherwise
// return as is
private String quoteIfNotSyntacticNameCompletion(String string)
{
if (!string.matches("^[a-zA-Z_.][a-zA-Z0-9_.]*$"))
return "`" + string + "`";
else
return string;
}
private void applyValueRmdOption(final String value)
{
suggestTimer_.cancel();
// If there is no token but spaces have been inserted, then compensate
// for that. This is necessary as we allow for spaces in the completion,
// and completions auto-popup after ',' so e.g. on
//
// ```{r, |}
// ^ -- automatically triggered completion
// ^ -- user inserted spaces
//
// if we accept a completion in that position, we should keep the
// spaces the user inserted. (After the user has inserted a character,
// it becomes part of the token and hence this is unnecessary.
if (token_ == "")
{
int startPos = selection_.getStart().getPosition();
String currentLine = docDisplay_.getCurrentLine();
while (startPos < currentLine.length() &&
currentLine.charAt(startPos) == ' ')
++startPos;
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(startPos, false),
input_.getSelection().getEnd()));
}
else
{
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(-token_.length(), true),
input_.getSelection().getEnd()));
}
input_.replaceSelection(value, true);
token_ = value;
selection_ = input_.getSelection();
}
private void applyValue(final QualifiedName qualifiedName)
{
if (qualifiedName.source == "`chunk-option`")
{
applyValueRmdOption(qualifiedName.name);
return;
}
boolean insertParen =
uiPrefs_.insertParensAfterFunctionCompletion().getValue() &&
RCompletionType.isFunctionType(qualifiedName.type);
// Don't insert a paren if there is already a '(' following
// the cursor
AceEditor editor = (AceEditor) input_;
boolean textFollowingCursorIsOpenParen = false;
boolean textFollowingCursorIsClosingParen = false;
if (editor != null)
{
TokenCursor cursor =
editor.getSession().getMode().getRCodeModel().getTokenCursor();
cursor.moveToPosition(editor.getCursorPosition());
if (cursor.moveToNextToken())
{
textFollowingCursorIsOpenParen =
cursor.currentValue() == "(";
textFollowingCursorIsClosingParen =
cursor.currentValue() == ")" && !cursor.bwdToMatchingToken();
}
}
String value = qualifiedName.name;
String source = qualifiedName.source;
boolean shouldQuote = qualifiedName.shouldQuote;
if (qualifiedName.type == RCompletionType.DIRECTORY)
value = value + "/";
if (!RCompletionType.isFileType(qualifiedName.type))
{
if (value == ":=")
value = quoteIfNotSyntacticNameCompletion(value);
else if (!value.matches(".*[=:]\\s*$") &&
!value.matches("^\\s*([`'\"]).*\\1\\s*$") &&
source != "<file>" &&
source != "<directory>" &&
source != "`chunk-option`" &&
!value.startsWith("@") &&
!shouldQuote)
value = quoteIfNotSyntacticNameCompletion(value);
}
/* In some cases, applyValue can be called more than once
* as part of the same completion instance--specifically,
* if there's only one completion candidate and it is in
* a package. To make sure that the selection movement
* logic works the second time, we need to reset the
* selection.
*/
// Move range to beginning of token
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(-token_.length(), true),
input_.getSelection().getEnd()));
if (insertParen && !overrideInsertParens_ && !textFollowingCursorIsOpenParen)
{
// Don't replace the selection if the token ends with a ')'
// (implies an earlier replacement handled this)
if (token_.endsWith("("))
{
input_.setSelection(new InputEditorSelection(
input_.getSelection().getEnd(),
input_.getSelection().getEnd()));
}
else
{
// If the token after the cursor is already a ')', don't insert
// a closing paren
int relMovement = 0;
if (textFollowingCursorIsClosingParen || !uiPrefs_.insertMatching().getValue())
{
input_.replaceSelection(value + "(", true);
}
else
{
input_.replaceSelection(value + "()", true);
relMovement = -1;
}
// Move the cursor into the newly inserted parens
InputEditorSelection newSelection = new InputEditorSelection(
input_.getSelection().getEnd().movePosition(
relMovement, true));
token_ = value + "(";
selection_ = new InputEditorSelection(
input_.getSelection().getStart().movePosition(
relMovement - 1, true),
newSelection.getStart());
input_.setSelection(newSelection);
}
}
else
{
if (shouldQuote)
value = "\"" + value + "\"";
// don't add spaces around equals if requested
final String kSpaceEquals = " = ";
if (!uiPrefs_.insertSpacesAroundEquals().getValue() &&
value.endsWith(kSpaceEquals))
{
value = value.substring(0, value.length() - kSpaceEquals.length()) + "=";
}
input_.replaceSelection(value, true);
token_ = value;
selection_ = input_.getSelection();
}
// Show a signature popup if we just completed a function
if (RCompletionType.isFunctionType(qualifiedName.type))
displaySignatureToolTip(qualifiedName);
}
private final Invalidation.Token invalidationToken_ ;
private InputEditorSelection selection_ ;
private final boolean canAutoAccept_;
private boolean suggestOnAccept_;
private boolean overrideInsertParens_;
}
private void displaySignatureToolTip(final QualifiedName qualifiedName)
{
// Bail on lack of UI prefs
if (!uiPrefs_.showSignatureTooltips().getValue())
return;
// We want to find the cursor position, and place the popup
// above the cursor.
server_.getArgs(
qualifiedName.name,
qualifiedName.source,
new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String args)
{
if (!StringUtil.isNullOrEmpty(args))
doDisplaySignatureToolTip(qualifiedName.name + args);
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
private void doDisplaySignatureToolTip(String signature)
{
if (sigTip_.isShowing())
sigTip_.hide();
sigTip_.resolvePositionAndShow(signature);
}
private String getSourceDocumentPath()
{
if (rContext_ != null)
return rContext_.getPath();
else
return null;
}
public void showHelpDeferred(final CompletionRequestContext context,
final QualifiedName item,
int milliseconds)
{
if (helpRequest_ != null && helpRequest_.isRunning())
helpRequest_.cancel();
helpRequest_ = new Timer() {
@Override
public void run()
{
if (item.equals(lastSelectedItem_) && popup_.isShowing())
context.showHelp(item);
}
};
helpRequest_.schedule(milliseconds);
}
private GlobalDisplay globalDisplay_;
private FileTypeRegistry fileTypeRegistry_;
private EventBus eventBus_;
private HelpStrategy helpStrategy_;
private UIPrefs uiPrefs_;
private final CodeToolsServerOperations server_;
private final InputEditorDisplay input_ ;
private final NavigableSourceEditor navigableSourceEditor_;
private final CompletionPopupDisplay popup_ ;
private final CompletionRequester requester_ ;
private final InitCompletionFilter initFilter_ ;
// Prevents completion popup from being dismissed when you merely
// click on it to scroll.
private boolean ignoreNextInputBlur_ = false;
private String token_ ;
private final DocDisplay docDisplay_;
private final boolean isConsole_;
private final Invalidation invalidation_ = new Invalidation();
private CompletionRequestContext context_ ;
private final RCompletionContext rContext_;
private final RnwCompletionContext rnwContext_;
private RCompletionToolTip sigTip_;
private NativeEvent nativeEvent_;
private QualifiedName lastSelectedItem_;
private Timer helpRequest_;
private final SuggestionTimer suggestTimer_;
private class SuggestionTimer
{
SuggestionTimer()
{
timer_ = new Timer()
{
@Override
public void run()
{
beginSuggest(
flushCache_,
implicit_,
canAutoInsert_);
}
};
}
public void schedule(boolean flushCache,
boolean implicit,
boolean canAutoInsert)
{
flushCache_ = flushCache;
implicit_ = implicit;
canAutoInsert_ = canAutoInsert;
timer_.schedule(400);
}
public void cancel()
{
timer_.cancel();
}
@SuppressWarnings("unused")
public boolean isRunning()
{
return timer_.isRunning();
}
private boolean flushCache_;
private boolean implicit_;
private boolean canAutoInsert_;
private final Timer timer_;
}
}
| src/gwt/src/org/rstudio/studio/client/workbench/views/console/shell/assist/RCompletionManager.java | /*
* RCompletionManager.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.console.shell.assist;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.inject.Inject;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.Invalidation;
import org.rstudio.core.client.Rectangle;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.KeyboardShortcut;
import org.rstudio.core.client.events.SelectionCommitEvent;
import org.rstudio.core.client.events.SelectionCommitHandler;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.GlobalProgressDelayer;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations;
import org.rstudio.studio.client.common.codetools.RCompletionType;
import org.rstudio.studio.client.common.filetypes.DocumentMode;
import org.rstudio.studio.client.common.filetypes.FileTypeRegistry;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.codesearch.CodeSearchOracle;
import org.rstudio.studio.client.workbench.codesearch.model.FunctionDefinition;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionRequester.CompletionResult;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionRequester.QualifiedName;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorLineWithCursorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorUtil;
import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay;
import org.rstudio.studio.client.workbench.views.source.editors.text.NavigableSourceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.RCompletionContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.CodeModel;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.DplyrJoinContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.RInfixData;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.TokenCursor;
import org.rstudio.studio.client.workbench.views.source.editors.text.r.RCompletionToolTip;
import org.rstudio.studio.client.workbench.views.source.events.CodeBrowserNavigationEvent;
import org.rstudio.studio.client.workbench.views.source.model.RnwCompletionContext;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class RCompletionManager implements CompletionManager
{
// globally suppress F1 and F2 so no default browser behavior takes those
// keystrokes (e.g. Help in Chrome)
static
{
Event.addNativePreviewHandler(new NativePreviewHandler() {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{
if (event.getTypeInt() == Event.ONKEYDOWN)
{
int keyCode = event.getNativeEvent().getKeyCode();
if ((keyCode == 112 || keyCode == 113) &&
KeyboardShortcut.NONE ==
KeyboardShortcut.getModifierValue(event.getNativeEvent()))
{
event.getNativeEvent().preventDefault();
}
}
}
});
}
public RCompletionManager(InputEditorDisplay input,
NavigableSourceEditor navigableSourceEditor,
CompletionPopupDisplay popup,
CodeToolsServerOperations server,
InitCompletionFilter initFilter,
RCompletionContext rContext,
RnwCompletionContext rnwContext,
DocDisplay docDisplay,
boolean isConsole)
{
RStudioGinjector.INSTANCE.injectMembers(this);
input_ = input ;
navigableSourceEditor_ = navigableSourceEditor;
popup_ = popup ;
server_ = server ;
requester_ = new CompletionRequester(server_, rnwContext, navigableSourceEditor);
initFilter_ = initFilter ;
rContext_ = rContext;
rnwContext_ = rnwContext;
docDisplay_ = docDisplay;
isConsole_ = isConsole;
sigTip_ = new RCompletionToolTip(docDisplay_);
suggestTimer_ = new SuggestionTimer();
input_.addBlurHandler(new BlurHandler() {
public void onBlur(BlurEvent event)
{
if (!ignoreNextInputBlur_)
invalidatePendingRequests() ;
ignoreNextInputBlur_ = false ;
}
}) ;
input_.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
invalidatePendingRequests();
}
});
popup_.addSelectionCommitHandler(new SelectionCommitHandler<QualifiedName>() {
public void onSelectionCommit(SelectionCommitEvent<QualifiedName> event)
{
assert context_ != null : "onSelection called but handler is null" ;
if (context_ != null)
context_.onSelection(event.getSelectedItem()) ;
}
}) ;
popup_.addSelectionHandler(new SelectionHandler<QualifiedName>() {
public void onSelection(SelectionEvent<QualifiedName> event)
{
lastSelectedItem_ = event.getSelectedItem();
if (popup_.isHelpVisible())
context_.showHelp(lastSelectedItem_);
else
showHelpDeferred(context_, lastSelectedItem_, 600);
}
}) ;
popup_.addMouseDownHandler(new MouseDownHandler() {
public void onMouseDown(MouseDownEvent event)
{
ignoreNextInputBlur_ = true ;
}
});
popup_.addSelectionHandler(new SelectionHandler<QualifiedName>() {
@Override
public void onSelection(SelectionEvent<QualifiedName> event)
{
docDisplay_.setPopupVisible(true);
}
});
popup_.addCloseHandler(new CloseHandler<PopupPanel>()
{
@Override
public void onClose(CloseEvent<PopupPanel> event)
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
docDisplay_.setPopupVisible(false);
}
});
}
});
}
@Inject
public void initialize(GlobalDisplay globalDisplay,
FileTypeRegistry fileTypeRegistry,
EventBus eventBus,
HelpStrategy helpStrategy,
UIPrefs uiPrefs)
{
globalDisplay_ = globalDisplay;
fileTypeRegistry_ = fileTypeRegistry;
eventBus_ = eventBus;
helpStrategy_ = helpStrategy;
uiPrefs_ = uiPrefs;
}
public void close()
{
popup_.hide();
}
public void codeCompletion()
{
if (initFilter_ == null || initFilter_.shouldComplete(null))
beginSuggest(true, false, true);
}
public void goToHelp()
{
InputEditorLineWithCursorPosition linePos =
InputEditorUtil.getLineWithCursorPosition(input_);
server_.getHelpAtCursor(
linePos.getLine(), linePos.getPosition(),
new SimpleRequestCallback<Void>("Help"));
}
public void goToFunctionDefinition()
{
// determine current line and cursor position
InputEditorLineWithCursorPosition lineWithPos =
InputEditorUtil.getLineWithCursorPosition(input_);
// lookup function definition at this location
// delayed progress indicator
final GlobalProgressDelayer progress = new GlobalProgressDelayer(
globalDisplay_, 1000, "Searching for function definition...");
server_.getFunctionDefinition(
lineWithPos.getLine(),
lineWithPos.getPosition(),
new ServerRequestCallback<FunctionDefinition>() {
@Override
public void onResponseReceived(FunctionDefinition def)
{
// dismiss progress
progress.dismiss();
// if we got a hit
if (def.getFunctionName() != null)
{
// search locally if a function navigator was provided
if (navigableSourceEditor_ != null)
{
// try to search for the function locally
SourcePosition position =
navigableSourceEditor_.findFunctionPositionFromCursor(
def.getFunctionName());
if (position != null)
{
navigableSourceEditor_.navigateToPosition(position,
true);
return; // we're done
}
}
// if we didn't satisfy the request using a function
// navigator and we got a file back from the server then
// navigate to the file/loc
if (def.getFile() != null)
{
fileTypeRegistry_.editFile(def.getFile(),
def.getPosition());
}
// if we didn't get a file back see if we got a
// search path definition
else if (def.getSearchPathFunctionDefinition() != null)
{
eventBus_.fireEvent(new CodeBrowserNavigationEvent(
def.getSearchPathFunctionDefinition()));
}
}
}
@Override
public void onError(ServerError error)
{
progress.dismiss();
globalDisplay_.showErrorMessage("Error Searching for Function",
error.getUserMessage());
}
});
}
public boolean previewKeyDown(NativeEvent event)
{
suggestTimer_.cancel();
if (sigTip_ != null)
if (sigTip_.previewKeyDown(event))
return true;
/**
* KEYS THAT MATTER
*
* When popup not showing:
* Tab - attempt completion (handled in Console.java)
*
* When popup showing:
* Esc - dismiss popup
* Enter/Tab/Right-arrow - accept current selection
* Up-arrow/Down-arrow - change selected item
* Left-arrow - dismiss popup
* [identifier] - narrow suggestions--or if we're lame, just dismiss
* All others - dismiss popup
*/
nativeEvent_ = event;
int keycode = event.getKeyCode();
int modifier = KeyboardShortcut.getModifierValue(event);
if (!popup_.isShowing())
{
if (CompletionUtils.isCompletionRequest(event, modifier))
{
if (initFilter_ == null || initFilter_.shouldComplete(event))
{
// If we're in markdown mode, only autocomplete in '```{r',
// '[](', or '`r |' contexts
if (DocumentMode.isCursorInMarkdownMode(docDisplay_))
{
String currentLine = docDisplay_.getCurrentLineUpToCursor();
if (!(Pattern.create("^```{[rR]").test(currentLine) ||
Pattern.create(".*\\[.*\\]\\(").test(currentLine) ||
(Pattern.create(".*`r").test(currentLine) &&
StringUtil.countMatches(currentLine, '`') % 2 == 1)))
return false;
}
// If we're in tex mode, only provide completions in chunks
if (DocumentMode.isCursorInTexMode(docDisplay_))
{
String currentLine = docDisplay_.getCurrentLineUpToCursor();
if (!Pattern.create("^<<").test(currentLine))
return false;
}
return beginSuggest(true, false, true);
}
}
else if (keycode == 112 // F1
&& modifier == KeyboardShortcut.NONE)
{
goToHelp();
}
else if (keycode == 113 // F2
&& modifier == KeyboardShortcut.NONE)
{
goToFunctionDefinition();
}
}
else
{
switch (keycode)
{
// chrome on ubuntu now sends this before every keydown
// so we need to explicitly ignore it. see:
// https://github.com/ivaynberg/select2/issues/2482
case KeyCodes.KEY_WIN_IME:
return false ;
case KeyCodes.KEY_SHIFT:
case KeyCodes.KEY_CTRL:
case KeyCodes.KEY_ALT:
case KeyCodes.KEY_MAC_FF_META:
case KeyCodes.KEY_WIN_KEY_LEFT_META:
return false ; // bare modifiers should do nothing
}
if (modifier == KeyboardShortcut.NONE)
{
if (keycode == KeyCodes.KEY_ESCAPE)
{
invalidatePendingRequests() ;
return true ;
}
// NOTE: It is possible for the popup to still be showing, but
// showing offscreen with no values. We only grab these keys
// when the popup is both showing, and has completions.
// This functionality is here to ensure backspace works properly;
// e.g "stats::rna" -> "stats::rn" brings completions if the user
// had originally requested completions at e.g. "stats::".
if (popup_.hasCompletions() && !popup_.isOffscreen())
{
if (keycode == KeyCodes.KEY_ENTER)
{
QualifiedName value = popup_.getSelectedValue() ;
if (value != null)
{
context_.onSelection(value) ;
return true ;
}
}
else if (keycode == KeyCodes.KEY_TAB ||
keycode == KeyCodes.KEY_RIGHT)
{
QualifiedName value = popup_.getSelectedValue() ;
if (value != null)
{
if (value.type == RCompletionType.DIRECTORY)
context_.suggestOnAccept_ = true;
context_.onSelection(value);
return true;
}
}
else if (keycode == KeyCodes.KEY_UP)
return popup_.selectPrev() ;
else if (keycode == KeyCodes.KEY_DOWN)
return popup_.selectNext() ;
else if (keycode == KeyCodes.KEY_PAGEUP)
return popup_.selectPrevPage() ;
else if (keycode == KeyCodes.KEY_PAGEDOWN)
return popup_.selectNextPage() ;
else if (keycode == KeyCodes.KEY_HOME)
return popup_.selectFirst() ;
else if (keycode == KeyCodes.KEY_END)
return popup_.selectLast() ;
else if (keycode == KeyCodes.KEY_LEFT)
{
invalidatePendingRequests() ;
return true ;
}
if (keycode == 112) // F1
{
context_.showHelpTopic() ;
return true ;
}
else if (keycode == 113) // F2
{
goToFunctionDefinition();
return true;
}
}
}
if (canContinueCompletions(event))
return false;
// if we insert a '/', we're probably forming a directory --
// pop up completions
if (keycode == 191 && modifier == KeyboardShortcut.NONE)
{
input_.insertCode("/");
return beginSuggest(true, true, false);
}
// continue showing completions on backspace
if (keycode == KeyCodes.KEY_BACKSPACE && modifier == KeyboardShortcut.NONE)
{
int cursorColumn = input_.getCursorPosition().getColumn();
String currentLine = docDisplay_.getCurrentLine();
// only suggest if the character previous to the cursor is an R identifier
// also halt suggestions if we're about to remove the only character on the line
if (cursorColumn > 0)
{
char ch = currentLine.charAt(cursorColumn - 2);
char prevCh = currentLine.charAt(cursorColumn - 3);
boolean isAcceptableCharSequence = isValidForRIdentifier(ch) ||
(ch == ':' && prevCh == ':') ||
ch == '$' ||
ch == '@' ||
ch == '/'; // for file completions
if (currentLine.length() > 0 &&
cursorColumn > 0 &&
isAcceptableCharSequence)
{
// manually remove the previous character
InputEditorSelection selection = input_.getSelection();
InputEditorPosition start = selection.getStart().movePosition(-1, true);
InputEditorPosition end = selection.getStart();
if (currentLine.charAt(cursorColumn) == ')' && currentLine.charAt(cursorColumn - 1) == '(')
{
// flush cache as old completions no longer relevant
requester_.flushCache();
end = selection.getStart().movePosition(1, true);
}
input_.setSelection(new InputEditorSelection(start, end));
input_.replaceSelection("", false);
return beginSuggest(false, false, false);
}
}
else
{
invalidatePendingRequests();
return true;
}
}
invalidatePendingRequests();
return false ;
}
return false ;
}
private boolean isValidForRIdentifier(char c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c == '.') ||
(c == '_');
}
private boolean checkCanAutoPopup(char c, int lookbackLimit)
{
String currentLine = docDisplay_.getCurrentLine();
Position cursorPos = input_.getCursorPosition();
int cursorColumn = cursorPos.getColumn();
// Don't auto-popup when the cursor is within a string
if (docDisplay_.isCursorInSingleLineString())
return false;
// Grab the current token on the line
String currentToken = StringUtil.getToken(
currentLine, cursorColumn, "^[a-zA-Z0-9._'\"`]$", false, false);
// Don't auto-popup for common keywords + symbols
String[] keywords = {
"for", "if", "in", "function", "while", "repeat",
"break", "switch", "return", "library", "require",
"TRUE", "FALSE"
};
for (String keyword : keywords)
if (currentToken.length() <= keyword.length() &&
keyword.substring(0, currentToken.length()).equals(currentToken))
return false;
boolean canAutoPopup =
(currentLine.length() > lookbackLimit - 1 && isValidForRIdentifier(c));
if (isConsole_ && !uiPrefs_.alwaysCompleteInConsole().getValue())
canAutoPopup = false;
if (canAutoPopup)
{
for (int i = 0; i < lookbackLimit; i++)
{
if (!isValidForRIdentifier(currentLine.charAt(cursorColumn - i - 1)))
{
canAutoPopup = false;
break;
}
}
}
return canAutoPopup;
}
public boolean previewKeyPress(char c)
{
suggestTimer_.cancel();
if (popup_.isShowing())
{
// If insertion of this character completes an available suggestion,
// and is not a prefix match of any other suggestion, then implicitly
// apply that.
QualifiedName selectedItem =
popup_.getSelectedValue();
if (selectedItem != null &&
selectedItem.name.equals(token_ + c))
{
String fullToken = token_ + c;
// Find prefix matches -- there should only be one if we really
// want this behaviour (ie the current selection)
int prefixMatchCount = 0;
QualifiedName[] items = popup_.getItems();
for (int i = 0; i < items.length; i++)
{
if (items[i].name.startsWith(fullToken))
{
++prefixMatchCount;
if (prefixMatchCount > 1)
break;
}
}
if (prefixMatchCount == 1)
{
// We place the completion list offscreen to ensure that
// backspace events are handled later.
popup_.placeOffscreen();
return false;
}
}
if (isValidForRIdentifier(c))
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(false, true, false);
}
});
}
if (c == ':')
{
suggestTimer_.schedule(false, true, false);
}
}
else
{
// Bail if we're not in R mode
if (!DocumentMode.isCursorInRMode(docDisplay_))
return false;
// Perform an auto-popup if a set number of R identifier characters
// have been inserted (but only if the user has allowed it in prefs)
boolean autoPopupEnabled = uiPrefs_.codeComplete().getValue().equals(
UIPrefsAccessor.COMPLETION_ALWAYS);
if (!autoPopupEnabled)
return false;
// Check for a valid number of R identifier characters for autopopup
boolean canAutoPopup = checkCanAutoPopup(c, 4);
char prevChar = docDisplay_.getCurrentLine().charAt(
input_.getCursorPosition().getColumn() - 1);
// Automatically popup completions after certain function calls
if (c == '(' && !isLineInComment(docDisplay_.getCurrentLine()))
{
String token = StringUtil.getToken(
docDisplay_.getCurrentLine(),
input_.getCursorPosition().getColumn(),
"[a-zA-Z0-9._]",
false,
true);
QualifiedName lastSelectedItem = popup_.getLastSelectedValue();
if (lastSelectedItem != null)
{
if (lastSelectedItem.name.equals(token))
displaySignatureToolTip(lastSelectedItem);
}
if (token.matches("^(library|require|requireNamespace|data)\\s*$"))
canAutoPopup = true;
}
if (
(canAutoPopup) ||
(c == ':' && prevChar == ':') ||
(c == '$') ||
(c == '@') ||
isSweaveCompletion(c))
{
// Delay suggestion to avoid auto-popup while the user is typing
suggestTimer_.schedule(true, true, false);
}
else if (CompletionUtils.handleEncloseSelection(input_, c))
{
return true;
}
}
return false ;
}
@SuppressWarnings("unused")
private boolean isRoxygenTagValidHere()
{
if (input_.getText().matches("\\s*#+'.*"))
{
String linePart = input_.getText().substring(0, input_.getSelection().getStart().getPosition());
if (linePart.matches("\\s*#+'\\s*"))
return true;
}
return false;
}
private boolean isSweaveCompletion(char c)
{
if (rnwContext_ == null || (c != ',' && c != ' ' && c != '='))
return false;
int optionsStart = rnwContext_.getRnwOptionsStart(
input_.getText(),
input_.getSelection().getStart().getPosition());
if (optionsStart < 0)
{
return false;
}
String linePart = input_.getText().substring(
optionsStart,
input_.getSelection().getStart().getPosition());
return c != ' ' || linePart.matches(".*,\\s*");
}
private static boolean canContinueCompletions(NativeEvent event)
{
if (event.getAltKey()
|| event.getCtrlKey()
|| event.getMetaKey())
{
return false ;
}
int keyCode = event.getKeyCode() ;
if (keyCode >= 'a' && keyCode <= 'z')
return true ;
if (keyCode >= 'A' && keyCode <= 'Z')
return true ;
if (keyCode == ' ')
return true ;
if (keyCode == 189) // dash
return true ;
if (keyCode == 189 && event.getShiftKey()) // underscore
return true ;
if (event.getShiftKey())
return false ;
if (keyCode >= '0' && keyCode <= '9')
return true ;
if (keyCode == 190) // period
return true ;
return false ;
}
private void invalidatePendingRequests()
{
invalidatePendingRequests(true, true);
}
private void invalidatePendingRequests(boolean flushCache,
boolean hidePopup)
{
invalidation_.invalidate();
if (hidePopup && popup_.isShowing())
{
popup_.hide();
popup_.clearHelp(false);
}
if (flushCache)
requester_.flushCache() ;
}
// Things we need to form an appropriate autocompletion:
//
// 1. The token to the left of the cursor,
// 2. The associated function call (if any -- for arguments),
// 3. The associated data for a `[` call (if any -- completions from data object),
// 4. The associated data for a `[[` call (if any -- completions from data object)
class AutocompletionContext {
// Be sure to sync these with 'SessionCodeTools.R'!
public static final int TYPE_UNKNOWN = 0;
public static final int TYPE_FUNCTION = 1;
public static final int TYPE_SINGLE_BRACKET = 2;
public static final int TYPE_DOUBLE_BRACKET = 3;
public static final int TYPE_NAMESPACE_EXPORTED = 4;
public static final int TYPE_NAMESPACE_ALL = 5;
public static final int TYPE_DOLLAR = 6;
public static final int TYPE_AT = 7;
public static final int TYPE_FILE = 8;
public static final int TYPE_CHUNK = 9;
public static final int TYPE_ROXYGEN = 10;
public static final int TYPE_HELP = 11;
public static final int TYPE_ARGUMENT = 12;
public AutocompletionContext(
String token,
List<String> assocData,
List<Integer> dataType,
List<Integer> numCommas,
String functionCallString)
{
token_ = token;
assocData_ = assocData;
dataType_ = dataType;
numCommas_ = numCommas;
functionCallString_ = functionCallString;
}
public AutocompletionContext(
String token,
ArrayList<String> assocData,
ArrayList<Integer> dataType)
{
token_ = token;
assocData_ = assocData;
dataType_ = dataType;
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext(
String token,
String assocData,
int dataType)
{
token_ = token;
assocData_ = Arrays.asList(assocData);
dataType_ = Arrays.asList(dataType);
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext(
String token,
int dataType)
{
token_ = token;
assocData_ = Arrays.asList("");
dataType_ = Arrays.asList(dataType);
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext()
{
token_ = "";
assocData_ = new ArrayList<String>();
dataType_ = new ArrayList<Integer>();
numCommas_ = new ArrayList<Integer>();
functionCallString_ = "";
}
public String getToken()
{
return token_;
}
public void setToken(String token)
{
this.token_ = token;
}
public List<String> getAssocData()
{
return assocData_;
}
public void setAssocData(List<String> assocData)
{
this.assocData_ = assocData;
}
public List<Integer> getDataType()
{
return dataType_;
}
public void setDataType(List<Integer> dataType)
{
this.dataType_ = dataType;
}
public List<Integer> getNumCommas()
{
return numCommas_;
}
public void setNumCommas(List<Integer> numCommas)
{
this.numCommas_ = numCommas;
}
public String getFunctionCallString()
{
return functionCallString_;
}
public void setFunctionCallString(String functionCallString)
{
this.functionCallString_ = functionCallString;
}
public void add(String assocData, Integer dataType, Integer numCommas)
{
assocData_.add(assocData);
dataType_.add(dataType);
numCommas_.add(numCommas);
}
public void add(String assocData, Integer dataType)
{
add(assocData, dataType, 0);
}
public void add(String assocData)
{
add(assocData, AutocompletionContext.TYPE_UNKNOWN, 0);
}
private String token_;
private List<String> assocData_;
private List<Integer> dataType_;
private List<Integer> numCommas_;
private String functionCallString_;
}
private boolean isLineInRoxygenComment(String line)
{
return line.matches("^\\s*#+'\\s*[^\\s].*");
}
private boolean isLineInComment(String line)
{
return StringUtil.stripBalancedQuotes(line).contains("#");
}
/**
* If false, the suggest operation was aborted
*/
private boolean beginSuggest(boolean flushCache,
boolean implicit,
boolean canAutoInsert)
{
suggestTimer_.cancel();
if (!input_.isSelectionCollapsed())
return false ;
invalidatePendingRequests(flushCache, false);
InputEditorSelection selection = input_.getSelection() ;
if (selection == null)
return false;
int cursorCol = selection.getStart().getPosition();
String firstLine = input_.getText().substring(0, cursorCol);
// never autocomplete in (non-roxygen) comments, or at the start
// of roxygen comments (e.g. at "#' |")
if (isLineInComment(firstLine) && !isLineInRoxygenComment(firstLine))
return false;
// don't auto-complete with tab on lines with only whitespace,
// if the insertion character was a tab (unless the user has opted in)
if (!uiPrefs_.allowTabMultilineCompletion().getValue())
{
if (nativeEvent_ != null &&
nativeEvent_.getKeyCode() == KeyCodes.KEY_TAB)
if (firstLine.matches("^\\s*$"))
return false;
}
AutocompletionContext context = getAutocompletionContext();
context_ = new CompletionRequestContext(invalidation_.getInvalidationToken(),
selection,
canAutoInsert);
RInfixData infixData = RInfixData.create();
AceEditor editor = (AceEditor) docDisplay_;
if (editor != null)
{
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
TokenCursor cursor = codeModel.getTokenCursor();
if (cursor.moveToPosition(input_.getCursorPosition()))
{
String token = "";
if (cursor.currentType() == "identifier")
token = cursor.currentValue();
String cursorPos = "left";
if (cursor.currentValue() == "=")
cursorPos = "right";
TokenCursor clone = cursor.cloneCursor();
if (clone.moveToPreviousToken())
if (clone.currentValue() == "=")
cursorPos = "right";
// Try to get a dplyr join completion
DplyrJoinContext joinContext =
codeModel.getDplyrJoinContextFromInfixChain(cursor);
// If that failed, try a non-infix lookup
if (joinContext == null)
{
String joinString =
getDplyrJoinString(editor, cursor);
if (!StringUtil.isNullOrEmpty(joinString))
{
requester_.getDplyrJoinCompletionsString(
token,
joinString,
cursorPos,
implicit,
context_);
return true;
}
}
else
{
requester_.getDplyrJoinCompletions(
joinContext,
implicit,
context_);
return true;
}
// Try to see if there's an object name we should use to supplement
// completions
if (cursor.moveToPosition(input_.getCursorPosition()))
infixData = codeModel.getDataFromInfixChain(cursor);
}
}
String filePath = getSourceDocumentPath();
if (filePath == null)
filePath = "";
requester_.getCompletions(
context.getToken(),
context.getAssocData(),
context.getDataType(),
context.getNumCommas(),
context.getFunctionCallString(),
infixData.getDataName(),
infixData.getAdditionalArgs(),
infixData.getExcludeArgs(),
infixData.getExcludeArgsFromObject(),
filePath,
implicit,
context_);
return true ;
}
private String getDplyrJoinString(
AceEditor editor,
TokenCursor cursor)
{
while (true)
{
int commaCount = cursor.findOpeningBracketCountCommas("(", true);
if (commaCount == -1)
break;
if (!cursor.moveToPreviousToken())
return "";
if (!cursor.currentValue().matches(".*join$"))
continue;
if (commaCount < 2)
return "";
Position start = cursor.currentPosition();
if (!cursor.moveToNextToken())
return "";
if (!cursor.fwdToMatchingToken())
return "";
Position end = cursor.currentPosition();
end.setColumn(end.getColumn() + 1);
return editor.getTextForRange(Range.fromPoints(
start, end));
}
return "";
}
private void addAutocompletionContextForFile(AutocompletionContext context,
String line)
{
int index = Math.max(line.lastIndexOf('"'), line.lastIndexOf('\''));
String token = line.substring(index + 1);
context.add(token, AutocompletionContext.TYPE_FILE);
context.setToken(token);
}
private AutocompletionContext getAutocompletionContextForFileMarkdownLink(
String line)
{
int index = line.lastIndexOf('(');
AutocompletionContext result = new AutocompletionContext(
line.substring(index + 1),
AutocompletionContext.TYPE_FILE);
// NOTE: we overload the meaning of the function call string for file
// completions, to signal whether we should generate files relative to
// the current working directory, or to the file being used for
// completions
result.setFunctionCallString("useFile");
return result;
}
private void addAutocompletionContextForNamespace(
String token,
AutocompletionContext context)
{
String[] splat = token.split(":{2,3}");
String left = "";
if (splat.length <= 0)
{
left = "";
}
else
{
left = splat[0];
}
int type = token.contains(":::") ?
AutocompletionContext.TYPE_NAMESPACE_ALL :
AutocompletionContext.TYPE_NAMESPACE_EXPORTED;
context.add(left, type);
}
private boolean addAutocompletionContextForDollar(AutocompletionContext context)
{
// Establish an evaluation context by looking backwards
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return false;
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
codeModel.tokenizeUpToRow(input_.getCursorPosition().getRow());
TokenCursor cursor = codeModel.getTokenCursor();
if (!cursor.moveToPosition(input_.getCursorPosition()))
return false;
// Move back to the '$'
while (cursor.currentValue() != "$" && cursor.currentValue() != "@")
if (!cursor.moveToPreviousToken())
return false;
int type = cursor.currentValue() == "$" ?
AutocompletionContext.TYPE_DOLLAR :
AutocompletionContext.TYPE_AT;
// Put a cursor here
TokenCursor contextEndCursor = cursor.cloneCursor();
// We allow for arbitrary elements previous, so we want to get e.g.
//
// env::foo()$bar()[1]$baz
// Get the string forming the context
//
//
// If this fails, we still want to report an empty evaluation context
// (the completion is still occurring in a '$' context, so we do want
// to exclude completions from other scopes)
String data = "";
if (cursor.moveToPreviousToken() && cursor.findStartOfEvaluationContext())
{
data = editor.getTextForRange(Range.fromPoints(
cursor.currentPosition(),
contextEndCursor.currentPosition()));
}
context.add(data, type);
return true;
}
private AutocompletionContext getAutocompletionContext()
{
AutocompletionContext context = new AutocompletionContext();
String firstLine = input_.getText();
int row = input_.getCursorPosition().getRow();
// trim to cursor position
firstLine = firstLine.substring(0, input_.getCursorPosition().getColumn());
// Get the token at the cursor position
String token = firstLine.replaceAll(".*[^a-zA-Z0-9._:$@-]", "");
// If we're in Markdown mode and have an appropriate string, try to get
// file completions
if (DocumentMode.isCursorInMarkdownMode(docDisplay_) &&
firstLine.matches(".*\\[.*\\]\\(.*"))
return getAutocompletionContextForFileMarkdownLink(firstLine);
// If we're completing an object within a string, assume it's a
// file-system completion. Note that we may need other contextual information
// to decide if e.g. we only want directories.
String firstLineStripped = StringUtil.stripBalancedQuotes(
StringUtil.stripRComment(firstLine));
boolean isFileCompletion = false;
if (firstLineStripped.indexOf('\'') != -1 ||
firstLineStripped.indexOf('"') != -1)
{
isFileCompletion = true;
addAutocompletionContextForFile(context, firstLine);
}
// If this line starts with '```{', then we're completing chunk options
// pass the whole line as a token
if (firstLine.startsWith("```{") || firstLine.startsWith("<<"))
return new AutocompletionContext(firstLine, AutocompletionContext.TYPE_CHUNK);
// If this line starts with a '?', assume it's a help query
if (firstLine.matches("^\\s*[?].*"))
return new AutocompletionContext(token, AutocompletionContext.TYPE_HELP);
// escape early for roxygen
if (firstLine.matches("\\s*#+'.*"))
return new AutocompletionContext(
token, AutocompletionContext.TYPE_ROXYGEN);
// If the token has '$' or '@', add in the autocompletion context --
// note that we still need parent contexts to give more information
// about the appropriate completion
if (token.contains("$") || token.contains("@"))
addAutocompletionContextForDollar(context);
// If the token has '::' or ':::', add that context. Note that
// we still need outer contexts (so that e.g., if we try
// 'debug(stats::rnorm)' we know not to auto-insert parens)
if (token.contains("::"))
addAutocompletionContextForNamespace(token, context);
// If this is not a file completion, we need to further strip and
// then set the token. Note that the token will have already been
// set if this is a file completion.
token = token.replaceAll(".*[$@:]", "");
if (!isFileCompletion)
context.setToken(token);
// access to the R Code model
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return context;
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
// We might need to grab content from further up in the document than
// the current cursor position -- so tokenize ahead.
codeModel.tokenizeUpToRow(row + 100);
// Make a token cursor and place it at the first token previous
// to the cursor.
TokenCursor tokenCursor = codeModel.getTokenCursor();
if (!tokenCursor.moveToPosition(input_.getCursorPosition()))
return context;
TokenCursor startCursor = tokenCursor.cloneCursor();
// If this is an argument, return auto-completions tuned to that argument
TokenCursor argsCursor = startCursor.cloneCursor();
if (argsCursor.currentType() == "identifier")
argsCursor.moveToPreviousToken();
if (argsCursor.currentValue() == "=")
{
if (argsCursor.moveToPreviousToken())
{
return new AutocompletionContext(
token,
argsCursor.currentValue(),
AutocompletionContext.TYPE_ARGUMENT);
}
}
// Find an opening '(' or '[' -- this provides the function or object
// for completion.
int initialNumCommas = 0;
if (tokenCursor.currentValue() != "(" && tokenCursor.currentValue() != "[")
{
int commaCount = tokenCursor.findOpeningBracketCountCommas(
new String[]{ "[", "(" }, true);
if (commaCount == -1)
{
commaCount = tokenCursor.findOpeningBracketCountCommas("[", false);
if (commaCount == -1)
return context;
else
initialNumCommas = commaCount;
}
else
{
initialNumCommas = commaCount;
}
}
// Figure out whether we're looking at '(', '[', or '[[',
// and place the token cursor on the first token preceding.
TokenCursor endOfDecl = tokenCursor.cloneCursor();
int initialDataType = AutocompletionContext.TYPE_UNKNOWN;
if (tokenCursor.currentValue() == "(")
{
initialDataType = AutocompletionContext.TYPE_FUNCTION;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else if (tokenCursor.currentValue() == "[")
{
if (!tokenCursor.moveToPreviousToken())
return context;
if (tokenCursor.currentValue() == "[")
{
if (!endOfDecl.moveToPreviousToken())
return context;
initialDataType = AutocompletionContext.TYPE_DOUBLE_BRACKET;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else
{
initialDataType = AutocompletionContext.TYPE_SINGLE_BRACKET;
}
}
// Get the string marking the function or data
if (!tokenCursor.findStartOfEvaluationContext())
return context;
// Try to get the function call string -- either there's
// an associated closing paren we can use, or we should just go up
// to the current cursor position
// default case: use start cursor
Position endPos = startCursor.currentPosition();
endPos.setColumn(endPos.getColumn() + startCursor.currentValue().length());
// try to look forward for closing paren
if (endOfDecl.currentValue() == "(")
{
TokenCursor closingParenCursor = endOfDecl.cloneCursor();
if (closingParenCursor.fwdToMatchingToken())
{
endPos = closingParenCursor.currentPosition();
endPos.setColumn(endPos.getColumn() + 1);
}
}
// We can now set the function call string
// We strip the current token so that the matched.call work later on
// can properly resolve the current argument
Position startPosition = startCursor.currentPosition();
if (startCursor.currentValue() == "(")
startPosition.setColumn(startPosition.getColumn() + 1);
String beforeText = editor.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
startPosition));
Position afterTokenPos = startCursor.currentPosition();
if (startCursor.currentType() == "identifier")
afterTokenPos.setColumn(afterTokenPos.getColumn() +
startCursor.currentValue().length());
String afterText = editor.getTextForRange(Range.fromPoints(
afterTokenPos, endPos));
context.setFunctionCallString(
(beforeText + afterText).trim());
String initialData =
docDisplay_.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
endOfDecl.currentPosition())).trim();
// And the first context
context.add(initialData, initialDataType, initialNumCommas);
// Get the rest of the single-bracket contexts for completions as well
String assocData;
int dataType;
int numCommas;
while (true)
{
int commaCount = tokenCursor.findOpeningBracketCountCommas("[", false);
if (commaCount == -1)
break;
numCommas = commaCount;
TokenCursor declEnd = tokenCursor.cloneCursor();
if (!tokenCursor.moveToPreviousToken())
return context;
if (tokenCursor.currentValue() == "[")
{
if (!declEnd.moveToPreviousToken())
return context;
dataType = AutocompletionContext.TYPE_DOUBLE_BRACKET;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else
{
dataType = AutocompletionContext.TYPE_SINGLE_BRACKET;
}
tokenCursor.findStartOfEvaluationContext();
assocData =
docDisplay_.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
declEnd.currentPosition())).trim();
context.add(assocData, dataType, numCommas);
}
return context;
}
public Comparator<QualifiedName> createFuzzyComparator(String query)
{
final String queryLower = query.toLowerCase();
return new Comparator<QualifiedName>() {
@Override
public int compare(final QualifiedName lhs,
final QualifiedName rhs)
{
int lhsScore = CodeSearchOracle.scoreMatch(
lhs.name,
queryLower,
false);
int rhsScore = CodeSearchOracle.scoreMatch(
rhs.name,
queryLower,
false);
if (lhsScore == rhsScore)
{
return lhs.name.length() - rhs.name.length();
}
else
{
return lhsScore < rhsScore ? -1 : 1;
}
}
};
}
/**
* It's important that we create a new instance of this each time.
* It maintains state that is associated with a completion request.
*/
private final class CompletionRequestContext extends
ServerRequestCallback<CompletionResult>
{
public CompletionRequestContext(Invalidation.Token token,
InputEditorSelection selection,
boolean canAutoAccept)
{
invalidationToken_ = token ;
selection_ = selection ;
canAutoAccept_ = canAutoAccept;
}
public void showHelp(QualifiedName selectedItem)
{
helpStrategy_.showHelp(selectedItem, popup_);
}
public void showHelpTopic()
{
helpStrategy_.showHelpTopic(popup_.getSelectedValue());
}
@Override
public void onError(ServerError error)
{
if (invalidationToken_.isInvalid())
return ;
RCompletionManager.this.popup_.showErrorMessage(
error.getUserMessage(),
new PopupPositioner(input_.getCursorBounds(), popup_)) ;
}
@Override
public void onResponseReceived(CompletionResult completions)
{
if (invalidationToken_.isInvalid())
return ;
// Only display the top completions
final QualifiedName[] results =
completions.completions.toArray(new QualifiedName[0]);
if (results.length == 0)
{
popup_.clearCompletions();
boolean lastInputWasTab =
(nativeEvent_ != null && nativeEvent_.getKeyCode() == KeyCodes.KEY_TAB);
boolean lineIsWhitespace = docDisplay_.getCurrentLine().matches("^\\s*$");
if (lastInputWasTab && lineIsWhitespace)
{
docDisplay_.insertCode("\t");
return;
}
if (canAutoAccept_)
{
popup_.showErrorMessage(
"(No matches)",
new PopupPositioner(input_.getCursorBounds(), popup_));
}
else
{
// Show an empty popup message offscreen -- this is a hack to
// ensure that we can get completion results on backspace after a
// failed completion, e.g. 'stats::rna' -> 'stats::rn'
popup_.placeOffscreen();
}
return ;
}
// If there is only one result and the name is identical to the
// current token, then don't display anything
if (results.length == 1 &&
completions.token.equals(results[0].name))
{
return;
}
// Move range to beginning of token; we want to place the popup there.
final String token = completions.token ;
Rectangle rect = input_.getPositionBounds(
selection_.getStart().movePosition(-token.length(), true));
token_ = token;
suggestOnAccept_ = completions.suggestOnAccept;
overrideInsertParens_ = completions.dontInsertParens;
if (results.length == 1
&& canAutoAccept_
&& results[0].type != RCompletionType.DIRECTORY)
{
onSelection(results[0]);
}
else
{
popup_.showCompletionValues(
results,
new PopupPositioner(rect, popup_),
false);
}
}
private void onSelection(QualifiedName qname)
{
suggestTimer_.cancel();
final String value = qname.name ;
if (invalidationToken_.isInvalid())
return;
requester_.flushCache() ;
helpStrategy_.clearCache();
if (value == null)
{
assert false : "Selected comp value is null" ;
return ;
}
applyValue(qname);
if (suggestOnAccept_ || qname.name.endsWith(":"))
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(true, true, false);
}
});
}
else
{
popup_.hide() ;
popup_.clearHelp(false);
popup_.setHelpVisible(false);
}
}
// For input of the form 'something$foo' or 'something@bar', quote the
// element following '@' if it's a non-syntactic R symbol; otherwise
// return as is
private String quoteIfNotSyntacticNameCompletion(String string)
{
if (!string.matches("^[a-zA-Z_.][a-zA-Z0-9_.]*$"))
return "`" + string + "`";
else
return string;
}
private void applyValueRmdOption(final String value)
{
suggestTimer_.cancel();
// If there is no token but spaces have been inserted, then compensate
// for that. This is necessary as we allow for spaces in the completion,
// and completions auto-popup after ',' so e.g. on
//
// ```{r, |}
// ^ -- automatically triggered completion
// ^ -- user inserted spaces
//
// if we accept a completion in that position, we should keep the
// spaces the user inserted. (After the user has inserted a character,
// it becomes part of the token and hence this is unnecessary.
if (token_ == "")
{
int startPos = selection_.getStart().getPosition();
String currentLine = docDisplay_.getCurrentLine();
while (startPos < currentLine.length() &&
currentLine.charAt(startPos) == ' ')
++startPos;
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(startPos, false),
input_.getSelection().getEnd()));
}
else
{
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(-token_.length(), true),
input_.getSelection().getEnd()));
}
input_.replaceSelection(value, true);
token_ = value;
selection_ = input_.getSelection();
}
private void applyValue(final QualifiedName qualifiedName)
{
if (qualifiedName.source == "`chunk-option`")
{
applyValueRmdOption(qualifiedName.name);
return;
}
boolean insertParen =
uiPrefs_.insertParensAfterFunctionCompletion().getValue() &&
RCompletionType.isFunctionType(qualifiedName.type);
// Don't insert a paren if there is already a '(' following
// the cursor
AceEditor editor = (AceEditor) input_;
boolean textFollowingCursorIsOpenParen = false;
boolean textFollowingCursorIsClosingParen = false;
if (editor != null)
{
TokenCursor cursor =
editor.getSession().getMode().getRCodeModel().getTokenCursor();
cursor.moveToPosition(editor.getCursorPosition());
if (cursor.moveToNextToken())
{
textFollowingCursorIsOpenParen =
cursor.currentValue() == "(";
textFollowingCursorIsClosingParen =
cursor.currentValue() == ")" && !cursor.bwdToMatchingToken();
}
}
String value = qualifiedName.name;
String source = qualifiedName.source;
boolean shouldQuote = qualifiedName.shouldQuote;
if (qualifiedName.type == RCompletionType.DIRECTORY)
value = value + "/";
if (!RCompletionType.isFileType(qualifiedName.type))
{
if (value == ":=")
value = quoteIfNotSyntacticNameCompletion(value);
else if (!value.matches(".*[=:]\\s*$") &&
!value.matches("^\\s*([`'\"]).*\\1\\s*$") &&
source != "<file>" &&
source != "<directory>" &&
source != "`chunk-option`" &&
!value.startsWith("@") &&
!shouldQuote)
value = quoteIfNotSyntacticNameCompletion(value);
}
/* In some cases, applyValue can be called more than once
* as part of the same completion instance--specifically,
* if there's only one completion candidate and it is in
* a package. To make sure that the selection movement
* logic works the second time, we need to reset the
* selection.
*/
// Move range to beginning of token
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(-token_.length(), true),
input_.getSelection().getEnd()));
if (insertParen && !overrideInsertParens_ && !textFollowingCursorIsOpenParen)
{
// Don't replace the selection if the token ends with a ')'
// (implies an earlier replacement handled this)
if (token_.endsWith("("))
{
input_.setSelection(new InputEditorSelection(
input_.getSelection().getEnd(),
input_.getSelection().getEnd()));
}
else
{
// If the token after the cursor is already a ')', don't insert
// a closing paren
int relMovement = 0;
if (textFollowingCursorIsClosingParen || !uiPrefs_.insertMatching().getValue())
{
input_.replaceSelection(value + "(", true);
}
else
{
input_.replaceSelection(value + "()", true);
relMovement = -1;
}
// Move the cursor into the newly inserted parens
InputEditorSelection newSelection = new InputEditorSelection(
input_.getSelection().getEnd().movePosition(
relMovement, true));
token_ = value + "(";
selection_ = new InputEditorSelection(
input_.getSelection().getStart().movePosition(
relMovement - 1, true),
newSelection.getStart());
input_.setSelection(newSelection);
}
}
else
{
if (shouldQuote)
value = "\"" + value + "\"";
// don't add spaces around equals if requested
final String kSpaceEquals = " = ";
if (!uiPrefs_.insertSpacesAroundEquals().getValue() &&
value.endsWith(kSpaceEquals))
{
value = value.substring(0, value.length() - kSpaceEquals.length()) + "=";
}
input_.replaceSelection(value, true);
token_ = value;
selection_ = input_.getSelection();
}
// Show a signature popup if we just completed a function
if (RCompletionType.isFunctionType(qualifiedName.type))
displaySignatureToolTip(qualifiedName);
}
private final Invalidation.Token invalidationToken_ ;
private InputEditorSelection selection_ ;
private final boolean canAutoAccept_;
private boolean suggestOnAccept_;
private boolean overrideInsertParens_;
}
private void displaySignatureToolTip(final QualifiedName qualifiedName)
{
// Bail on lack of UI prefs
if (!uiPrefs_.showSignatureTooltips().getValue())
return;
// We want to find the cursor position, and place the popup
// above the cursor.
server_.getArgs(
qualifiedName.name,
qualifiedName.source,
new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String args)
{
if (!StringUtil.isNullOrEmpty(args))
doDisplaySignatureToolTip(qualifiedName.name + args);
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
private void doDisplaySignatureToolTip(String signature)
{
if (sigTip_.isShowing())
sigTip_.hide();
sigTip_.resolvePositionAndShow(signature);
}
private String getSourceDocumentPath()
{
if (rContext_ != null)
return rContext_.getPath();
else
return null;
}
public void showHelpDeferred(final CompletionRequestContext context,
final QualifiedName item,
int milliseconds)
{
if (helpRequest_ != null && helpRequest_.isRunning())
helpRequest_.cancel();
helpRequest_ = new Timer() {
@Override
public void run()
{
if (item.equals(lastSelectedItem_) && popup_.isShowing())
context.showHelp(item);
}
};
helpRequest_.schedule(milliseconds);
}
private GlobalDisplay globalDisplay_;
private FileTypeRegistry fileTypeRegistry_;
private EventBus eventBus_;
private HelpStrategy helpStrategy_;
private UIPrefs uiPrefs_;
private final CodeToolsServerOperations server_;
private final InputEditorDisplay input_ ;
private final NavigableSourceEditor navigableSourceEditor_;
private final CompletionPopupDisplay popup_ ;
private final CompletionRequester requester_ ;
private final InitCompletionFilter initFilter_ ;
// Prevents completion popup from being dismissed when you merely
// click on it to scroll.
private boolean ignoreNextInputBlur_ = false;
private String token_ ;
private final DocDisplay docDisplay_;
private final boolean isConsole_;
private final Invalidation invalidation_ = new Invalidation();
private CompletionRequestContext context_ ;
private final RCompletionContext rContext_;
private final RnwCompletionContext rnwContext_;
private RCompletionToolTip sigTip_;
private NativeEvent nativeEvent_;
private QualifiedName lastSelectedItem_;
private Timer helpRequest_;
private final SuggestionTimer suggestTimer_;
private class SuggestionTimer
{
SuggestionTimer()
{
timer_ = new Timer()
{
@Override
public void run()
{
beginSuggest(
flushCache_,
implicit_,
canAutoInsert_);
}
};
}
public void schedule(boolean flushCache,
boolean implicit,
boolean canAutoInsert)
{
flushCache_ = flushCache;
implicit_ = implicit;
canAutoInsert_ = canAutoInsert;
timer_.schedule(400);
}
public void cancel()
{
timer_.cancel();
}
@SuppressWarnings("unused")
public boolean isRunning()
{
return timer_.isRunning();
}
private boolean flushCache_;
private boolean implicit_;
private boolean canAutoInsert_;
private final Timer timer_;
}
}
| fix markdown link completion
| src/gwt/src/org/rstudio/studio/client/workbench/views/console/shell/assist/RCompletionManager.java | fix markdown link completion | <ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/console/shell/assist/RCompletionManager.java
<ide> String line)
<ide> {
<ide> int index = line.lastIndexOf('(');
<add> String token = line.substring(index + 1);
<add>
<ide> AutocompletionContext result = new AutocompletionContext(
<del> line.substring(index + 1),
<add> token,
<add> token,
<ide> AutocompletionContext.TYPE_FILE);
<ide>
<ide> // NOTE: we overload the meaning of the function call string for file
<ide> // trim to cursor position
<ide> firstLine = firstLine.substring(0, input_.getCursorPosition().getColumn());
<ide>
<del> // Get the token at the cursor position
<del> String token = firstLine.replaceAll(".*[^a-zA-Z0-9._:$@-]", "");
<del>
<ide> // If we're in Markdown mode and have an appropriate string, try to get
<ide> // file completions
<ide> if (DocumentMode.isCursorInMarkdownMode(docDisplay_) &&
<ide> firstLine.matches(".*\\[.*\\]\\(.*"))
<ide> return getAutocompletionContextForFileMarkdownLink(firstLine);
<add>
<add> // Get the token at the cursor position
<add> String token = firstLine.replaceAll(".*[^a-zA-Z0-9._:$@-]", "");
<ide>
<ide> // If we're completing an object within a string, assume it's a
<ide> // file-system completion. Note that we may need other contextual information |
|
Java | apache-2.0 | 6af4ed2f0e011dc4f61975334c0c89a8ad16d828 | 0 | ProgrammingLife2017/Desoxyribonucleinezuur | package programminglife.gui.controller;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.*;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import jp.uphy.javafx.console.ConsoleView;
import programminglife.ProgrammingLife;
import programminglife.gui.Alerts;
import programminglife.gui.NumbersOnlyListener;
import programminglife.gui.ResizableCanvas;
import programminglife.model.GenomeGraph;
import programminglife.model.drawing.*;
import programminglife.parser.GraphParser;
import programminglife.parser.ProgressCounter;
import programminglife.utility.Console;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;
/**
* The controller for the GUI that is used in the application.
* The @FXML tag is needed in initialize so that javaFX knows what to do.
*/
public class GuiController implements Observer {
//static finals
private static final String INITIAL_CENTER_NODE = "1";
private static final String INITIAL_MAX_DRAW_DEPTH = "10";
//FXML imports.
@FXML private MenuItem btnOpenGFA;
@FXML private MenuItem btnQuit;
@FXML private MenuItem btnBookmarks;
@FXML private MenuItem btnAbout;
@FXML private MenuItem btnInstructions;
@FXML private Menu menuRecentGFA;
@FXML private RadioMenuItem btnDark;
@FXML private RadioMenuItem btnSNP;
@FXML private RadioMenuItem btnConsole;
@FXML private RadioMenuItem btnMiniMap;
@FXML private Button btnZoomReset;
@FXML private Button btnDraw;
@FXML private Button btnDrawRandom;
@FXML private Button btnBookmark;
@FXML private Button btnClipboard;
@FXML private Button btnClipboard2;
@FXML private ProgressBar progressBar;
@FXML private Tab searchTab;
@FXML private TextField txtMaxDrawDepth;
@FXML private TextField txtCenterNode;
@FXML private ResizableCanvas canvas;
@FXML private AnchorPane anchorLeftControlPanel;
@FXML private AnchorPane anchorGraphPanel;
@FXML private AnchorPane anchorGraphInfo;
@FXML private Canvas miniMap;
private double orgSceneX, orgSceneY;
private double scale;
private GraphController graphController;
private RecentFileController recentFileControllerGFA;
private MiniMapController miniMapController;
private HighlightController highlightController;
private File file;
private File recentFileGFA = new File("RecentGFA.txt");
private Thread parseThread;
private final ExtensionFilter extFilterGFA = new ExtensionFilter("GFA files (*.gfa)", "*.GFA");
private static final double MAX_SCALE = 10.0d;
private static final double MIN_SCALE = .02d;
private static final double ZOOM_FACTOR = 1.05d;
/**
* The initialize will call the other methods that are run in the .
*/
@FXML
@SuppressWarnings("unused")
private void initialize() {
this.graphController = new GraphController(this.canvas);
this.scale = 1;
this.recentFileControllerGFA = new RecentFileController(this.recentFileGFA, this.menuRecentGFA);
this.recentFileControllerGFA.setGuiController(this);
initMenuBar();
initBookmarkMenu();
initLeftControlpanelScreenModifiers();
initLeftControlpanelDraw();
initMouse();
initShowInfoTab();
initConsole();
initRightSearchTab();
}
/**
* Open and parse a GFA file.
*
* @param file The {@link File} to open.
* @return the parser to be notified when it is finished
*/
public GraphParser openFile(File file) {
if (file != null) {
if (this.graphController != null && this.graphController.getGraph() != null) {
this.graphController.resetClicked();
this.graphController.getGraph().close();
this.canvas.getGraphicsContext2D().clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
}
disableGraphUIElements(true);
GraphParser graphParser = new GraphParser(file);
graphParser.addObserver(this);
graphParser.getProgressCounter().addObserver(this);
if (this.parseThread != null) {
this.parseThread.interrupt();
}
this.parseThread = new Thread(graphParser);
this.parseThread.start();
this.setFile(file);
return graphParser;
}
return null;
}
@Override
public void update(Observable o, Object arg) {
if (o instanceof GraphParser) {
if (arg instanceof GenomeGraph) {
GenomeGraph graph = (GenomeGraph) arg;
Console.println("[%s] File Parsed.", Thread.currentThread().getName());
this.setGraph(graph);
} else if (arg instanceof Exception) {
Exception e = (Exception) arg;
e.printStackTrace();
Alerts.error(e.getMessage());
} else if (arg instanceof String) {
String msg = (String) arg;
Platform.runLater(() -> ProgrammingLife.getStage().setTitle(msg));
}
} else if (o instanceof ProgressCounter) {
progressBar.setVisible(true);
ProgressCounter progress = (ProgressCounter) o;
this.getProgressBar().setProgress(progress.percentage());
if (progressBar.getProgress() == 1.0d) {
progressBar.setVisible(false);
}
}
}
/**
* Set the graph for this GUIController.
*
* @param graph {@link GenomeGraph} to use.
*/
private void setGraph(GenomeGraph graph) {
this.graphController.setGraph(graph);
disableGraphUIElements(graph == null);
searchTab.setDisable(graph == null);
Platform.runLater(() -> {
assert graph != null;
ProgrammingLife.getStage().setTitle(graph.getID());
});
if (graph != null) {
this.miniMapController = new MiniMapController(this.miniMap, graph.size());
Platform.runLater(() -> highlightController.initGenome());
graphController.setHighlightController(highlightController);
miniMap.setWidth(anchorGraphPanel.getWidth());
miniMap.setHeight(50.d);
Console.println("[%s] Graph was set to %s.", Thread.currentThread().getName(), graph.getID());
Console.println("[%s] The graph has %d nodes", Thread.currentThread().getName(), graph.size());
Platform.runLater(this::draw);
}
}
/**
* Handles the fileChooser when open a file.
*
* @param filter ExtensionFilter of which file type to open.
* @param isGFA boolean to check if it is a GFA file.
*/
private void fileChooser(ExtensionFilter filter, boolean isGFA) {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(filter);
if (file != null) {
File existDirectory = file.getParentFile();
fileChooser.setInitialDirectory(existDirectory);
}
file = fileChooser.showOpenDialog(ProgrammingLife.getStage());
if (file != null) {
if (isGFA) {
this.openFile(file);
Platform.runLater(() -> {
File recentFileGFA = recentFileControllerGFA.getRecentFile();
recentFileControllerGFA.updateRecent(recentFileGFA, file);
});
}
}
}
/**
* Initializes the open button so that the user can decide which file to open.
* Sets the action for the open MenuItem.
* Sets the event for the quit MenuItem.
*/
private void initMenuBar() {
btnOpenGFA.setOnAction((ActionEvent event) -> fileChooser(extFilterGFA, true));
btnOpenGFA.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCodeCombination.CONTROL_DOWN));
btnQuit.setOnAction(event -> Alerts.quitAlert());
btnQuit.setAccelerator(new KeyCodeCombination(KeyCode.Q, KeyCodeCombination.CONTROL_DOWN));
btnAbout.setOnAction(event -> Alerts.infoAboutAlert());
btnAbout.setAccelerator(new KeyCodeCombination(KeyCode.I, KeyCodeCombination.CONTROL_DOWN));
btnInstructions.setOnAction(event -> Alerts.infoInstructionAlert());
btnInstructions.setAccelerator(new KeyCodeCombination(KeyCode.H, KeyCodeCombination.CONTROL_DOWN));
btnMiniMap.setOnAction(event -> miniMapController.toggleVisibility());
btnMiniMap.setAccelerator(new KeyCodeCombination(KeyCode.M, KeyCodeCombination.CONTROL_DOWN));
btnSNP.setOnAction(event -> {
graphController.setSNP();
Platform.runLater(this::draw);
});
btnSNP.setAccelerator(new KeyCodeCombination(KeyCode.G, KeyCodeCombination.CONTROL_DOWN));
btnDark.setOnAction(event -> ProgrammingLife.toggleCSS());
btnDark.setAccelerator(new KeyCodeCombination(KeyCode.Z, KeyCodeCombination.CONTROL_DOWN));
}
/**
* Initializes the bookmark buttons in the menu.
*/
private void initBookmarkMenu() {
btnBookmarks.setOnAction(event -> {
try {
FXMLLoader loader = new FXMLLoader(ProgrammingLife.class.getResource("/LoadBookmarkWindow.fxml"));
AnchorPane page = loader.load();
GuiLoadBookmarkController gc = loader.getController();
gc.setGuiController(this);
gc.initBookmarks();
if (this.graphController.getGraph() != null) {
gc.setBtnCreateBookmarkActive();
}
Scene scene = new Scene(page);
Stage bookmarkDialogStage = new Stage();
bookmarkDialogStage.setResizable(false);
bookmarkDialogStage.setScene(scene);
bookmarkDialogStage.setTitle("Load Bookmark");
bookmarkDialogStage.initOwner(ProgrammingLife.getStage());
bookmarkDialogStage.showAndWait();
} catch (IOException e) {
Alerts.error("The bookmarks file can't be opened");
}
});
btnBookmarks.setAccelerator(new KeyCodeCombination(KeyCode.B, KeyCodeCombination.CONTROL_DOWN));
}
/**
* Method to disable the UI Elements on the left of the GUI.
*
* @param isDisabled boolean, true disables the left anchor panel.
*/
private void disableGraphUIElements(boolean isDisabled) {
anchorLeftControlPanel.setDisable(isDisabled);
}
/**
* Initializes the buttons on the panel on the left side which do translation/zoom.
*/
private void initLeftControlpanelScreenModifiers() {
disableGraphUIElements(true);
btnZoomReset.setOnAction(event -> {
this.draw();
});
}
/**
* Method to reset the zoom levels.
*/
private void resetZoom() {
graphController.resetZoom();
scale = 1;
canvas.setScaleX(1);
canvas.setScaleY(1);
}
/**
* Initializes the button on the left side that are used to draw the graph.
*/
private void initLeftControlpanelDraw() {
disableGraphUIElements(true);
btnDraw.setOnAction(e -> this.draw());
btnDrawRandom.setOnAction(event -> {
int randomNodeID = (new Random()).nextInt(this.graphController.getGraph().size() - 1) + 1;
txtCenterNode.setText(Integer.toString(randomNodeID));
this.draw();
});
btnBookmark.setOnAction(event -> buttonBookmark());
txtMaxDrawDepth.textProperty().addListener(new NumbersOnlyListener(txtMaxDrawDepth));
txtMaxDrawDepth.setText(INITIAL_MAX_DRAW_DEPTH);
txtCenterNode.textProperty().addListener(new NumbersOnlyListener(txtCenterNode));
txtCenterNode.setText(INITIAL_CENTER_NODE);
}
/**
* Draw the current graph with current center node and depth settings.
*/
void draw() {
Console.println("[%s] Drawing graph...", Thread.currentThread().getName());
graphController.resetClicked();
int centerNode = 0;
int maxDepth = 0;
scale = 1;
try {
centerNode = Integer.parseInt(txtCenterNode.getText());
try {
maxDepth = Integer.parseInt(txtMaxDrawDepth.getText());
} catch (NumberFormatException e) {
Alerts.warning("Radius is not a number, try again with a number as input.");
}
} catch (NumberFormatException e) {
Alerts.warning("Center node ID is not a number, try again with a number as input.");
}
if (centerNode > getGraphController().getGraph().size()) {
centerNode = 1;
}
if (graphController.getGraph().contains(centerNode)) {
this.graphController.clear();
this.graphController.draw(centerNode, maxDepth);
this.miniMapController.showPosition(centerNode);
resetZoom();
Console.println("[%s] Graph drawn.", Thread.currentThread().getName());
} else {
Alerts.warning("The centernode is not a existing node, try again with a number that exists as a node.");
}
}
/**
* Handles the events of the bookmark button.
*/
private void buttonBookmark() {
try {
FXMLLoader loader = new FXMLLoader(ProgrammingLife.class.getResource("/CreateBookmarkWindow.fxml"));
AnchorPane page = loader.load();
GuiCreateBookmarkController gc = loader.getController();
gc.setGuiController(this);
gc.setText(txtCenterNode.getText(), txtMaxDrawDepth.getText());
Scene scene = new Scene(page);
Stage bookmarkDialogStage = new Stage();
bookmarkDialogStage.setResizable(false);
bookmarkDialogStage.setScene(scene);
bookmarkDialogStage.setTitle("Create Bookmark");
bookmarkDialogStage.initOwner(ProgrammingLife.getStage());
bookmarkDialogStage.showAndWait();
} catch (IOException e) {
Alerts.error("This bookmark cannot be created.");
}
}
/**
* Initialises the mouse events.
*/
private void initMouse() {
anchorGraphPanel.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
orgSceneX = event.getSceneX();
orgSceneY = event.getSceneY();
});
canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
if (event.isShiftDown() || event.getButton() == MouseButton.SECONDARY) {
mouseClick(event.getX(), event.getY(), true);
} else {
mouseClick(event.getX(), event.getY(), false);
}
});
anchorGraphPanel.addEventHandler(MouseEvent.MOUSE_DRAGGED, event -> {
double xDifference = event.getSceneX() - orgSceneX;
double yDifference = event.getSceneY() - orgSceneY;
orgSceneX += xDifference;
orgSceneY += yDifference;
graphController.translate(xDifference, yDifference);
event.consume();
});
anchorGraphPanel.addEventHandler(ScrollEvent.SCROLL, event ->
zoom(event.getDeltaX(), event.getDeltaY(), event.getSceneX(), event.getSceneY()));
}
/**
* Mouse click method that does the show info handling.
*
* @param x coordinate where is clicked.
* @param y coordinate where is clicked.
* @param shiftPressed boolean if shift is pressed it should be displayed in panel 2.
*/
private void mouseClick(double x, double y, boolean shiftPressed) {
Drawable clickedOn = graphController.onClick(x, y);
if (clickedOn != null) {
if (clickedOn instanceof DrawableSNP) {
DrawableSNP snp = (DrawableSNP) clickedOn;
if (shiftPressed) {
showInfoSNP(snp, 240);
} else {
showInfoSNP(snp, 10);
}
graphController.highlightClicked(null, snp, shiftPressed);
} else if (clickedOn instanceof DrawableSegment) {
DrawableSegment segment = (DrawableSegment) clickedOn;
if (shiftPressed) {
showInfoNode(segment, 240);
} else {
showInfoNode(segment, 10);
}
graphController.highlightClicked(segment, null, shiftPressed);
} else if (clickedOn instanceof DrawableEdge) {
DrawableEdge edge = (DrawableEdge) clickedOn;
if (shiftPressed) {
showInfoEdge(edge, 240);
} else {
showInfoEdge(edge, 10);
}
// graphController.highlightClicked(edge, shiftPressed); TODO FIX.
}
}
}
/**
* Handles the zooming in and out of the group.
*
* @param deltaX The scroll amount in the X direction. See {@link ScrollEvent#getDeltaX()}
* @param deltaY The scroll amount in the Y direction. See {@link ScrollEvent#getDeltaY()}
* @param sceneX double for the x location.
* @param sceneY double for the y location.
*/
private void zoom(double deltaX, double deltaY, double sceneX, double sceneY) {
double oldScale = scale;
if (deltaX < 0 || deltaY < 0) {
scale *= ZOOM_FACTOR;
} else {
scale /= ZOOM_FACTOR;
}
scale = clamp(scale);
double factor = (scale / oldScale) - 1;
graphController.zoom(factor + 1);
//factor to determine the difference in the scales.
Bounds bounds = canvas.localToScene(canvas.getBoundsInLocal());
double dx = (sceneX - bounds.getMinX());
double dy = (sceneY - bounds.getMinY());
graphController.translate(factor * dx, factor * dy);
}
/**
* Clamp function used for zooming in and out.
*
* @param value double current scale.
* @return double scale value.
*/
private static double clamp(double value) {
if (Double.compare(value, GuiController.MIN_SCALE) < 0) {
return GuiController.MIN_SCALE;
}
if (Double.compare(value, GuiController.MAX_SCALE) > 0) {
return GuiController.MAX_SCALE;
}
return value;
}
/**
* Initialises the Console.
*/
private void initConsole() {
final ConsoleView console = new ConsoleView(Charset.forName("UTF-8"));
AnchorPane root = new AnchorPane(console);
Stage st = new Stage();
st.setScene(new Scene(root, 500, 500, Color.GRAY));
st.setMinWidth(500);
st.setMinHeight(250);
AnchorPane.setBottomAnchor(console, 0.d);
AnchorPane.setTopAnchor(console, 0.d);
AnchorPane.setRightAnchor(console, 0.d);
AnchorPane.setLeftAnchor(console, 0.d);
btnConsole.setOnAction(event -> {
if (btnConsole.isSelected()) {
st.show();
} else {
st.close();
}
});
st.show();
btnConsole.setSelected(true);
root.visibleProperty().bind(btnConsole.selectedProperty());
Console.setOut(console.getOut());
}
/**
* Initializes the search tab in the left panel.
* Button to be disabled without a graph loaded.
*/
private void initRightSearchTab() {
try {
FXMLLoader loader = new FXMLLoader(ProgrammingLife.class.getResource("/HighlightWindow.fxml"));
AnchorPane page = loader.load();
highlightController = loader.getController();
highlightController.setGraphController(this.getGraphController());
searchTab.setContent(page);
searchTab.setDisable(true);
searchTab.setOnSelectionChanged(event -> highlightController.initMinMax());
} catch (IOException e) {
e.printStackTrace();
}
}
private ProgressBar getProgressBar() {
return this.progressBar;
}
/**
* Initializes the info tab.
*/
private void initShowInfoTab() {
btnClipboard.setOnAction(event -> copyToClipboard(10));
btnClipboard2.setOnAction(event -> copyToClipboard(240));
}
/**
* Copies information to the clipboard.
*
* @param x int used in the ID, to know which sequence to get.
*/
private void copyToClipboard(int x) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
String toClipboard = "";
for (Node node : anchorGraphInfo.getChildren()) {
if (node instanceof TextArea && node.getId().equals(x + " Sequence: ")) {
toClipboard = toClipboard.concat(((TextArea) node).getText()) + System.getProperty("line.separator");
toClipboard = toClipboard.replaceAll("(.{100})", "$1" + System.getProperty("line.separator"));
}
}
StringSelection selection = new StringSelection(toClipboard);
clipboard.setContents(selection, selection);
}
/**
* Sets the text field for drawing the graph.
*
* @param center The center node
* @param radius The radius of the subGraph
*/
void setText(int center, int radius) {
txtCenterNode.setText(String.valueOf(center));
txtMaxDrawDepth.setText(String.valueOf(radius));
}
/**
* Method to show the information of an edge.
*
* @param edge DrawableEdge the edge which has been clicked on.
* @param x int the x location of the TextField.
*/
private void showInfoEdge(DrawableEdge edge, int x) {
Text parentsText = makeText(x, 65, "Parent: ");
Text childrenText = makeText(x, 105, "Child: ");
Text idText = makeText(x, 145, "Genomes: ");
TextField parent = makeTextField("Parent Node: ", x, 70,
Integer.toString(edge.getStart().getParentSegment().getIdentifier()));
TextField child = makeTextField("Child Node: ", x, 110,
Integer.toString(edge.getEnd().getChildSegment().getIdentifier()));
Collection<Integer> genomesEdge = graphController.getGenomesEdge(edge);
TextArea genomes = null;
if (genomesEdge != null) {
String result = graphController.getGraph().getGenomeNames(genomesEdge).toString();
genomes = makeTextArea("Genomes: ", x, 150, result.substring(1, result.length() - 1), 80);
genomes.setWrapText(true);
}
anchorGraphInfo.getChildren().removeIf(node1 -> node1.getLayoutX() == x);
anchorGraphInfo.getChildren().addAll(idText, parentsText, childrenText, genomes, parent, child);
}
/**
* Method to show the information of a node.
*
* @param node DrawableSegment the node which has been clicked on.
* @param x int the x location of the TextField.
*/
private void showInfoNode(DrawableSegment node, int x) {
Text idText = makeText(x, 65, "ID: ");
Text parentText = makeText(x, 105, "Parents: ");
Text childText = makeText(x, 145, "Children: ");
Text inEdgeText = makeText(x, 185, "Incoming Edges: ");
Text outEdgeText = makeText(x, 225, "Outgoing Edges: ");
Text seqLengthText = makeText(x, 265, "Sequence Length: ");
Text genomeText = makeText(x, 305, "Genomes: ");
Text seqText = makeText(x, 370, "Sequence: ");
TextField idTextField = makeTextField("ID: ", x, 70, Integer.toString(node.getIdentifier()));
StringBuilder parentSB = new StringBuilder();
graphController.getParentSegments(node).forEach(
parentNode -> parentSB.append(parentNode.getIdentifier()).append(", "));
TextField parents;
if (parentSB.length() > 2) {
parentSB.setLength(parentSB.length() - 2);
parents = makeTextField("Parents: ", x, 110, parentSB.toString());
} else {
parentSB.replace(0, parentSB.length(), "This node has no parent");
parents = makeTextField("Parents: ", x, 110, parentSB.toString());
}
StringBuilder childSB = new StringBuilder();
graphController.getChildSegments(node).forEach(
childNode -> childSB.append(childNode.getIdentifier()).append(", "));
TextField children;
if (childSB.length() > 2) {
childSB.setLength(childSB.length() - 2);
children = makeTextField("Children: ", x, 150, childSB.toString());
} else {
childSB.replace(0, childSB.length(), "This node has no child");
children = makeTextField("Children: ", x, 150, childSB.toString());
}
String genomesString = graphController.getGraph().getGenomeNames(node.getGenomes()).toString();
String sequenceString = node.getSequence().replaceAll("(.{23})", "$1" + System.getProperty("line.separator"));
TextField inEdges = makeTextField("Incoming Edges: ", x, 190, Integer.toString(node.getParents().size()));
TextField outEdges = makeTextField("Outgoing Edges: ", x, 230, Integer.toString(node.getChildren().size()));
TextField seqLength = makeTextField("Sequence Length: ", x, 270, Integer.toString(node.getSequence().length()));
TextArea genome = makeTextArea("Genome: ", x, 310, genomesString.substring(1, genomesString.length() - 1), 40);
genome.setWrapText(true);
TextArea seq = makeTextArea(x + " Sequence: ", x, 375, sequenceString, 250);
anchorGraphInfo.getChildren().removeIf(node1 -> node1.getLayoutX() == x);
anchorGraphInfo.getChildren().addAll(idText, parentText, childText, inEdgeText, outEdgeText, seqLengthText,
genomeText, seqText, idTextField, parents, children, inEdges, outEdges, genome, seqLength, seq);
}
/**
* Method to show the information of an SNP.
*
* @param snp DrawableSegment the node which has been clicked on.
* @param x int the x location of the TextField.
*/
private void showInfoSNP(DrawableSNP snp, int x) {
Text idParent = makeText(x, 65, "Parent: ");
Text idChild = makeText(x, 105, "Child: ");
Text idMutation = makeText(x, 145, "Mutation: ");
Text idGenome = makeText(x, 185, "Genome: ");
TextField parentTextField = makeTextField("Parent: ", x, 70,
Integer.toString(snp.getParent().getParentSegment().getIdentifier()));
TextField childTextField = makeTextField("Child: ", x, 110,
Integer.toString(snp.getChild().getChildSegment().getIdentifier()));
String c = snp.getMutations().stream().map(DrawableSegment::getSequence).collect(Collectors.toSet()).toString();
TextField mutationTextField = makeTextField("Mutation: ", x, 150, c.substring(1, c.length() - 1));
String genomesString = graphController.getGraph().getGenomeNames(snp.getGenomes()).toString();
TextArea genomeTextField = makeTextArea("Genome: ", x, 190,
genomesString.substring(1, genomesString.length() - 1), 80);
genomeTextField.setWrapText(true);
anchorGraphInfo.getChildren().removeIf(node1 -> node1.getLayoutX() == x);
anchorGraphInfo.getChildren().addAll(idParent, idChild, idMutation, idGenome,
parentTextField, childTextField, mutationTextField, genomeTextField);
}
/**
* Returns a textField to be used by the edge and node information show panel.
*
* @param x int the x coordinate of the textField inside the anchorPane.
* @param y int the y coordinate of the textField inside the anchorPane.
* @param s String the text to be shown by the textField.
* @return Text the created textField.
*/
private Text makeText(int x, int y, String s) {
Text text = new Text(s);
text.setLayoutX(x);
text.setLayoutY(y);
return text;
}
/**
* Returns a textField to be used by the edge and node information show panel.
*
* @param id String the id of the textField.
* @param x int the x coordinate of the textField inside the anchorPane.
* @param y int the y coordinate of the textField inside the anchorPane.
* @param text String the text to be shown by the textField.
* @return TextField the created textField.
*/
private TextField makeTextField(String id, int x, int y, String text) {
TextField textField = new TextField();
textField.setId(id);
textField.setText(text);
textField.setLayoutX(x);
textField.setLayoutY(y);
textField.setEditable(false);
textField.setPrefSize(220, 20);
return textField;
}
/**
* Returns a textField to be used by the edge and node information show panel.
*
* @param id String the id of the textField.
* @param x int the x coordinate of the textField inside the anchorPane.
* @param y int the y coordinate of the textField inside the anchorPane.
* @param text String the text to be shown by the textField.
* @param height int of the height of the area.
* @return TextField the created textField.
*/
private TextArea makeTextArea(String id, int x, int y, String text, int height) {
TextArea textArea = new TextArea();
textArea.setId(id);
textArea.setText(text);
textArea.setLayoutX(x);
textArea.setLayoutY(y);
textArea.setEditable(false);
textArea.setPrefSize(225, height);
return textArea;
}
public File getFile() {
return this.file;
}
public void setFile(File file) {
this.file = file;
}
GraphController getGraphController() {
return this.graphController;
}
}
| src/main/java/programminglife/gui/controller/GuiController.java | package programminglife.gui.controller;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.*;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import jp.uphy.javafx.console.ConsoleView;
import programminglife.ProgrammingLife;
import programminglife.gui.Alerts;
import programminglife.gui.NumbersOnlyListener;
import programminglife.gui.ResizableCanvas;
import programminglife.model.GenomeGraph;
import programminglife.model.drawing.*;
import programminglife.parser.GraphParser;
import programminglife.parser.ProgressCounter;
import programminglife.utility.Console;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;
/**
* The controller for the GUI that is used in the application.
* The @FXML tag is needed in initialize so that javaFX knows what to do.
*/
public class GuiController implements Observer {
//static finals
private static final String INITIAL_CENTER_NODE = "1";
private static final String INITIAL_MAX_DRAW_DEPTH = "10";
//FXML imports.
@FXML private MenuItem btnOpenGFA;
@FXML private MenuItem btnQuit;
@FXML private MenuItem btnBookmarks;
@FXML private MenuItem btnAbout;
@FXML private MenuItem btnInstructions;
@FXML private Menu menuRecentGFA;
@FXML private RadioMenuItem btnDark;
@FXML private RadioMenuItem btnSNP;
@FXML private RadioMenuItem btnConsole;
@FXML private RadioMenuItem btnMiniMap;
@FXML private Button btnZoomReset;
@FXML private Button btnDraw;
@FXML private Button btnDrawRandom;
@FXML private Button btnBookmark;
@FXML private Button btnClipboard;
@FXML private Button btnClipboard2;
@FXML private ProgressBar progressBar;
@FXML private Tab searchTab;
@FXML private TextField txtMaxDrawDepth;
@FXML private TextField txtCenterNode;
@FXML private ResizableCanvas canvas;
@FXML private AnchorPane anchorLeftControlPanel;
@FXML private AnchorPane anchorGraphPanel;
@FXML private AnchorPane anchorGraphInfo;
@FXML private Canvas miniMap;
private double orgSceneX, orgSceneY;
private double scale;
private GraphController graphController;
private RecentFileController recentFileControllerGFA;
private MiniMapController miniMapController;
private HighlightController highlightController;
private File file;
private File recentFileGFA = new File("RecentGFA.txt");
private Thread parseThread;
private final ExtensionFilter extFilterGFA = new ExtensionFilter("GFA files (*.gfa)", "*.GFA");
private static final double MAX_SCALE = 10.0d;
private static final double MIN_SCALE = .02d;
private static final double ZOOM_FACTOR = 1.05d;
/**
* The initialize will call the other methods that are run in the .
*/
@FXML
@SuppressWarnings("unused")
private void initialize() {
this.graphController = new GraphController(this.canvas);
this.scale = 1;
this.recentFileControllerGFA = new RecentFileController(this.recentFileGFA, this.menuRecentGFA);
this.recentFileControllerGFA.setGuiController(this);
initMenuBar();
initBookmarkMenu();
initLeftControlpanelScreenModifiers();
initLeftControlpanelDraw();
initMouse();
initShowInfoTab();
initConsole();
initRightSearchTab();
}
/**
* Open and parse a GFA file.
*
* @param file The {@link File} to open.
* @return the parser to be notified when it is finished
*/
public GraphParser openFile(File file) {
if (file != null) {
if (this.graphController != null && this.graphController.getGraph() != null) {
this.graphController.resetClicked();
this.graphController.getGraph().close();
this.canvas.getGraphicsContext2D().clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
}
disableGraphUIElements(true);
GraphParser graphParser = new GraphParser(file);
graphParser.addObserver(this);
graphParser.getProgressCounter().addObserver(this);
if (this.parseThread != null) {
this.parseThread.interrupt();
}
this.parseThread = new Thread(graphParser);
this.parseThread.start();
this.setFile(file);
return graphParser;
}
return null;
}
@Override
public void update(Observable o, Object arg) {
if (o instanceof GraphParser) {
if (arg instanceof GenomeGraph) {
GenomeGraph graph = (GenomeGraph) arg;
Console.println("[%s] File Parsed.", Thread.currentThread().getName());
this.setGraph(graph);
} else if (arg instanceof Exception) {
Exception e = (Exception) arg;
e.printStackTrace();
Alerts.error(e.getMessage());
} else if (arg instanceof String) {
String msg = (String) arg;
Platform.runLater(() -> ProgrammingLife.getStage().setTitle(msg));
}
} else if (o instanceof ProgressCounter) {
progressBar.setVisible(true);
ProgressCounter progress = (ProgressCounter) o;
this.getProgressBar().setProgress(progress.percentage());
if (progressBar.getProgress() == 1.0d) {
progressBar.setVisible(false);
}
}
}
/**
* Set the graph for this GUIController.
*
* @param graph {@link GenomeGraph} to use.
*/
private void setGraph(GenomeGraph graph) {
this.graphController.setGraph(graph);
disableGraphUIElements(graph == null);
searchTab.setDisable(graph == null);
Platform.runLater(() -> {
assert graph != null;
ProgrammingLife.getStage().setTitle(graph.getID());
});
if (graph != null) {
this.miniMapController = new MiniMapController(this.miniMap, graph.size());
Platform.runLater(() -> highlightController.initGenome());
graphController.setHighlightController(highlightController);
miniMap.setWidth(anchorGraphPanel.getWidth());
miniMap.setHeight(50.d);
Console.println("[%s] Graph was set to %s.", Thread.currentThread().getName(), graph.getID());
Console.println("[%s] The graph has %d nodes", Thread.currentThread().getName(), graph.size());
Platform.runLater(this::draw);
}
}
/**
* Handles the fileChooser when open a file.
*
* @param filter ExtensionFilter of which file type to open.
* @param isGFA boolean to check if it is a GFA file.
*/
private void fileChooser(ExtensionFilter filter, boolean isGFA) {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(filter);
if (file != null) {
File existDirectory = file.getParentFile();
fileChooser.setInitialDirectory(existDirectory);
}
file = fileChooser.showOpenDialog(ProgrammingLife.getStage());
if (file != null) {
if (isGFA) {
this.openFile(file);
Platform.runLater(() -> {
File recentFileGFA = recentFileControllerGFA.getRecentFile();
recentFileControllerGFA.updateRecent(recentFileGFA, file);
});
}
}
}
/**
* Initializes the open button so that the user can decide which file to open.
* Sets the action for the open MenuItem.
* Sets the event for the quit MenuItem.
*/
private void initMenuBar() {
btnOpenGFA.setOnAction((ActionEvent event) -> fileChooser(extFilterGFA, true));
btnOpenGFA.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCodeCombination.CONTROL_DOWN));
btnQuit.setOnAction(event -> Alerts.quitAlert());
btnQuit.setAccelerator(new KeyCodeCombination(KeyCode.Q, KeyCodeCombination.CONTROL_DOWN));
btnAbout.setOnAction(event -> Alerts.infoAboutAlert());
btnAbout.setAccelerator(new KeyCodeCombination(KeyCode.I, KeyCodeCombination.CONTROL_DOWN));
btnInstructions.setOnAction(event -> Alerts.infoInstructionAlert());
btnInstructions.setAccelerator(new KeyCodeCombination(KeyCode.H, KeyCodeCombination.CONTROL_DOWN));
btnMiniMap.setOnAction(event -> miniMapController.toggleVisibility());
btnMiniMap.setAccelerator(new KeyCodeCombination(KeyCode.M, KeyCodeCombination.CONTROL_DOWN));
btnSNP.setOnAction(event -> {
graphController.setSNP();
Platform.runLater(this::draw);
});
btnSNP.setAccelerator(new KeyCodeCombination(KeyCode.G, KeyCodeCombination.CONTROL_DOWN));
btnDark.setOnAction(event -> ProgrammingLife.toggleCSS());
btnDark.setAccelerator(new KeyCodeCombination(KeyCode.Z, KeyCodeCombination.CONTROL_DOWN));
}
/**
* Initializes the bookmark buttons in the menu.
*/
private void initBookmarkMenu() {
btnBookmarks.setOnAction(event -> {
try {
FXMLLoader loader = new FXMLLoader(ProgrammingLife.class.getResource("/LoadBookmarkWindow.fxml"));
AnchorPane page = loader.load();
GuiLoadBookmarkController gc = loader.getController();
gc.setGuiController(this);
gc.initBookmarks();
if (this.graphController.getGraph() != null) {
gc.setBtnCreateBookmarkActive();
}
Scene scene = new Scene(page);
Stage bookmarkDialogStage = new Stage();
bookmarkDialogStage.setResizable(false);
bookmarkDialogStage.setScene(scene);
bookmarkDialogStage.setTitle("Load Bookmark");
bookmarkDialogStage.initOwner(ProgrammingLife.getStage());
bookmarkDialogStage.showAndWait();
} catch (IOException e) {
Alerts.error("The bookmarks file can't be opened");
}
});
btnBookmarks.setAccelerator(new KeyCodeCombination(KeyCode.B, KeyCodeCombination.CONTROL_DOWN));
}
/**
* Method to disable the UI Elements on the left of the GUI.
*
* @param isDisabled boolean, true disables the left anchor panel.
*/
private void disableGraphUIElements(boolean isDisabled) {
anchorLeftControlPanel.setDisable(isDisabled);
}
/**
* Initializes the buttons on the panel on the left side which do translation/zoom.
*/
private void initLeftControlpanelScreenModifiers() {
disableGraphUIElements(true);
btnZoomReset.setOnAction(event -> {
this.draw();
});
}
/**
* Method to reset the zoom levels.
*/
private void resetZoom() {
graphController.resetZoom();
scale = 1;
canvas.setScaleX(1);
canvas.setScaleY(1);
}
/**
* Initializes the button on the left side that are used to draw the graph.
*/
private void initLeftControlpanelDraw() {
disableGraphUIElements(true);
btnDraw.setOnAction(e -> this.draw());
btnDrawRandom.setOnAction(event -> {
int randomNodeID = (new Random()).nextInt(this.graphController.getGraph().size() - 1) + 1;
txtCenterNode.setText(Integer.toString(randomNodeID));
this.draw();
});
btnBookmark.setOnAction(event -> buttonBookmark());
txtMaxDrawDepth.textProperty().addListener(new NumbersOnlyListener(txtMaxDrawDepth));
txtMaxDrawDepth.setText(INITIAL_MAX_DRAW_DEPTH);
txtCenterNode.textProperty().addListener(new NumbersOnlyListener(txtCenterNode));
txtCenterNode.setText(INITIAL_CENTER_NODE);
}
/**
* Draw the current graph with current center node and depth settings.
*/
void draw() {
Console.println("[%s] Drawing graph...", Thread.currentThread().getName());
graphController.resetClicked();
int centerNode = 0;
int maxDepth = 0;
scale = 1;
try {
centerNode = Integer.parseInt(txtCenterNode.getText());
try {
maxDepth = Integer.parseInt(txtMaxDrawDepth.getText());
} catch (NumberFormatException e) {
Alerts.warning("Radius is not a number, try again with a number as input.");
}
} catch (NumberFormatException e) {
Alerts.warning("Center node ID is not a number, try again with a number as input.");
}
if (centerNode > getGraphController().getGraph().size()) {
centerNode = 1;
}
if (graphController.getGraph().contains(centerNode)) {
this.graphController.clear();
this.graphController.draw(centerNode, maxDepth);
this.miniMapController.showPosition(centerNode);
resetZoom();
Console.println("[%s] Graph drawn.", Thread.currentThread().getName());
} else {
Alerts.warning("The centernode is not a existing node, try again with a number that exists as a node.");
}
}
/**
* Handles the events of the bookmark button.
*/
private void buttonBookmark() {
try {
FXMLLoader loader = new FXMLLoader(ProgrammingLife.class.getResource("/CreateBookmarkWindow.fxml"));
AnchorPane page = loader.load();
GuiCreateBookmarkController gc = loader.getController();
gc.setGuiController(this);
gc.setText(txtCenterNode.getText(), txtMaxDrawDepth.getText());
Scene scene = new Scene(page);
Stage bookmarkDialogStage = new Stage();
bookmarkDialogStage.setResizable(false);
bookmarkDialogStage.setScene(scene);
bookmarkDialogStage.setTitle("Create Bookmark");
bookmarkDialogStage.initOwner(ProgrammingLife.getStage());
bookmarkDialogStage.showAndWait();
} catch (IOException e) {
Alerts.error("This bookmark cannot be created.");
}
}
/**
* Initialises the mouse events.
*/
private void initMouse() {
anchorGraphPanel.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
orgSceneX = event.getSceneX();
orgSceneY = event.getSceneY();
});
canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
if (event.isShiftDown() || event.getButton() == MouseButton.SECONDARY) {
mouseClick(event.getX(), event.getY(), true);
} else {
mouseClick(event.getX(), event.getY(), false);
}
});
anchorGraphPanel.addEventHandler(MouseEvent.MOUSE_DRAGGED, event -> {
double xDifference = event.getSceneX() - orgSceneX;
double yDifference = event.getSceneY() - orgSceneY;
orgSceneX += xDifference;
orgSceneY += yDifference;
graphController.translate(xDifference, yDifference);
event.consume();
});
anchorGraphPanel.addEventHandler(ScrollEvent.SCROLL, event ->
zoom(event.getDeltaX(), event.getDeltaY(), event.getSceneX(), event.getSceneY()));
}
/**
* Mouse click method that does the show info handling.
*
* @param x coordinate where is clicked.
* @param y coordinate where is clicked.
* @param shiftPressed boolean if shift is pressed it should be displayed in panel 2.
*/
private void mouseClick(double x, double y, boolean shiftPressed) {
Drawable clickedOn = graphController.onClick(x, y);
if (clickedOn != null) {
if (clickedOn instanceof DrawableSNP) {
DrawableSNP snp = (DrawableSNP) clickedOn;
if (shiftPressed) {
showInfoSNP(snp, 240);
} else {
showInfoSNP(snp, 10);
}
graphController.highlightClicked(null, snp, shiftPressed);
} else if (clickedOn instanceof DrawableSegment) {
DrawableSegment segment = (DrawableSegment) clickedOn;
if (shiftPressed) {
showInfoNode(segment, 240);
} else {
showInfoNode(segment, 10);
}
graphController.highlightClicked(segment, null, shiftPressed);
} else if (clickedOn instanceof DrawableEdge) {
DrawableEdge edge = (DrawableEdge) clickedOn;
if (shiftPressed) {
showInfoEdge(edge, 240);
} else {
showInfoEdge(edge, 10);
}
// graphController.highlightClicked(edge, shiftPressed); TODO FIX.
}
}
}
/**
* Handles the zooming in and out of the group.
*
* @param deltaX The scroll amount in the X direction. See {@link ScrollEvent#getDeltaX()}
* @param deltaY The scroll amount in the Y direction. See {@link ScrollEvent#getDeltaY()}
* @param sceneX double for the x location.
* @param sceneY double for the y location.
*/
private void zoom(double deltaX, double deltaY, double sceneX, double sceneY) {
double oldScale = scale;
if (deltaX < 0 || deltaY < 0) {
scale *= ZOOM_FACTOR;
} else {
scale /= ZOOM_FACTOR;
}
scale = clamp(scale);
double factor = (scale / oldScale) - 1;
graphController.zoom(factor + 1);
//factor to determine the difference in the scales.
Bounds bounds = canvas.localToScene(canvas.getBoundsInLocal());
double dx = (sceneX - bounds.getMinX());
double dy = (sceneY - bounds.getMinY());
graphController.translate(factor * dx, factor * dy);
}
/**
* Clamp function used for zooming in and out.
*
* @param value double current scale.
* @return double scale value.
*/
private static double clamp(double value) {
if (Double.compare(value, GuiController.MIN_SCALE) < 0) {
return GuiController.MIN_SCALE;
}
if (Double.compare(value, GuiController.MAX_SCALE) > 0) {
return GuiController.MAX_SCALE;
}
return value;
}
/**
* Initialises the Console.
*/
private void initConsole() {
final ConsoleView console = new ConsoleView(Charset.forName("UTF-8"));
AnchorPane root = new AnchorPane(console);
Stage st = new Stage();
st.setScene(new Scene(root, 500, 500, Color.GRAY));
st.setMinWidth(500);
st.setMinHeight(250);
AnchorPane.setBottomAnchor(console, 0.d);
AnchorPane.setTopAnchor(console, 0.d);
AnchorPane.setRightAnchor(console, 0.d);
AnchorPane.setLeftAnchor(console, 0.d);
btnConsole.setOnAction(event -> {
if (btnConsole.isSelected()) {
st.show();
} else {
st.close();
}
});
st.show();
btnConsole.setSelected(true);
root.visibleProperty().bind(btnConsole.selectedProperty());
Console.setOut(console.getOut());
}
/**
* Initializes the search tab in the left panel.
* Button to be disabled without a graph loaded.
*/
private void initRightSearchTab() {
try {
FXMLLoader loader = new FXMLLoader(ProgrammingLife.class.getResource("/HighlightWindow.fxml"));
AnchorPane page = loader.load();
highlightController = loader.getController();
highlightController.setGraphController(this.getGraphController());
searchTab.setContent(page);
searchTab.setDisable(true);
searchTab.setOnSelectionChanged(event -> highlightController.initMinMax());
} catch (IOException e) {
e.printStackTrace();
}
}
private ProgressBar getProgressBar() {
return this.progressBar;
}
/**
* Initializes the info tab.
*/
private void initShowInfoTab() {
btnClipboard.setOnAction(event -> copyToClipboard(10));
btnClipboard2.setOnAction(event -> copyToClipboard(240));
}
/**
* Copies information to the clipboard.
*
* @param x int used in the ID, to know which sequence to get.
*/
private void copyToClipboard(int x) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
String toClipboard = "";
for (Node node : anchorGraphInfo.getChildren()) {
if (node instanceof TextArea && node.getId().equals(x + " Sequence: ")) {
toClipboard = toClipboard.concat(((TextArea) node).getText()) + System.getProperty("line.separator");
toClipboard = toClipboard.replaceAll("(.{100})", "$1" + System.getProperty("line.separator"));
}
}
StringSelection selection = new StringSelection(toClipboard);
clipboard.setContents(selection, selection);
}
/**
* Sets the text field for drawing the graph.
*
* @param center The center node
* @param radius The radius of the subGraph
*/
void setText(int center, int radius) {
txtCenterNode.setText(String.valueOf(center));
txtMaxDrawDepth.setText(String.valueOf(radius));
}
/**
* Method to show the information of an edge.
*
* @param edge DrawableEdge the edge which has been clicked on.
* @param x int the x location of the TextField.
*/
private void showInfoEdge(DrawableEdge edge, int x) {
Text parentsText = makeText(x, 65, "Parent: ");
Text childrenText = makeText(x, 105, "Child: ");
Text idText = makeText(x, 145, "Genomes: ");
TextField parent = makeTextField("Parent Node: ", x, 70,
Integer.toString(edge.getStart().getParentSegment().getIdentifier()));
TextField child = makeTextField("Child Node: ", x, 110,
Integer.toString(edge.getEnd().getChildSegment().getIdentifier()));
Collection<Integer> genomesEdge = graphController.getGenomesEdge(edge);
TextArea genomes = null;
if (genomesEdge != null) {
String result = graphController.getGraph().getGenomeNames(genomesEdge).toString();
genomes = makeTextArea("Genomes: ", x, 150, result.substring(1, result.length() - 1), 80);
genomes.setWrapText(true);
}
anchorGraphInfo.getChildren().removeIf(node1 -> node1.getLayoutX() == x);
anchorGraphInfo.getChildren().addAll(idText, parentsText, childrenText, genomes, parent, child);
}
/**
* Method to show the information of a node.
*
* @param node DrawableSegment the node which has been clicked on.
* @param x int the x location of the TextField.
*/
private void showInfoNode(DrawableSegment node, int x) {
Text idText = makeText(x, 65, "ID: ");
Text parentText = makeText(x, 105, "Parents: ");
Text childText = makeText(x, 145, "Children: ");
Text inEdgeText = makeText(x, 185, "Incoming Edges: ");
Text outEdgeText = makeText(x, 225, "Outgoing Edges: ");
Text seqLengthText = makeText(x, 265, "Sequence Length: ");
Text genomeText = makeText(x, 305, "Genomes: ");
Text seqText = makeText(x, 370, "Sequence: ");
TextField idTextField = makeTextField("ID: ", x, 70, Integer.toString(node.getIdentifier()));
StringBuilder parentSB = new StringBuilder();
graphController.getParentSegments(node).forEach(
parentNode -> parentSB.append(parentNode.getIdentifier()).append(", "));
TextField parents;
if (parentSB.length() > 2) {
parentSB.setLength(parentSB.length() - 2);
parents = makeTextField("Parents: ", x, 110, parentSB.toString());
} else {
parentSB.replace(0, parentSB.length(), "This node has no parent(s)");
parents = makeTextField("Parents: ", x, 110, parentSB.toString());
}
StringBuilder childSB = new StringBuilder();
graphController.getChildSegments(node).forEach(
childNode -> childSB.append(childNode.getIdentifier()).append(", "));
TextField children;
if (childSB.length() > 2) {
childSB.setLength(childSB.length() - 2);
children = makeTextField("Children: ", x, 150, childSB.toString());
} else {
childSB.replace(0, childSB.length(), "This node has no child(ren)");
children = makeTextField("Children: ", x, 150, childSB.toString());
}
String genomesString = graphController.getGraph().getGenomeNames(node.getGenomes()).toString();
String sequenceString = node.getSequence().replaceAll("(.{23})", "$1" + System.getProperty("line.separator"));
TextField inEdges = makeTextField("Incoming Edges: ", x, 190, Integer.toString(node.getParents().size()));
TextField outEdges = makeTextField("Outgoing Edges: ", x, 230, Integer.toString(node.getChildren().size()));
TextField seqLength = makeTextField("Sequence Length: ", x, 270, Integer.toString(node.getSequence().length()));
TextArea genome = makeTextArea("Genome: ", x, 310, genomesString.substring(1, genomesString.length() - 1), 40);
genome.setWrapText(true);
TextArea seq = makeTextArea(x + " Sequence: ", x, 375, sequenceString, 250);
anchorGraphInfo.getChildren().removeIf(node1 -> node1.getLayoutX() == x);
anchorGraphInfo.getChildren().addAll(idText, parentText, childText, inEdgeText, outEdgeText, seqLengthText,
genomeText, seqText, idTextField, parents, children, inEdges, outEdges, genome, seqLength, seq);
}
/**
* Method to show the information of an SNP.
*
* @param snp DrawableSegment the node which has been clicked on.
* @param x int the x location of the TextField.
*/
private void showInfoSNP(DrawableSNP snp, int x) {
Text idParent = makeText(x, 65, "Parent: ");
Text idChild = makeText(x, 105, "Child: ");
Text idMutation = makeText(x, 145, "Mutation: ");
Text idGenome = makeText(x, 185, "Genome: ");
TextField parentTextField = makeTextField("Parent: ", x, 70,
Integer.toString(snp.getParent().getParentSegment().getIdentifier()));
TextField childTextField = makeTextField("Child: ", x, 110,
Integer.toString(snp.getChild().getChildSegment().getIdentifier()));
String c = snp.getMutations().stream().map(DrawableSegment::getSequence).collect(Collectors.toSet()).toString();
TextField mutationTextField = makeTextField("Mutation: ", x, 150, c.substring(1, c.length() - 1));
String genomesString = graphController.getGraph().getGenomeNames(snp.getGenomes()).toString();
TextArea genomeTextField = makeTextArea("Genome: ", x, 190,
genomesString.substring(1, genomesString.length() - 1), 80);
genomeTextField.setWrapText(true);
anchorGraphInfo.getChildren().removeIf(node1 -> node1.getLayoutX() == x);
anchorGraphInfo.getChildren().addAll(idParent, idChild, idMutation, idGenome,
parentTextField, childTextField, mutationTextField, genomeTextField);
}
/**
* Returns a textField to be used by the edge and node information show panel.
*
* @param x int the x coordinate of the textField inside the anchorPane.
* @param y int the y coordinate of the textField inside the anchorPane.
* @param s String the text to be shown by the textField.
* @return Text the created textField.
*/
private Text makeText(int x, int y, String s) {
Text text = new Text(s);
text.setLayoutX(x);
text.setLayoutY(y);
return text;
}
/**
* Returns a textField to be used by the edge and node information show panel.
*
* @param id String the id of the textField.
* @param x int the x coordinate of the textField inside the anchorPane.
* @param y int the y coordinate of the textField inside the anchorPane.
* @param text String the text to be shown by the textField.
* @return TextField the created textField.
*/
private TextField makeTextField(String id, int x, int y, String text) {
TextField textField = new TextField();
textField.setId(id);
textField.setText(text);
textField.setLayoutX(x);
textField.setLayoutY(y);
textField.setEditable(false);
textField.setPrefSize(220, 20);
return textField;
}
/**
* Returns a textField to be used by the edge and node information show panel.
*
* @param id String the id of the textField.
* @param x int the x coordinate of the textField inside the anchorPane.
* @param y int the y coordinate of the textField inside the anchorPane.
* @param text String the text to be shown by the textField.
* @param height int of the height of the area.
* @return TextField the created textField.
*/
private TextArea makeTextArea(String id, int x, int y, String text, int height) {
TextArea textArea = new TextArea();
textArea.setId(id);
textArea.setText(text);
textArea.setLayoutX(x);
textArea.setLayoutY(y);
textArea.setEditable(false);
textArea.setPrefSize(225, height);
return textArea;
}
public File getFile() {
return this.file;
}
public void setFile(File file) {
this.file = file;
}
GraphController getGraphController() {
return this.graphController;
}
}
| Just fit
| src/main/java/programminglife/gui/controller/GuiController.java | Just fit | <ide><path>rc/main/java/programminglife/gui/controller/GuiController.java
<ide> parentSB.setLength(parentSB.length() - 2);
<ide> parents = makeTextField("Parents: ", x, 110, parentSB.toString());
<ide> } else {
<del> parentSB.replace(0, parentSB.length(), "This node has no parent(s)");
<add> parentSB.replace(0, parentSB.length(), "This node has no parent");
<ide> parents = makeTextField("Parents: ", x, 110, parentSB.toString());
<ide> }
<ide>
<ide> childSB.setLength(childSB.length() - 2);
<ide> children = makeTextField("Children: ", x, 150, childSB.toString());
<ide> } else {
<del> childSB.replace(0, childSB.length(), "This node has no child(ren)");
<add> childSB.replace(0, childSB.length(), "This node has no child");
<ide> children = makeTextField("Children: ", x, 150, childSB.toString());
<ide> }
<ide> |
|
Java | apache-2.0 | c3f39243f569d2d489f35e336ca4168b5d0ec89d | 0 | troels/nz-presto,troels/nz-presto,troels/nz-presto,troels/nz-presto,troels/nz-presto | /*
* 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.facebook.presto.operator;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spiller.SingleStreamSpiller;
import com.facebook.presto.spiller.SingleStreamSpillerFactory;
import com.facebook.presto.sql.gen.JoinFilterFunctionCompiler.JoinFilterFunctionFactory;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.HashCode;
import com.google.common.io.Closer;
import com.google.common.util.concurrent.ListenableFuture;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import static com.facebook.presto.operator.Operators.checkSuccess;
import static com.facebook.presto.operator.Operators.getDone;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
@ThreadSafe
public class HashBuilderOperator
implements Operator
{
public static class HashBuilderOperatorFactory
implements OperatorFactory
{
private final int operatorId;
private final PlanNodeId planNodeId;
private final PartitionedLookupSourceFactory lookupSourceFactory;
private final List<Integer> outputChannels;
private final List<Integer> hashChannels;
private final Optional<Integer> preComputedHashChannel;
private final Optional<JoinFilterFunctionFactory> filterFunctionFactory;
private final PagesIndex.Factory pagesIndexFactory;
private final int expectedPositions;
private final boolean spillEnabled;
private final SingleStreamSpillerFactory singleStreamSpillerFactory;
private int partitionIndex;
private boolean closed;
public HashBuilderOperatorFactory(
int operatorId,
PlanNodeId planNodeId,
List<Type> types,
List<Integer> outputChannels,
Map<Symbol, Integer> layout,
List<Integer> hashChannels,
Optional<Integer> preComputedHashChannel,
boolean outer,
Optional<JoinFilterFunctionFactory> filterFunctionFactory,
int expectedPositions,
int partitionCount,
PagesIndex.Factory pagesIndexFactory)
{
this(operatorId,
planNodeId,
types,
outputChannels,
layout,
hashChannels,
preComputedHashChannel,
outer,
filterFunctionFactory,
expectedPositions,
partitionCount,
pagesIndexFactory,
false,
SingleStreamSpillerFactory.unsupportedSingleStreamSpillerFactory());
}
public HashBuilderOperatorFactory(
int operatorId,
PlanNodeId planNodeId,
List<Type> types,
List<Integer> outputChannels,
Map<Symbol, Integer> layout,
List<Integer> hashChannels,
Optional<Integer> preComputedHashChannel,
boolean outer,
Optional<JoinFilterFunctionFactory> filterFunctionFactory,
int expectedPositions,
int partitionCount,
PagesIndex.Factory pagesIndexFactory,
boolean spillEnabled,
SingleStreamSpillerFactory singleStreamSpillerFactory)
{
this.operatorId = operatorId;
this.planNodeId = requireNonNull(planNodeId, "planNodeId is null");
checkArgument(Integer.bitCount(partitionCount) == 1, "partitionCount must be a power of 2");
lookupSourceFactory = new PartitionedLookupSourceFactory(
types,
outputChannels.stream()
.map(types::get)
.collect(toImmutableList()),
hashChannels,
partitionCount,
requireNonNull(layout, "layout is null"),
outer);
this.outputChannels = ImmutableList.copyOf(requireNonNull(outputChannels, "outputChannels is null"));
this.hashChannels = ImmutableList.copyOf(requireNonNull(hashChannels, "hashChannels is null"));
this.preComputedHashChannel = requireNonNull(preComputedHashChannel, "preComputedHashChannel is null");
this.filterFunctionFactory = requireNonNull(filterFunctionFactory, "filterFunctionFactory is null");
this.pagesIndexFactory = requireNonNull(pagesIndexFactory, "pagesIndexFactory is null");
this.spillEnabled = spillEnabled;
this.singleStreamSpillerFactory = requireNonNull(singleStreamSpillerFactory, "singleStreamSpillerFactory is null");
this.expectedPositions = expectedPositions;
}
public LookupSourceFactory getLookupSourceFactory()
{
return lookupSourceFactory;
}
@Override
public List<Type> getTypes()
{
return lookupSourceFactory.getTypes();
}
@Override
public Operator createOperator(DriverContext driverContext)
{
checkState(!closed, "Factory is already closed");
OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, HashBuilderOperator.class.getSimpleName());
HashBuilderOperator operator = new HashBuilderOperator(
operatorContext,
lookupSourceFactory,
partitionIndex,
outputChannels,
hashChannels,
preComputedHashChannel,
filterFunctionFactory,
expectedPositions,
pagesIndexFactory,
spillEnabled,
singleStreamSpillerFactory);
partitionIndex++;
return operator;
}
@Override
public void close()
{
closed = true;
}
@Override
public OperatorFactory duplicate()
{
throw new UnsupportedOperationException("Parallel hash build can not be duplicated");
}
}
private enum State
{
/**
* Operator accepts input
*/
CONSUMING_INPUT,
/**
* Memory revoking occurred during {@link #CONSUMING_INPUT}. Operator accepts input and spills it
*/
SPILLING_INPUT,
/**
* LookupSource has been built and passed on without any spill occurring
*/
LOOKUP_SOURCE_BUILT,
/**
* Input has been finished and spilled
*/
LOOKUP_SOURCE_SPILLED,
/**
* Spilled input is being unspilled
*/
LOOKUP_SOURCE_UNSPILLING,
/**
* Spilled input has been unspilled, LookupSource built from it
*/
LOOKUP_SOURCE_UNSPILLED_AND_BUILT,
/**
* No longer needed
*/
DISPOSED
}
private static final double INDEX_COMPACTION_ON_REVOCATION_TARGET = 0.8;
private final OperatorContext operatorContext;
private final PartitionedLookupSourceFactory lookupSourceFactory;
private final ListenableFuture<?> lookupSourceFactoryDestroyed;
private final int partitionIndex;
private final List<Integer> outputChannels;
private final List<Integer> hashChannels;
private final Optional<Integer> preComputedHashChannel;
private final Optional<JoinFilterFunctionFactory> filterFunctionFactory;
private final PagesIndex index;
private final boolean spillEnabled;
private final SingleStreamSpillerFactory singleStreamSpillerFactory;
private final HashCollisionsCounter hashCollisionsCounter;
private State state = State.CONSUMING_INPUT;
private Optional<ListenableFuture<?>> lookupSourceNotNeeded = Optional.empty();
private SpilledLookupSourceHandle spilledLookupSourceHandle = new SpilledLookupSourceHandle();
private Optional<SingleStreamSpiller> spiller = Optional.empty();
private ListenableFuture<?> spillInProgress = NOT_BLOCKED;
private Optional<ListenableFuture<List<Page>>> unspillInProgress = Optional.empty();
@Nullable
private LookupSourceSupplier lookupSourceSupplier;
private Optional<HashCode> lookupSourceChecksum = Optional.empty();
private Optional<Runnable> finishMemoryRevoke = Optional.empty();
public HashBuilderOperator(
OperatorContext operatorContext,
PartitionedLookupSourceFactory lookupSourceFactory,
int partitionIndex,
List<Integer> outputChannels,
List<Integer> hashChannels,
Optional<Integer> preComputedHashChannel,
Optional<JoinFilterFunctionFactory> filterFunctionFactory,
int expectedPositions,
PagesIndex.Factory pagesIndexFactory,
boolean spillEnabled,
SingleStreamSpillerFactory singleStreamSpillerFactory)
{
requireNonNull(pagesIndexFactory, "pagesIndexFactory is null");
this.operatorContext = operatorContext;
this.partitionIndex = partitionIndex;
this.filterFunctionFactory = filterFunctionFactory;
this.index = pagesIndexFactory.newPagesIndex(lookupSourceFactory.getTypes(), expectedPositions);
this.lookupSourceFactory = lookupSourceFactory;
lookupSourceFactoryDestroyed = lookupSourceFactory.isDestroyed();
this.outputChannels = outputChannels;
this.hashChannels = hashChannels;
this.preComputedHashChannel = preComputedHashChannel;
this.hashCollisionsCounter = new HashCollisionsCounter(operatorContext);
operatorContext.setInfoSupplier(hashCollisionsCounter);
this.spillEnabled = spillEnabled;
this.singleStreamSpillerFactory = requireNonNull(singleStreamSpillerFactory, "singleStreamSpillerFactory is null");
}
@Override
public OperatorContext getOperatorContext()
{
return operatorContext;
}
@Override
public List<Type> getTypes()
{
return lookupSourceFactory.getTypes();
}
@Override
public ListenableFuture<?> isBlocked()
{
switch (state) {
case CONSUMING_INPUT:
return NOT_BLOCKED;
case SPILLING_INPUT:
return spillInProgress;
case LOOKUP_SOURCE_BUILT:
return lookupSourceNotNeeded.get();
case LOOKUP_SOURCE_SPILLED:
return spilledLookupSourceHandle.getUnspillingOrDisposeRequested();
case LOOKUP_SOURCE_UNSPILLING:
return unspillInProgress.get();
case LOOKUP_SOURCE_UNSPILLED_AND_BUILT:
return spilledLookupSourceHandle.getDisposeRequested();
case DISPOSED:
return lookupSourceFactoryDestroyed;
}
throw new IllegalStateException("Unhandled state: " + state);
}
@Override
public boolean needsInput()
{
boolean stateNeedsInput = state == State.CONSUMING_INPUT
|| (state == State.SPILLING_INPUT && spillInProgress.isDone());
return stateNeedsInput && !lookupSourceFactoryDestroyed.isDone();
}
@Override
public void addInput(Page page)
{
requireNonNull(page, "page is null");
if (lookupSourceFactoryDestroyed.isDone()) {
close();
return;
}
if (state == State.SPILLING_INPUT) {
spillInput(page);
return;
}
checkState(state == State.CONSUMING_INPUT);
updateIndex(page);
}
private void updateIndex(Page page)
{
index.addPage(page);
if (spillEnabled) {
operatorContext.setRevocableMemoryReservation(index.getEstimatedSize().toBytes());
}
else {
if (!operatorContext.trySetMemoryReservation(index.getEstimatedSize().toBytes())) {
index.compact();
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
}
}
operatorContext.recordGeneratedOutput(page.getSizeInBytes(), page.getPositionCount());
}
private void spillInput(Page page)
{
checkState(spillInProgress.isDone(), "Previous spill still in progress");
checkSuccess(spillInProgress, "spilling failed");
spillInProgress = getSpiller().spill(page);
}
@Override
public ListenableFuture<?> startMemoryRevoke()
{
checkState(spillEnabled, "Spill not enabled, no revokable memory should be reserved");
if (state == State.CONSUMING_INPUT) {
long indexSizeBeforeCompaction = index.getEstimatedSize().toBytes();
index.compact();
long indexSizeAfterCompaction = index.getEstimatedSize().toBytes();
if (indexSizeAfterCompaction < indexSizeBeforeCompaction * INDEX_COMPACTION_ON_REVOCATION_TARGET) {
finishMemoryRevoke = Optional.of(() -> {
});
return immediateFuture(null);
}
finishMemoryRevoke = Optional.of(() -> {
index.clear();
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
operatorContext.setRevocableMemoryReservation(0L);
state = State.SPILLING_INPUT;
// TODO we could immediately call lookupSourceFactory.setPartitionSpilledLookupSource
});
return spillIndex();
}
else if (state == State.LOOKUP_SOURCE_BUILT) {
finishMemoryRevoke = Optional.of(() -> {
lookupSourceFactory.setPartitionSpilledLookupSource(partitionIndex, spilledLookupSourceHandle);
lookupSourceNotNeeded = Optional.empty();
index.clear();
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
operatorContext.setRevocableMemoryReservation(0L);
lookupSourceChecksum = Optional.of(lookupSourceSupplier.checksum());
lookupSourceSupplier = null;
state = State.LOOKUP_SOURCE_SPILLED;
});
return spillIndex();
}
else if (operatorContext.getReservedRevocableBytes() == 0) {
// Probably stale revoking request
finishMemoryRevoke = Optional.of(() -> {
});
return immediateFuture(null);
}
throw new IllegalStateException(format("Remaining %s revocable bytes which I don't know how to revoke", operatorContext.getReservedRevocableBytes()));
}
private ListenableFuture<?> spillIndex()
{
createSpiller();
return getSpiller().spill(index.getPages());
}
@Override
public void finishMemoryRevoke()
{
checkState(finishMemoryRevoke.isPresent(), "Cannot finish unknown revoking");
finishMemoryRevoke.get().run();
finishMemoryRevoke = Optional.empty();
}
@Override
public Page getOutput()
{
return null;
}
@Override
public void finish()
{
if (lookupSourceFactoryDestroyed.isDone()) {
close();
return;
}
switch (state) {
case CONSUMING_INPUT:
finishInput();
return;
case LOOKUP_SOURCE_BUILT:
disposeLookupSourceIfRequested();
return;
case SPILLING_INPUT:
finishSpilledInput();
return;
case LOOKUP_SOURCE_SPILLED:
disposeSpilledLookupSourceIfRequested();
if (state == State.LOOKUP_SOURCE_SPILLED) {
unspillLookupSourceIfRequested();
}
return;
case LOOKUP_SOURCE_UNSPILLING:
finishLookupSourceUnspilling();
return;
case LOOKUP_SOURCE_UNSPILLED_AND_BUILT:
disposeUnspilledLookupSourceIfRequested();
return;
case DISPOSED:
// no-op
return;
}
throw new IllegalStateException("Unhandled state: " + state);
}
private void finishInput()
{
if (lookupSourceFactoryDestroyed.isDone()) {
close();
return;
}
LookupSourceSupplier partition = buildLookupSource();
if (spillEnabled) {
operatorContext.setRevocableMemoryReservation(partition.get().getInMemorySizeInBytes());
}
else {
operatorContext.setMemoryReservation(partition.get().getInMemorySizeInBytes());
}
lookupSourceNotNeeded = Optional.of(lookupSourceFactory.setPartitionLookupSourceSupplier(partitionIndex, partition));
state = State.LOOKUP_SOURCE_BUILT;
}
private void disposeLookupSourceIfRequested()
{
verify(lookupSourceNotNeeded.isPresent());
if (!lookupSourceNotNeeded.get().isDone()) {
return;
}
index.clear();
operatorContext.setRevocableMemoryReservation(0L);
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
lookupSourceSupplier = null;
state = State.DISPOSED;
}
private void finishSpilledInput()
{
if (!spillInProgress.isDone()) {
// Not ready to handle finish() yet
return;
}
checkSuccess(spillInProgress, "spilling failed");
lookupSourceFactory.setPartitionSpilledLookupSource(partitionIndex, spilledLookupSourceHandle);
state = State.LOOKUP_SOURCE_SPILLED;
}
private void disposeSpilledLookupSourceIfRequested()
{
if (!spilledLookupSourceHandle.getDisposeRequested().isDone()) {
return;
}
close();
}
private void unspillLookupSourceIfRequested()
{
if (!spilledLookupSourceHandle.getUnspillingRequested().isDone()) {
// Nothing to do yet.
return;
}
verify(spiller.isPresent());
verify(!unspillInProgress.isPresent());
operatorContext.setMemoryReservation(getSpiller().getSpilledPagesInMemorySize() + index.getEstimatedSize().toBytes());
unspillInProgress = Optional.of(getSpiller().getAllSpilledPages());
state = State.LOOKUP_SOURCE_UNSPILLING;
}
private void finishLookupSourceUnspilling()
{
if (!unspillInProgress.get().isDone()) {
// Pages have not be unspilled yet.
return;
}
// Use Queue so that Pages already consumed by Index are not retained by us.
Queue<Page> pages = new ArrayDeque<>(getDone(unspillInProgress.get()));
long memoryRetainedByRemainingPages = pages.stream()
.mapToLong(Page::getRetainedSizeInBytes)
.sum();
operatorContext.setMemoryReservation(memoryRetainedByRemainingPages + index.getEstimatedSize().toBytes());
while (!pages.isEmpty()) {
Page next = pages.remove();
index.addPage(next);
// There is no attempt to compact index, since unspilled pages are unlikely to have blocks with retained size > logical size.
memoryRetainedByRemainingPages -= next.getRetainedSizeInBytes();
operatorContext.setMemoryReservation(memoryRetainedByRemainingPages + index.getEstimatedSize().toBytes());
}
LookupSourceSupplier partition = buildLookupSource();
lookupSourceChecksum.ifPresent(lookupSourceSupplierChecksum ->
checkState(Objects.equals(partition.checksum(), lookupSourceSupplierChecksum), "Unspilled lookupSource checksum does not match original one"));
operatorContext.setMemoryReservation(partition.get().getInMemorySizeInBytes());
spilledLookupSourceHandle.setLookupSource(partition);
state = State.LOOKUP_SOURCE_UNSPILLED_AND_BUILT;
}
private void disposeUnspilledLookupSourceIfRequested()
{
if (!spilledLookupSourceHandle.getDisposeRequested().isDone()) {
return;
}
index.clear();
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
state = State.DISPOSED;
}
private LookupSourceSupplier buildLookupSource()
{
LookupSourceSupplier partition = index.createLookupSourceSupplier(operatorContext.getSession(), hashChannels, preComputedHashChannel, filterFunctionFactory, Optional.of(outputChannels));
hashCollisionsCounter.recordHashCollision(partition.getHashCollisions(), partition.getExpectedHashCollisions());
checkState(lookupSourceSupplier == null, "lookupSourceSupplier is already set");
this.lookupSourceSupplier = partition;
return partition;
}
@Override
public boolean isFinished()
{
if (lookupSourceFactoryDestroyed.isDone()) {
// Finish early when the probe side is empty
close();
return true;
}
return state == State.DISPOSED;
}
private void createSpiller()
{
checkState(!spiller.isPresent(), "Spiller already loaded");
spiller = Optional.of(singleStreamSpillerFactory.create(index.getTypes(),
operatorContext.getSpillContext().newLocalSpillContext(),
operatorContext.getSystemMemoryContext().newLocalMemoryContext()));
}
private SingleStreamSpiller getSpiller()
{
return spiller.orElseThrow(() -> new IllegalStateException("Spiller not loaded"));
}
@Override
public void close()
{
// close() can be called in any state, due for example to query failure, and must clean resource up unconditionally
lookupSourceSupplier = null;
state = State.DISPOSED;
try (Closer closer = Closer.create()) {
closer.register(index::clear);
spiller.ifPresent(closer::register);
closer.register(() -> operatorContext.setMemoryReservation(0));
closer.register(() -> operatorContext.setRevocableMemoryReservation(0));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| presto-main/src/main/java/com/facebook/presto/operator/HashBuilderOperator.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spiller.SingleStreamSpiller;
import com.facebook.presto.spiller.SingleStreamSpillerFactory;
import com.facebook.presto.sql.gen.JoinFilterFunctionCompiler.JoinFilterFunctionFactory;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Closer;
import com.google.common.util.concurrent.ListenableFuture;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Queue;
import static com.facebook.presto.operator.Operators.checkSuccess;
import static com.facebook.presto.operator.Operators.getDone;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
@ThreadSafe
public class HashBuilderOperator
implements Operator
{
public static class HashBuilderOperatorFactory
implements OperatorFactory
{
private final int operatorId;
private final PlanNodeId planNodeId;
private final PartitionedLookupSourceFactory lookupSourceFactory;
private final List<Integer> outputChannels;
private final List<Integer> hashChannels;
private final Optional<Integer> preComputedHashChannel;
private final Optional<JoinFilterFunctionFactory> filterFunctionFactory;
private final PagesIndex.Factory pagesIndexFactory;
private final int expectedPositions;
private final boolean spillEnabled;
private final SingleStreamSpillerFactory singleStreamSpillerFactory;
private int partitionIndex;
private boolean closed;
public HashBuilderOperatorFactory(
int operatorId,
PlanNodeId planNodeId,
List<Type> types,
List<Integer> outputChannels,
Map<Symbol, Integer> layout,
List<Integer> hashChannels,
Optional<Integer> preComputedHashChannel,
boolean outer,
Optional<JoinFilterFunctionFactory> filterFunctionFactory,
int expectedPositions,
int partitionCount,
PagesIndex.Factory pagesIndexFactory)
{
this(operatorId,
planNodeId,
types,
outputChannels,
layout,
hashChannels,
preComputedHashChannel,
outer,
filterFunctionFactory,
expectedPositions,
partitionCount,
pagesIndexFactory,
false,
SingleStreamSpillerFactory.unsupportedSingleStreamSpillerFactory());
}
public HashBuilderOperatorFactory(
int operatorId,
PlanNodeId planNodeId,
List<Type> types,
List<Integer> outputChannels,
Map<Symbol, Integer> layout,
List<Integer> hashChannels,
Optional<Integer> preComputedHashChannel,
boolean outer,
Optional<JoinFilterFunctionFactory> filterFunctionFactory,
int expectedPositions,
int partitionCount,
PagesIndex.Factory pagesIndexFactory,
boolean spillEnabled,
SingleStreamSpillerFactory singleStreamSpillerFactory)
{
this.operatorId = operatorId;
this.planNodeId = requireNonNull(planNodeId, "planNodeId is null");
checkArgument(Integer.bitCount(partitionCount) == 1, "partitionCount must be a power of 2");
lookupSourceFactory = new PartitionedLookupSourceFactory(
types,
outputChannels.stream()
.map(types::get)
.collect(toImmutableList()),
hashChannels,
partitionCount,
requireNonNull(layout, "layout is null"),
outer);
this.outputChannels = ImmutableList.copyOf(requireNonNull(outputChannels, "outputChannels is null"));
this.hashChannels = ImmutableList.copyOf(requireNonNull(hashChannels, "hashChannels is null"));
this.preComputedHashChannel = requireNonNull(preComputedHashChannel, "preComputedHashChannel is null");
this.filterFunctionFactory = requireNonNull(filterFunctionFactory, "filterFunctionFactory is null");
this.pagesIndexFactory = requireNonNull(pagesIndexFactory, "pagesIndexFactory is null");
this.spillEnabled = spillEnabled;
this.singleStreamSpillerFactory = requireNonNull(singleStreamSpillerFactory, "singleStreamSpillerFactory is null");
this.expectedPositions = expectedPositions;
}
public LookupSourceFactory getLookupSourceFactory()
{
return lookupSourceFactory;
}
@Override
public List<Type> getTypes()
{
return lookupSourceFactory.getTypes();
}
@Override
public Operator createOperator(DriverContext driverContext)
{
checkState(!closed, "Factory is already closed");
OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, HashBuilderOperator.class.getSimpleName());
HashBuilderOperator operator = new HashBuilderOperator(
operatorContext,
lookupSourceFactory,
partitionIndex,
outputChannels,
hashChannels,
preComputedHashChannel,
filterFunctionFactory,
expectedPositions,
pagesIndexFactory,
spillEnabled,
singleStreamSpillerFactory);
partitionIndex++;
return operator;
}
@Override
public void close()
{
closed = true;
}
@Override
public OperatorFactory duplicate()
{
throw new UnsupportedOperationException("Parallel hash build can not be duplicated");
}
}
private enum State
{
/**
* Operator accepts input
*/
CONSUMING_INPUT,
/**
* Memory revoking occurred during {@link #CONSUMING_INPUT}. Operator accepts input and spills it
*/
SPILLING_INPUT,
/**
* LookupSource has been built and passed on without any spill occurring
*/
LOOKUP_SOURCE_BUILT,
/**
* Input has been finished and spilled
*/
LOOKUP_SOURCE_SPILLED,
/**
* Spilled input is being unspilled
*/
LOOKUP_SOURCE_UNSPILLING,
/**
* Spilled input has been unspilled, LookupSource built from it
*/
LOOKUP_SOURCE_UNSPILLED_AND_BUILT,
/**
* No longer needed
*/
DISPOSED
}
private static final double INDEX_COMPACTION_ON_REVOCATION_TARGET = 0.8;
private final OperatorContext operatorContext;
private final PartitionedLookupSourceFactory lookupSourceFactory;
private final ListenableFuture<?> lookupSourceFactoryDestroyed;
private final int partitionIndex;
private final List<Integer> outputChannels;
private final List<Integer> hashChannels;
private final Optional<Integer> preComputedHashChannel;
private final Optional<JoinFilterFunctionFactory> filterFunctionFactory;
private final PagesIndex index;
private final boolean spillEnabled;
private final SingleStreamSpillerFactory singleStreamSpillerFactory;
private final HashCollisionsCounter hashCollisionsCounter;
private State state = State.CONSUMING_INPUT;
private Optional<ListenableFuture<?>> lookupSourceNotNeeded = Optional.empty();
private SpilledLookupSourceHandle spilledLookupSourceHandle = new SpilledLookupSourceHandle();
private Optional<SingleStreamSpiller> spiller = Optional.empty();
private ListenableFuture<?> spillInProgress = NOT_BLOCKED;
private Optional<ListenableFuture<List<Page>>> unspillInProgress = Optional.empty();
@Nullable
private LookupSourceSupplier lookupSourceSupplier;
private OptionalLong lookupSourceChecksum = OptionalLong.empty();
private Optional<Runnable> finishMemoryRevoke = Optional.empty();
public HashBuilderOperator(
OperatorContext operatorContext,
PartitionedLookupSourceFactory lookupSourceFactory,
int partitionIndex,
List<Integer> outputChannels,
List<Integer> hashChannels,
Optional<Integer> preComputedHashChannel,
Optional<JoinFilterFunctionFactory> filterFunctionFactory,
int expectedPositions,
PagesIndex.Factory pagesIndexFactory,
boolean spillEnabled,
SingleStreamSpillerFactory singleStreamSpillerFactory)
{
requireNonNull(pagesIndexFactory, "pagesIndexFactory is null");
this.operatorContext = operatorContext;
this.partitionIndex = partitionIndex;
this.filterFunctionFactory = filterFunctionFactory;
this.index = pagesIndexFactory.newPagesIndex(lookupSourceFactory.getTypes(), expectedPositions);
this.lookupSourceFactory = lookupSourceFactory;
lookupSourceFactoryDestroyed = lookupSourceFactory.isDestroyed();
this.outputChannels = outputChannels;
this.hashChannels = hashChannels;
this.preComputedHashChannel = preComputedHashChannel;
this.hashCollisionsCounter = new HashCollisionsCounter(operatorContext);
operatorContext.setInfoSupplier(hashCollisionsCounter);
this.spillEnabled = spillEnabled;
this.singleStreamSpillerFactory = requireNonNull(singleStreamSpillerFactory, "singleStreamSpillerFactory is null");
}
@Override
public OperatorContext getOperatorContext()
{
return operatorContext;
}
@Override
public List<Type> getTypes()
{
return lookupSourceFactory.getTypes();
}
@Override
public ListenableFuture<?> isBlocked()
{
switch (state) {
case CONSUMING_INPUT:
return NOT_BLOCKED;
case SPILLING_INPUT:
return spillInProgress;
case LOOKUP_SOURCE_BUILT:
return lookupSourceNotNeeded.get();
case LOOKUP_SOURCE_SPILLED:
return spilledLookupSourceHandle.getUnspillingOrDisposeRequested();
case LOOKUP_SOURCE_UNSPILLING:
return unspillInProgress.get();
case LOOKUP_SOURCE_UNSPILLED_AND_BUILT:
return spilledLookupSourceHandle.getDisposeRequested();
case DISPOSED:
return lookupSourceFactoryDestroyed;
}
throw new IllegalStateException("Unhandled state: " + state);
}
@Override
public boolean needsInput()
{
boolean stateNeedsInput = state == State.CONSUMING_INPUT
|| (state == State.SPILLING_INPUT && spillInProgress.isDone());
return stateNeedsInput && !lookupSourceFactoryDestroyed.isDone();
}
@Override
public void addInput(Page page)
{
requireNonNull(page, "page is null");
if (lookupSourceFactoryDestroyed.isDone()) {
close();
return;
}
if (state == State.SPILLING_INPUT) {
spillInput(page);
return;
}
checkState(state == State.CONSUMING_INPUT);
updateIndex(page);
}
private void updateIndex(Page page)
{
index.addPage(page);
if (spillEnabled) {
operatorContext.setRevocableMemoryReservation(index.getEstimatedSize().toBytes());
}
else {
if (!operatorContext.trySetMemoryReservation(index.getEstimatedSize().toBytes())) {
index.compact();
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
}
}
operatorContext.recordGeneratedOutput(page.getSizeInBytes(), page.getPositionCount());
}
private void spillInput(Page page)
{
checkState(spillInProgress.isDone(), "Previous spill still in progress");
checkSuccess(spillInProgress, "spilling failed");
spillInProgress = getSpiller().spill(page);
}
@Override
public ListenableFuture<?> startMemoryRevoke()
{
checkState(spillEnabled, "Spill not enabled, no revokable memory should be reserved");
if (state == State.CONSUMING_INPUT) {
long indexSizeBeforeCompaction = index.getEstimatedSize().toBytes();
index.compact();
long indexSizeAfterCompaction = index.getEstimatedSize().toBytes();
if (indexSizeAfterCompaction < indexSizeBeforeCompaction * INDEX_COMPACTION_ON_REVOCATION_TARGET) {
finishMemoryRevoke = Optional.of(() -> {
});
return immediateFuture(null);
}
finishMemoryRevoke = Optional.of(() -> {
index.clear();
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
operatorContext.setRevocableMemoryReservation(0L);
state = State.SPILLING_INPUT;
// TODO we could immediately call lookupSourceFactory.setPartitionSpilledLookupSource
});
return spillIndex();
}
else if (state == State.LOOKUP_SOURCE_BUILT) {
finishMemoryRevoke = Optional.of(() -> {
lookupSourceFactory.setPartitionSpilledLookupSource(partitionIndex, spilledLookupSourceHandle);
lookupSourceNotNeeded = Optional.empty();
index.clear();
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
operatorContext.setRevocableMemoryReservation(0L);
lookupSourceChecksum = OptionalLong.of(lookupSourceSupplier.checksum());
lookupSourceSupplier = null;
state = State.LOOKUP_SOURCE_SPILLED;
});
return spillIndex();
}
else if (operatorContext.getReservedRevocableBytes() == 0) {
// Probably stale revoking request
finishMemoryRevoke = Optional.of(() -> {
});
return immediateFuture(null);
}
throw new IllegalStateException(format("Remaining %s revocable bytes which I don't know how to revoke", operatorContext.getReservedRevocableBytes()));
}
private ListenableFuture<?> spillIndex()
{
createSpiller();
return getSpiller().spill(index.getPages());
}
@Override
public void finishMemoryRevoke()
{
checkState(finishMemoryRevoke.isPresent(), "Cannot finish unknown revoking");
finishMemoryRevoke.get().run();
finishMemoryRevoke = Optional.empty();
}
@Override
public Page getOutput()
{
return null;
}
@Override
public void finish()
{
if (lookupSourceFactoryDestroyed.isDone()) {
close();
return;
}
switch (state) {
case CONSUMING_INPUT:
finishInput();
return;
case LOOKUP_SOURCE_BUILT:
disposeLookupSourceIfRequested();
return;
case SPILLING_INPUT:
finishSpilledInput();
return;
case LOOKUP_SOURCE_SPILLED:
disposeSpilledLookupSourceIfRequested();
if (state == State.LOOKUP_SOURCE_SPILLED) {
unspillLookupSourceIfRequested();
}
return;
case LOOKUP_SOURCE_UNSPILLING:
finishLookupSourceUnspilling();
return;
case LOOKUP_SOURCE_UNSPILLED_AND_BUILT:
disposeUnspilledLookupSourceIfRequested();
return;
case DISPOSED:
// no-op
return;
}
throw new IllegalStateException("Unhandled state: " + state);
}
private void finishInput()
{
if (lookupSourceFactoryDestroyed.isDone()) {
close();
return;
}
LookupSourceSupplier partition = buildLookupSource();
if (spillEnabled) {
operatorContext.setRevocableMemoryReservation(partition.get().getInMemorySizeInBytes());
}
else {
operatorContext.setMemoryReservation(partition.get().getInMemorySizeInBytes());
}
lookupSourceNotNeeded = Optional.of(lookupSourceFactory.setPartitionLookupSourceSupplier(partitionIndex, partition));
state = State.LOOKUP_SOURCE_BUILT;
}
private void disposeLookupSourceIfRequested()
{
verify(lookupSourceNotNeeded.isPresent());
if (!lookupSourceNotNeeded.get().isDone()) {
return;
}
index.clear();
operatorContext.setRevocableMemoryReservation(0L);
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
lookupSourceSupplier = null;
state = State.DISPOSED;
}
private void finishSpilledInput()
{
if (!spillInProgress.isDone()) {
// Not ready to handle finish() yet
return;
}
checkSuccess(spillInProgress, "spilling failed");
lookupSourceFactory.setPartitionSpilledLookupSource(partitionIndex, spilledLookupSourceHandle);
state = State.LOOKUP_SOURCE_SPILLED;
}
private void disposeSpilledLookupSourceIfRequested()
{
if (!spilledLookupSourceHandle.getDisposeRequested().isDone()) {
return;
}
close();
}
private void unspillLookupSourceIfRequested()
{
if (!spilledLookupSourceHandle.getUnspillingRequested().isDone()) {
// Nothing to do yet.
return;
}
verify(spiller.isPresent());
verify(!unspillInProgress.isPresent());
operatorContext.setMemoryReservation(getSpiller().getSpilledPagesInMemorySize() + index.getEstimatedSize().toBytes());
unspillInProgress = Optional.of(getSpiller().getAllSpilledPages());
state = State.LOOKUP_SOURCE_UNSPILLING;
}
private void finishLookupSourceUnspilling()
{
if (!unspillInProgress.get().isDone()) {
// Pages have not be unspilled yet.
return;
}
// Use Queue so that Pages already consumed by Index are not retained by us.
Queue<Page> pages = new ArrayDeque<>(getDone(unspillInProgress.get()));
long memoryRetainedByRemainingPages = pages.stream()
.mapToLong(Page::getRetainedSizeInBytes)
.sum();
operatorContext.setMemoryReservation(memoryRetainedByRemainingPages + index.getEstimatedSize().toBytes());
while (!pages.isEmpty()) {
Page next = pages.remove();
index.addPage(next);
// There is no attempt to compact index, since unspilled pages are unlikely to have blocks with retained size > logical size.
memoryRetainedByRemainingPages -= next.getRetainedSizeInBytes();
operatorContext.setMemoryReservation(memoryRetainedByRemainingPages + index.getEstimatedSize().toBytes());
}
LookupSourceSupplier partition = buildLookupSource();
lookupSourceChecksum.ifPresent(lookupSourceSupplierChecksum ->
checkState(partition.checksum() == lookupSourceSupplierChecksum, "Unspilled lookupSource checksum does not match original one"));
operatorContext.setMemoryReservation(partition.get().getInMemorySizeInBytes());
spilledLookupSourceHandle.setLookupSource(partition);
state = State.LOOKUP_SOURCE_UNSPILLED_AND_BUILT;
}
private void disposeUnspilledLookupSourceIfRequested()
{
if (!spilledLookupSourceHandle.getDisposeRequested().isDone()) {
return;
}
index.clear();
operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
state = State.DISPOSED;
}
private LookupSourceSupplier buildLookupSource()
{
LookupSourceSupplier partition = index.createLookupSourceSupplier(operatorContext.getSession(), hashChannels, preComputedHashChannel, filterFunctionFactory, Optional.of(outputChannels));
hashCollisionsCounter.recordHashCollision(partition.getHashCollisions(), partition.getExpectedHashCollisions());
checkState(lookupSourceSupplier == null, "lookupSourceSupplier is already set");
this.lookupSourceSupplier = partition;
return partition;
}
@Override
public boolean isFinished()
{
if (lookupSourceFactoryDestroyed.isDone()) {
// Finish early when the probe side is empty
close();
return true;
}
return state == State.DISPOSED;
}
private void createSpiller()
{
checkState(!spiller.isPresent(), "Spiller already loaded");
spiller = Optional.of(singleStreamSpillerFactory.create(index.getTypes(),
operatorContext.getSpillContext().newLocalSpillContext(),
operatorContext.getSystemMemoryContext().newLocalMemoryContext()));
}
private SingleStreamSpiller getSpiller()
{
return spiller.orElseThrow(() -> new IllegalStateException("Spiller not loaded"));
}
@Override
public void close()
{
// close() can be called in any state, due for example to query failure, and must clean resource up unconditionally
lookupSourceSupplier = null;
state = State.DISPOSED;
try (Closer closer = Closer.create()) {
closer.register(index::clear);
spiller.ifPresent(closer::register);
closer.register(() -> operatorContext.setMemoryReservation(0));
closer.register(() -> operatorContext.setRevocableMemoryReservation(0));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| fixup! Check checksum of LookupSourceSupplier in HashBuilderOperator
| presto-main/src/main/java/com/facebook/presto/operator/HashBuilderOperator.java | fixup! Check checksum of LookupSourceSupplier in HashBuilderOperator | <ide><path>resto-main/src/main/java/com/facebook/presto/operator/HashBuilderOperator.java
<ide> import com.facebook.presto.sql.planner.Symbol;
<ide> import com.facebook.presto.sql.planner.plan.PlanNodeId;
<ide> import com.google.common.collect.ImmutableList;
<add>import com.google.common.hash.HashCode;
<ide> import com.google.common.io.Closer;
<ide> import com.google.common.util.concurrent.ListenableFuture;
<ide>
<ide> import java.util.ArrayDeque;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.Objects;
<ide> import java.util.Optional;
<del>import java.util.OptionalLong;
<ide> import java.util.Queue;
<ide>
<ide> import static com.facebook.presto.operator.Operators.checkSuccess;
<ide> private Optional<ListenableFuture<List<Page>>> unspillInProgress = Optional.empty();
<ide> @Nullable
<ide> private LookupSourceSupplier lookupSourceSupplier;
<del> private OptionalLong lookupSourceChecksum = OptionalLong.empty();
<add> private Optional<HashCode> lookupSourceChecksum = Optional.empty();
<ide>
<ide> private Optional<Runnable> finishMemoryRevoke = Optional.empty();
<ide>
<ide> index.clear();
<ide> operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes());
<ide> operatorContext.setRevocableMemoryReservation(0L);
<del> lookupSourceChecksum = OptionalLong.of(lookupSourceSupplier.checksum());
<add> lookupSourceChecksum = Optional.of(lookupSourceSupplier.checksum());
<ide> lookupSourceSupplier = null;
<ide> state = State.LOOKUP_SOURCE_SPILLED;
<ide> });
<ide>
<ide> LookupSourceSupplier partition = buildLookupSource();
<ide> lookupSourceChecksum.ifPresent(lookupSourceSupplierChecksum ->
<del> checkState(partition.checksum() == lookupSourceSupplierChecksum, "Unspilled lookupSource checksum does not match original one"));
<add> checkState(Objects.equals(partition.checksum(), lookupSourceSupplierChecksum), "Unspilled lookupSource checksum does not match original one"));
<ide> operatorContext.setMemoryReservation(partition.get().getInMemorySizeInBytes());
<ide>
<ide> spilledLookupSourceHandle.setLookupSource(partition); |
|
Java | mit | 5c9d20fe22a29808d4c18d960970770a05dbc071 | 0 | SpongePowered/Mixin | /*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.asm.launch.platform;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Locale;
import java.util.Optional;
import org.spongepowered.asm.launch.platform.container.IContainerHandle;
import org.spongepowered.asm.util.Constants;
import cpw.mods.modlauncher.Environment;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.IEnvironment;
import cpw.mods.modlauncher.api.ILaunchHandlerService;
/**
* Platform agent for minecraft forge under ModLauncher, only detects the side
*/
public class MixinPlatformAgentMinecraftForge extends MixinPlatformAgentAbstract implements IMixinPlatformServiceAgent {
/**
* getDist method name in launch handler
*/
private static final String GET_DIST_METHOD = "getDist";
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent
* #init()
*/
@Override
public void init() {
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.platform.MixinPlatformAgentAbstract
* #accept(org.spongepowered.asm.launch.platform.MixinPlatformManager,
* org.spongepowered.asm.launch.platform.container.IContainerHandle)
*/
@Override
public AcceptResult accept(MixinPlatformManager manager, IContainerHandle handle) {
// No containers plz
return AcceptResult.REJECTED;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.platform.IMixinPlatformAgent
* #getSideName()
*/
@Override
public String getSideName() {
Environment environment = Launcher.INSTANCE.environment();
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("missing").toLowerCase(Locale.ROOT);
if (launchTarget.contains("server")) {
return Constants.SIDE_SERVER;
}
if (launchTarget.contains("client")) {
return Constants.SIDE_CLIENT;
}
Optional<ILaunchHandlerService> launchHandler = environment.findLaunchHandler(launchTarget);
if (launchHandler.isPresent()) {
ILaunchHandlerService service = launchHandler.get();
try {
Method mdGetDist = service.getClass().getDeclaredMethod(MixinPlatformAgentMinecraftForge.GET_DIST_METHOD);
String strDist = mdGetDist.invoke(service).toString().toLowerCase(Locale.ROOT);
if (strDist.contains("server")) {
return Constants.SIDE_SERVER;
}
if (strDist.contains("client")) {
return Constants.SIDE_CLIENT;
}
} catch (Exception ex) {
return null;
}
}
return null;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent
* #getMixinContainers()
*/
@Override
public Collection<IContainerHandle> getMixinContainers() {
return null;
}
}
| src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java | /*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.asm.launch.platform;
import java.util.Collection;
import java.util.Locale;
import org.spongepowered.asm.launch.platform.container.IContainerHandle;
import org.spongepowered.asm.util.Constants;
import cpw.mods.modlauncher.Environment;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.IEnvironment;
/**
* Platform agent for minecraft forge under ModLauncher, only detects the side
*/
public class MixinPlatformAgentMinecraftForge extends MixinPlatformAgentAbstract implements IMixinPlatformServiceAgent {
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent
* #init()
*/
@Override
public void init() {
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.platform.MixinPlatformAgentAbstract
* #accept(org.spongepowered.asm.launch.platform.MixinPlatformManager,
* org.spongepowered.asm.launch.platform.container.IContainerHandle)
*/
@Override
public AcceptResult accept(MixinPlatformManager manager, IContainerHandle handle) {
// No containers plz
return AcceptResult.REJECTED;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.platform.IMixinPlatformAgent
* #getSideName()
*/
@Override
public String getSideName() {
Environment environment = Launcher.INSTANCE.environment();
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("missing").toLowerCase(Locale.ROOT);
if (launchTarget.contains("server")) {
return Constants.SIDE_SERVER;
}
if (launchTarget.contains("client")) {
return Constants.SIDE_CLIENT;
}
return null;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent
* #getMixinContainers()
*/
@Override
public Collection<IContainerHandle> getMixinContainers() {
return null;
}
}
| Detect side using getDist if launch handler name doesn't impl side
Closes #473 | src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java | Detect side using getDist if launch handler name doesn't impl side | <ide><path>rc/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java
<ide> */
<ide> package org.spongepowered.asm.launch.platform;
<ide>
<add>import java.lang.reflect.Method;
<ide> import java.util.Collection;
<ide> import java.util.Locale;
<add>import java.util.Optional;
<ide>
<ide> import org.spongepowered.asm.launch.platform.container.IContainerHandle;
<ide> import org.spongepowered.asm.util.Constants;
<ide> import cpw.mods.modlauncher.Environment;
<ide> import cpw.mods.modlauncher.Launcher;
<ide> import cpw.mods.modlauncher.api.IEnvironment;
<add>import cpw.mods.modlauncher.api.ILaunchHandlerService;
<ide>
<ide> /**
<ide> * Platform agent for minecraft forge under ModLauncher, only detects the side
<ide> */
<ide> public class MixinPlatformAgentMinecraftForge extends MixinPlatformAgentAbstract implements IMixinPlatformServiceAgent {
<add>
<add> /**
<add> * getDist method name in launch handler
<add> */
<add> private static final String GET_DIST_METHOD = "getDist";
<ide>
<ide> /* (non-Javadoc)
<ide> * @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent
<ide> if (launchTarget.contains("client")) {
<ide> return Constants.SIDE_CLIENT;
<ide> }
<add> Optional<ILaunchHandlerService> launchHandler = environment.findLaunchHandler(launchTarget);
<add> if (launchHandler.isPresent()) {
<add> ILaunchHandlerService service = launchHandler.get();
<add> try {
<add> Method mdGetDist = service.getClass().getDeclaredMethod(MixinPlatformAgentMinecraftForge.GET_DIST_METHOD);
<add> String strDist = mdGetDist.invoke(service).toString().toLowerCase(Locale.ROOT);
<add> if (strDist.contains("server")) {
<add> return Constants.SIDE_SERVER;
<add> }
<add> if (strDist.contains("client")) {
<add> return Constants.SIDE_CLIENT;
<add> }
<add> } catch (Exception ex) {
<add> return null;
<add> }
<add> }
<ide> return null;
<ide> }
<ide> |
|
Java | apache-2.0 | 9aa04ed4b1079328343f2aeae3bfe724d9d68d01 | 0 | Pluckypan/bigAndroid,Pluckypan/bigAndroid | package echo.engineer.oneactivity.cmpts.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
/**
* ClipView.java
* Useage: ClipView
* Created by Plucky<[email protected]> on 2017/8/18 - 13:58
*/
public class ClipView extends View implements View.OnClickListener {
private static final String TAG = "ClipView";
private Paint mPaintRed, mPaintBlue, mPaintAlpha, mPaintFont;
private int mWidth, mHeight;
private static final PorterDuff.Mode[] ALLS = new PorterDuff.Mode[]{Mode.CLEAR,
Mode.SRC,
Mode.DST,
Mode.SRC_OVER,
Mode.DST_OVER,
Mode.SRC_IN,
Mode.DST_IN,
Mode.SRC_OUT,
Mode.DST_OUT,
Mode.SRC_ATOP,
Mode.DST_ATOP,
Mode.XOR,
Mode.DARKEN,
Mode.LIGHTEN,
Mode.MULTIPLY,
Mode.SCREEN,
Mode.ADD,
Mode.OVERLAY
};
private static final String[] ALL_NAMES = new String[]{
"CLEAR",
"SRC",
"DST",
"SRC_OVER",
"DST_OVER",
"SRC_IN",
"DST_IN",
"SRC_OUT",
"DST_OUT",
"SRC_ATOP",
"DST_ATOP",
"XOR",
"DARKEN",
"LIGHTEN",
"MULTIPLY",
"SCREEN",
"ADD",
"OVERLAY"
};
public ClipView(Context context) {
this(context, null);
}
public ClipView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ClipView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//必须开启硬件加速
setLayerType(LAYER_TYPE_HARDWARE, null);
mPaintRed = new Paint();
mPaintRed.setColor(Color.RED);
mPaintBlue = new Paint();
mPaintBlue.setColor(Color.BLUE);
mPaintFont = new Paint();
mPaintFont.setTextSize(30);
mPaintFont.setColor(Color.WHITE);
mPaintAlpha = new Paint();
mPaintAlpha.setColor(Color.BLACK);
mPaintAlpha.setAlpha(60);
setOnClickListener(this);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
private static final int SPACE = 25;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, SPACE, 200, mHeight - SPACE, mPaintRed);
canvas.drawRect(100, SPACE, mWidth, mHeight - SPACE, mPaintBlue);
canvas.drawRect(250, 10, 300, mHeight - 10, mPaintAlpha);
String string = ALL_NAMES[mMode];
float w = mPaintFont.measureText(string);
canvas.drawText(string, mWidth - w - 20, mHeight / 2, mPaintFont);
}
private int mMode;
@Override
public void onClick(View v) {
mMode++;
if (mMode > 15) mMode = 0;
mPaintAlpha.setXfermode(new PorterDuffXfermode(ALLS[mMode]));
//mPaintBlue.setXfermode(new PorterDuffXfermode(ALLS[mMode]));
Log.d(TAG, "mMode=" + mMode);
postInvalidate();
}
}
| oneActivity/src/main/java/echo/engineer/oneactivity/cmpts/widget/ClipView.java | package echo.engineer.oneactivity.cmpts.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
/**
* ClipView.java
* Useage: ClipView
* Created by Plucky<[email protected]> on 2017/8/18 - 13:58
*/
public class ClipView extends View implements View.OnClickListener {
private static final String TAG = "ClipView";
private Paint mPaintRed, mPaintBlue, mPaintAlpha, mPaintFont;
private int mWidth, mHeight;
private static final PorterDuff.Mode[] ALLS = new PorterDuff.Mode[]{Mode.CLEAR,
Mode.SRC,
Mode.DST,
Mode.SRC_OVER,
Mode.DST_OVER,
Mode.SRC_IN,
Mode.DST_IN,
Mode.SRC_OUT,
Mode.DST_OUT,
Mode.SRC_ATOP,
Mode.DST_ATOP,
Mode.XOR,
Mode.DARKEN,
Mode.LIGHTEN,
Mode.MULTIPLY,
Mode.SCREEN,
Mode.ADD,
Mode.OVERLAY
};
private static final String[] ALL_NAMES = new String[]{
"CLEAR",
"SRC",
"DST",
"SRC_OVER",
"DST_OVER",
"SRC_IN",
"DST_IN",
"SRC_OUT",
"DST_OUT",
"SRC_ATOP",
"DST_ATOP",
"XOR",
"DARKEN",
"LIGHTEN",
"MULTIPLY",
"SCREEN",
"ADD",
"OVERLAY"
};
public ClipView(Context context) {
this(context, null);
}
public ClipView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ClipView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//必须开启硬件加速
setLayerType(LAYER_TYPE_HARDWARE, null);
mPaintRed = new Paint();
mPaintRed.setColor(Color.RED);
mPaintBlue = new Paint();
mPaintBlue.setColor(Color.BLUE);
mPaintFont = new Paint();
mPaintFont.setTextSize(30);
mPaintFont.setColor(Color.WHITE);
mPaintAlpha = new Paint();
mPaintAlpha.setAlpha(76);
setOnClickListener(this);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
private static final int SPACE = 25;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, SPACE, 200, mHeight - SPACE, mPaintRed);
canvas.drawRect(100, SPACE, mWidth, mHeight - SPACE, mPaintBlue);
canvas.drawRect(250, 10, 300, mHeight - 10, mPaintAlpha);
String string = ALL_NAMES[mMode];
float w = mPaintFont.measureText(string);
canvas.drawText(string, mWidth - w - 20, mHeight / 2, mPaintFont);
}
private int mMode;
@Override
public void onClick(View v) {
mMode++;
if (mMode > 15) mMode = 0;
mPaintAlpha.setXfermode(new PorterDuffXfermode(ALLS[mMode]));
//mPaintBlue.setXfermode(new PorterDuffXfermode(ALLS[mMode]));
Log.d(TAG, "mMode=" + mMode);
postInvalidate();
}
}
| ClipView设置SRC Paint颜色
| oneActivity/src/main/java/echo/engineer/oneactivity/cmpts/widget/ClipView.java | ClipView设置SRC Paint颜色 | <ide><path>neActivity/src/main/java/echo/engineer/oneactivity/cmpts/widget/ClipView.java
<ide> mPaintFont.setColor(Color.WHITE);
<ide>
<ide> mPaintAlpha = new Paint();
<del> mPaintAlpha.setAlpha(76);
<add> mPaintAlpha.setColor(Color.BLACK);
<add> mPaintAlpha.setAlpha(60);
<ide>
<ide> setOnClickListener(this);
<ide> } |
|
Java | bsd-3-clause | 8e66f6273d1973c8dfa944e9b1c527b4cf976333 | 0 | TheFakeMontyOnTheRun/gameworld | /**
*
*/
package br.odb.gameworld;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import br.odb.gameworld.exceptions.InvalidSlotException;
import br.odb.gameworld.exceptions.InventoryManipulationException;
import br.odb.gameworld.exceptions.ItemActionNotSupportedException;
import br.odb.gameworld.exceptions.ItemNotFoundException;
import br.odb.utils.Direction;
import br.odb.utils.Updatable;
/**
* @author monty
*
*/
public class Location implements Updatable {
public Location(String name) {
this.name = name;
connections = new Location[6];
material = new String[6];
}
private String[] material = new String[Direction.values().length];
private boolean magnetic;
private int lightning;
private Place place;
private final Door[] door = new Door[Direction.values().length];
private ArrayList<Item> items = new ArrayList<Item>();
private final String name;
private Location[] connections;
private String description;
private final List<CharacterActor> characters = new ArrayList<CharacterActor>();
private boolean hasBeenExplored;
private String floorId;
private String ambientSound;
public String getJSONState() {
StringBuilder sb = new StringBuilder();
sb.append( "'" );
sb.append( name );
sb.append( "': {" );
if ( items.size() > 0 ) {
sb.append( "'items': [ ");
for ( Item i : items ) {
sb.append( i.getJSONState() );
}
sb.append( "]," );
}
sb.append( "'connections': [" );
for ( Direction d : Direction.values() ) {
if ( connections[ d.ordinal() ] != null ) {
sb.append( "'" );
sb.append( d.simpleName );
sb.append( "':{" );
sb.append( door[ d.ordinal() ].getJSONState() );
sb.append( ", 'link':'" );
sb.append( connections[ d.ordinal() ].getName() );
sb.append( "'}," );
}
}
sb.append( "]," );
if ( characters.size() > 0 ) {
sb.append( "'characters': [" );
for ( CharacterActor ca : characters ) {
sb.append( ca.getJSONState() );
sb.append( "," );
}
sb.append( "]," );
}
sb.append( "'description': '" );
sb.append( description );
sb.append( "'," );
sb.append( "'lightning': '" );
sb.append( lightning );
sb.append( "'," );
sb.append( "'hasBeenExplored': '" );
sb.append( hasBeenExplored );
sb.append( "'," );
sb.append( "'floorId': '" );
sb.append( floorId );
sb.append( "'," );
sb.append( "'ambientSound': '" );
sb.append( ambientSound );
sb.append( "'" );
sb.append( "}" );
return sb.toString();
}
@Override
public void update(long milisseconds) {
for (Door d : door) {
if (d != null) {
d.update(milisseconds);
}
}
for (Item i : items) {
i.update(milisseconds);
}
for (CharacterActor a : characters) {
a.update(milisseconds);
}
}
@Override
public String toString() {
StringBuffer collectables = new StringBuffer();
StringBuffer connections = new StringBuffer();
if (items.size() > 0) {
collectables.append("\nObjects available in current location:");
}
collectables.append("\n");
for (Item i : this.items) {
//This is getting ugly...but does make some sense in the bigger picture. Plasma pellets move too fast.
if (i.location != this) {
continue;
}
collectables.append("- ");
collectables.append(i);
collectables.append("\n");
}
connections.append("\nPlaces to go:");
connections.append("\n");
for (Direction d : Direction.values()) {
if (this.connections[d.ordinal()] != null) {
connections.append(d + " : "
+ this.connections[d.ordinal()].getName());
connections.append(". \n");
}
}
return description + "\n" + collectables + connections;
}
public Location setCollectables(Item[] collectableItems) {
for (Item i : collectableItems) {
addItem( i );
}
return this;
}
public Item[] getCollectableItems() {
return items.toArray(new Item[items.size()]);
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result + Arrays.hashCode(door);
result = prime * result + (magnetic ? 1231 : 1237);
result = prime * result + Arrays.hashCode(material);
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Location)) {
return false;
}
Location other = (Location) obj;
if (!Arrays.equals(connections, other.connections)) {
return false;
}
if (description == null) {
if (other.description != null) {
return false;
}
} else if (!description.equals(other.description)) {
return false;
}
if (!Arrays.equals(door, other.door)) {
return false;
}
if (magnetic != other.magnetic) {
return false;
}
if (!Arrays.equals(material, other.material)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (place == null) {
if (other.place != null) {
return false;
}
} else if (!place.equals(other.place)) {
return false;
}
return true;
}
public Direction getConnectionDirectionForLocation(Location location)
throws InvalidSlotException {
if (location == null) {
throw new InvalidSlotException();
}
for (Direction d : Direction.values()) {
if (connections[d.ordinal()] == location) {
return d;
}
}
throw new InvalidSlotException();
}
public boolean containsCharacter(String charname) {
if (characters != null) {
for (CharacterActor c : characters) {
if (c.getName().equals(charname)) {
return true;
}
}
return false;
} else {
return false;
}
}
public Location setDescription(String description) {
this.description = description;
return this;
}
public Location setConnected(Direction d, Location location) {
connections[d.ordinal()] = location;
door[d.ordinal()] = new Door();
return this;
}
public void addCharacter(CharacterActor character) {
characters.add(character);
character.setLocation(this);
hasBeenExplored = true;
}
public void removeCharacter(CharacterActor character) {
characters.remove(character);
character.setLocation(null);
}
public boolean containsItem(String itemName) {
if (items != null) {
for (Item i : items) {
if (i.getName().equals(itemName)) {
return true;
}
}
}
return false;
}
public Location addItem(Item item) {
items.add(item);
item.location = this;
return this;
}
public Location[] getConnections() {
return connections;
}
public Item getItem(String obj) throws ItemNotFoundException {
for (Item i : items) {
if (i.getName().equalsIgnoreCase(obj)) {
return i;
}
}
throw new ItemNotFoundException();
}
public void removeItem(Item item) throws ItemNotFoundException {
if (!items.contains(item)) {
throw new ItemNotFoundException();
}
items.remove(item);
}
public boolean hasConnection(String entry) {
for (Location l : connections) {
if (l != null && l.getName().equalsIgnoreCase(entry)) {
return true;
}
}
return false;
}
public Door getDoor(Direction d) {
return this.door[d.ordinal()];
}
public Item giveItemTo(String itemName, CharacterActor c)
throws InventoryManipulationException, ItemNotFoundException,
ItemActionNotSupportedException {
Item item = getItem(itemName);
if (!item.isPickable()) {
throw new ItemActionNotSupportedException(Item.PICK_DENIAL_MESSAGE);
}
c.addItem(item.getName(), item);
c.getLocation().removeItem(item);
return item;
}
public Item takeItemFrom(String itemName, CharacterActor c)
throws ItemNotFoundException {
Item item = c.getItem(itemName);
c.removeItem(item);
c.getLocation().addItem(item);
return item;
}
public boolean hasExploredNeighbour() {
boolean toReturn = false;
for (Location l : connections) {
if (l != null) {
toReturn = toReturn || l.hasBeenExplored;
}
}
return toReturn;
}
public String getFloor() {
return floorId;
}
public Location setFloorId(String floorId) {
this.floorId = floorId;
return this;
}
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public boolean getHasBeenExplored() {
return hasBeenExplored;
}
public Door[] getDoors() {
return door;
}
public Collection<CharacterActor> getCharacters() {
return characters;
}
}
| src/main/java/br/odb/gameworld/Location.java | /**
*
*/
package br.odb.gameworld;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import br.odb.gameworld.exceptions.InvalidSlotException;
import br.odb.gameworld.exceptions.InventoryManipulationException;
import br.odb.gameworld.exceptions.ItemActionNotSupportedException;
import br.odb.gameworld.exceptions.ItemNotFoundException;
import br.odb.utils.Direction;
import br.odb.utils.Updatable;
/**
* @author monty
*
*/
public class Location implements Updatable {
public Location(String name) {
this.name = name;
connections = new Location[6];
material = new String[6];
}
private String[] material = new String[Direction.values().length];
private boolean magnetic;
private int lightning;
private Place place;
private final Door[] door = new Door[Direction.values().length];
private ArrayList<Item> items = new ArrayList<Item>();
private final String name;
private Location[] connections;
private String description;
private final List<CharacterActor> characters = new ArrayList<CharacterActor>();
private boolean hasBeenExplored;
private String floorId;
private String ambientSound;
public String getJSONState() {
StringBuilder sb = new StringBuilder();
sb.append( "'" );
sb.append( name );
sb.append( "': {" );
if ( items.size() > 0 ) {
sb.append( "'items': [ ");
for ( Item i : items ) {
sb.append( i.getJSONState() );
}
sb.append( "]," );
}
sb.append( "'connections': [" );
for ( Direction d : Direction.values() ) {
if ( connections[ d.ordinal() ] != null ) {
sb.append( "'" );
sb.append( d.simpleName );
sb.append( "':{" );
sb.append( door[ d.ordinal() ].getJSONState() );
sb.append( ", 'link':'" );
sb.append( connections[ d.ordinal() ].getName() );
sb.append( "'}," );
}
}
sb.append( "]," );
if ( characters.size() > 0 ) {
sb.append( "'characters': [" );
for ( CharacterActor ca : characters ) {
sb.append( ca.getJSONState() );
sb.append( "," );
}
sb.append( "]," );
}
sb.append( "'description': '" );
sb.append( description );
sb.append( "'," );
sb.append( "'lightning': '" );
sb.append( lightning );
sb.append( "'," );
sb.append( "'hasBeenExplored': '" );
sb.append( hasBeenExplored );
sb.append( "'," );
sb.append( "'floorId': '" );
sb.append( floorId );
sb.append( "'," );
sb.append( "'ambientSound': '" );
sb.append( ambientSound );
sb.append( "'" );
sb.append( "}" );
return sb.toString();
}
@Override
public void update(long milisseconds) {
for (Door d : door) {
if (d != null) {
d.update(milisseconds);
}
}
for (Item i : items) {
i.update(milisseconds);
}
for (CharacterActor a : characters) {
a.update(milisseconds);
}
}
@Override
public String toString() {
StringBuffer collectables = new StringBuffer();
StringBuffer connections = new StringBuffer();
if (items.size() > 0) {
collectables.append("\nObjects available in current location:");
}
collectables.append("\n");
for (Item i : this.items) {
//This is getting ugly...but does make some sense in the bigger picture. Plasma pellets move too fast.
if (i.location != this) {
continue;
}
collectables.append("- ");
collectables.append(i);
collectables.append("\n");
}
connections.append("\nPlaces to go:");
connections.append("\n");
for (Direction d : Direction.values()) {
if (this.connections[d.ordinal()] != null) {
connections.append(d + " : "
+ this.connections[d.ordinal()].getName());
connections.append(". \n");
}
}
return description + "\n" + collectables + connections;
}
public Location setCollectables(Item[] collectableItems) {
for (Item i : collectableItems) {
addItem( i );
}
return this;
}
public Item[] getCollectableItems() {
return items.toArray(new Item[items.size()]);
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result + Arrays.hashCode(door);
result = prime * result + (magnetic ? 1231 : 1237);
result = prime * result + Arrays.hashCode(material);
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Location)) {
return false;
}
Location other = (Location) obj;
if (!Arrays.equals(connections, other.connections)) {
return false;
}
if (description == null) {
if (other.description != null) {
return false;
}
} else if (!description.equals(other.description)) {
return false;
}
if (!Arrays.equals(door, other.door)) {
return false;
}
if (magnetic != other.magnetic) {
return false;
}
if (!Arrays.equals(material, other.material)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (place == null) {
if (other.place != null) {
return false;
}
} else if (!place.equals(other.place)) {
return false;
}
return true;
}
public Direction getConnectionDirectionForLocation(Location location)
throws InvalidSlotException {
if (location == null) {
throw new InvalidSlotException();
}
for (Direction d : Direction.values()) {
if (connections[d.ordinal()] == location) {
return d;
}
}
throw new InvalidSlotException();
}
public boolean containsCharacter(String charname) {
if (characters != null) {
for (CharacterActor c : characters) {
if (c.getName().equals(charname)) {
return true;
}
}
return false;
} else {
return false;
}
}
public Location setDescription(String description) {
this.description = description;
return this;
}
public Location setConnected(Direction d, Location location) {
connections[d.ordinal()] = location;
door[d.ordinal()] = new Door();
return this;
}
public void addCharacter(CharacterActor character) {
characters.add(character);
character.setLocation(this);
hasBeenExplored = true;
}
public void removeCharacter(CharacterActor character) {
characters.remove(character);
character.setLocation(null);
}
public boolean containsItem(String itemName) {
if (items != null) {
for (Item i : items) {
if (i.getName().equals(itemName)) {
return true;
}
}
}
return false;
}
public Location addItem(Item item) {
items.add(item);
item.location = this;
return this;
}
public Location[] getConnections() {
return connections;
}
public Item getItem(String obj) throws ItemNotFoundException {
for (Item i : items) {
if (i.getName().equalsIgnoreCase(obj)) {
return i;
}
}
throw new ItemNotFoundException();
}
public void removeItem(Item item) throws ItemNotFoundException {
if (!items.contains(item)) {
throw new ItemNotFoundException();
}
items.remove(item);
}
public boolean hasConnection(String entry) {
for (Location l : connections) {
if (l != null && l.getName().equalsIgnoreCase(entry)) {
return true;
}
}
return false;
}
public Door getDoor(Direction d) {
return this.door[d.ordinal()];
}
public Item giveItemTo(String itemName, CharacterActor c)
throws InventoryManipulationException, ItemNotFoundException,
ItemActionNotSupportedException {
Item item = getItem(itemName);
if (!item.isPickable()) {
throw new ItemActionNotSupportedException(Item.PICK_DENIAL_MESSAGE);
}
c.addItem(item.getName(), item);
c.getLocation().removeItem(item);
return item;
}
public Item takeItemFrom(String itemName, CharacterActor c)
throws ItemNotFoundException {
Item item = c.getItem(itemName);
c.removeItem(item);
c.getLocation().addItem(item);
return item;
}
public boolean hasExploredNeighbour() {
boolean toReturn = false;
for (Location l : connections) {
if (l != null) {
toReturn = toReturn || l.hasBeenExplored;
}
}
return toReturn;
}
public String getFloor() {
return floorId;
}
public Location setFloorId(String floorId) {
this.floorId = floorId;
return this;
}
public void setPlace(Place place) {
this.place = place;
}
public boolean getHasBeenExplored() {
return hasBeenExplored;
}
public Door[] getDoors() {
return door;
}
public Collection<CharacterActor> getCharacters() {
return characters;
}
}
| Adding getPlace to Location
Why having setPlace without getPlace?
| src/main/java/br/odb/gameworld/Location.java | Adding getPlace to Location | <ide><path>rc/main/java/br/odb/gameworld/Location.java
<ide> this.floorId = floorId;
<ide> return this;
<ide> }
<del>
<add>
<add> public Place getPlace() {
<add> return place;
<add> }
<ide>
<ide> public void setPlace(Place place) {
<ide> this.place = place; |
|
Java | apache-2.0 | fbd3a8fcb8630adb23efcb6430c15abd2aa834a9 | 0 | andrewdbate/jautomata,andrewdbate/jautomata | /*
* (C) Copyright 2005 Arnaud Bailly ([email protected]),
* Yves Roos ([email protected]) and others.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rationals.algebra;
import java.util.Iterator;
import java.util.Set;
import rationals.Rational;
import rationals.State;
import rationals.Transition;
import rationals.expr.Letter;
import rationals.expr.Plus;
import rationals.expr.RationalExpr;
/**
* A matrix for representing regular languages.
* <p>
* The cell of the matrix are rational expressions made from concatenation,
* epsilon, letters and union.
*
* @version $Id: RationalMatrix.java 2 2006-08-24 14:41:48Z oqube $
* @see rationals.expr
*/
public class RationalMatrix<L> {
private Matrix init;
private Matrix fini;
private Matrix transitions;
/**
* @return Returns the fini.
*/
public Matrix getFini() {
return fini;
}
/**
* @param fini The fini to set.
*/
public void setFini(Matrix fini) {
this.fini = fini;
}
/**
* @return Returns the init.
*/
public Matrix getInit() {
return init;
}
/**
* @param init The init to set.
*/
public void setInit(Matrix init) {
this.init = init;
}
/**
* @return Returns the transitions.
*/
public Matrix getTransitions() {
return transitions;
}
/**
* @param transitions The transitions to set.
*/
public void setTransitions(Matrix transitions) {
this.transitions = transitions;
}
/**
* Construct the matrix of a rational language.
*
* @param rat
* a Rational language.
*/
public RationalMatrix(Rational<L> rat) {
Set<State> st = rat.states();
int n = st.size();
init = Matrix.zero(1,n,RationalExpr.zero);
fini = Matrix.zero(n,1,RationalExpr.zero);
transitions = Matrix.zero(n,n,RationalExpr.zero);
State[] sta = (State[]) rat.states().toArray(new State[n]);
/* fill matrices */
for (int i = 0; i < sta.length; i++) {
if (sta[i].isInitial())
init.matrix[0][i] = Letter.epsilon;
else
init.matrix[0][i] = RationalExpr.zero;
if (sta[i].isTerminal())
fini.matrix[i][0] = Letter.epsilon;
else
fini.matrix[i][0] = RationalExpr.zero;
/* transitions */
for (int j = 0; j < n; j++) {
Set<Transition<L>> trs = rat.deltaFrom(sta[i], sta[j]);
RationalExpr re = null;
for (Iterator<Transition<L>> it = trs.iterator(); it.hasNext();) {
Transition<L> tr = it.next();
Object o = tr.label();
Letter l = (o == null) ? Letter.epsilon : new Letter(o);
if (re == null)
re = l;
else
re = new Plus(re, l);
}
transitions.matrix[i][j] = re == null ? RationalExpr.zero : re;
}
}
}
/**
* Compute words from this rational whose length is
* n.
*
* @param n
* @return
*/
public Matrix nwords(int n) {
Matrix res = transitions.power(n,Matrix.zero(transitions.getLine(),transitions.getLine(),RationalExpr.zero));
/* compute product for init and fini */
Matrix in = (Matrix)init.mult(res);
return (Matrix)in.mult(fini);
}
public String toString() {
return init.toString() + '\n'+ transitions.toString() + '\n'+fini.toString();
}
}
| jautomata-core/src/main/java/rationals/algebra/RationalMatrix.java | /*
* (C) Copyright 2005 Arnaud Bailly ([email protected]),
* Yves Roos ([email protected]) and others.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rationals.algebra;
import java.util.Iterator;
import java.util.Set;
import rationals.Rational;
import rationals.State;
import rationals.Transition;
import rationals.expr.Letter;
import rationals.expr.Plus;
import rationals.expr.RationalExpr;
/**
* A matrix for representing regular languages.
* <p>
* The cell of the matrix are rational expressions made from concatenation,
* epsilon, letters and union.
*
* @version $Id: RationalMatrix.java 2 2006-08-24 14:41:48Z oqube $
* @see rationals.expr
*/
public class RationalMatrix {
private Matrix init;
private Matrix fini;
private Matrix transitions;
/**
* @return Returns the fini.
*/
public Matrix getFini() {
return fini;
}
/**
* @param fini The fini to set.
*/
public void setFini(Matrix fini) {
this.fini = fini;
}
/**
* @return Returns the init.
*/
public Matrix getInit() {
return init;
}
/**
* @param init The init to set.
*/
public void setInit(Matrix init) {
this.init = init;
}
/**
* @return Returns the transitions.
*/
public Matrix getTransitions() {
return transitions;
}
/**
* @param transitions The transitions to set.
*/
public void setTransitions(Matrix transitions) {
this.transitions = transitions;
}
/**
* Construct the matrix of a rational language.
*
* @param rat
* a Rational language.
*/
public RationalMatrix(Rational rat) {
Set st = rat.states();
int n = st.size();
init = Matrix.zero(1,n,RationalExpr.zero);
fini = Matrix.zero(n,1,RationalExpr.zero);
transitions = Matrix.zero(n,n,RationalExpr.zero);
State[] sta = (State[]) rat.states().toArray(new State[n]);
/* fill matrices */
for (int i = 0; i < sta.length; i++) {
if (sta[i].isInitial())
init.matrix[0][i] = Letter.epsilon;
else
init.matrix[0][i] = RationalExpr.zero;
if (sta[i].isTerminal())
fini.matrix[i][0] = Letter.epsilon;
else
fini.matrix[i][0] = RationalExpr.zero;
/* transitions */
for (int j = 0; j < n; j++) {
Set trs = rat.deltaFrom(sta[i], (State) sta[j]);
RationalExpr re = null;
for (Iterator it = trs.iterator(); it.hasNext();) {
Transition tr = (Transition) it.next();
Object o = tr.label();
Letter l = (o == null) ? Letter.epsilon : new Letter(o);
if (re == null)
re = l;
else
re = new Plus(re, l);
}
transitions.matrix[i][j] = re == null ? RationalExpr.zero : re;
}
}
}
/**
* Compute words from this rational whose length is
* n.
*
* @param n
* @return
*/
public Matrix nwords(int n) {
Matrix res = transitions.power(n,Matrix.zero(transitions.getLine(),transitions.getLine(),RationalExpr.zero));
/* compute product for init and fini */
Matrix in = (Matrix)init.mult(res);
return (Matrix)in.mult(fini);
}
public String toString() {
return init.toString() + '\n'+ transitions.toString() + '\n'+fini.toString();
}
}
| Add generics.
| jautomata-core/src/main/java/rationals/algebra/RationalMatrix.java | Add generics. | <ide><path>automata-core/src/main/java/rationals/algebra/RationalMatrix.java
<ide> * @version $Id: RationalMatrix.java 2 2006-08-24 14:41:48Z oqube $
<ide> * @see rationals.expr
<ide> */
<del>public class RationalMatrix {
<add>public class RationalMatrix<L> {
<ide>
<ide> private Matrix init;
<ide> private Matrix fini;
<ide> * @param rat
<ide> * a Rational language.
<ide> */
<del> public RationalMatrix(Rational rat) {
<del> Set st = rat.states();
<add> public RationalMatrix(Rational<L> rat) {
<add> Set<State> st = rat.states();
<ide> int n = st.size();
<ide> init = Matrix.zero(1,n,RationalExpr.zero);
<ide> fini = Matrix.zero(n,1,RationalExpr.zero);
<ide> fini.matrix[i][0] = RationalExpr.zero;
<ide> /* transitions */
<ide> for (int j = 0; j < n; j++) {
<del> Set trs = rat.deltaFrom(sta[i], (State) sta[j]);
<add> Set<Transition<L>> trs = rat.deltaFrom(sta[i], sta[j]);
<ide> RationalExpr re = null;
<del> for (Iterator it = trs.iterator(); it.hasNext();) {
<del> Transition tr = (Transition) it.next();
<add> for (Iterator<Transition<L>> it = trs.iterator(); it.hasNext();) {
<add> Transition<L> tr = it.next();
<ide> Object o = tr.label();
<ide> Letter l = (o == null) ? Letter.epsilon : new Letter(o);
<ide> if (re == null) |
|
JavaScript | agpl-3.0 | 38d984ad232785b61593e0ae4f3cc2a685c9ddcf | 0 | quoideneuf/pop-up-archive,quoideneuf/pop-up-archive,quoideneuf/pop-up-archive,quoideneuf/pop-up-archive | angular.module('Directory.items.models', ['RailsModel', 'Directory.audioFiles.models', 'Directory.imageFiles.models'])
.factory('Item', ['Model', '$http', '$q', 'Contribution', 'Person', 'AudioFile', 'Player', 'ImageFile', function (Model, $http, $q, Contribution, Person, AudioFile, Player, ImageFile) {
var attrAccessible = "dateBroadcast dateCreated datePeg description digitalFormat digitalLocation episodeTitle identifier language musicSoundUsed notes physicalFormat physicalLocation rights seriesTitle tags title transcription adoptToCollection tagList text id originalFileUrl".split(' ');
var Item = Model({url:'/api/collections/{{collectionId}}/items/{{id}}', name: 'item', only: attrAccessible});
Item.beforeRequest(function(data, resource) {
var dataList = [];
if (angular.isArray(data)) {
dataList = data;
} else {
dataList = [data];
}
angular.forEach(dataList, function(value, key){
value.tags = [];
value.images = [];
angular.forEach((value.tag_list || []), function (v,k) {
value.tags.push(v['text']);
});
angular.forEach((value.images || []), function (v,k) {
value.images.push(v['imageFiles']);
});
delete value.tag_list;
delete value.images;
if ((!value.id || parseInt(value.id, 10) <= 0) || (value.adoptToCollection == value.collectionId)) {
delete value.adoptToCollection;
}
// console.log("item value:", value);
if (value.language) {
value.language = value.language.id;
}
});
return data;
});
Item.beforeResponse(function(data, resource) {
// console.log("beforeResponse");
console.log(data);
data.tagList = [];
data.images = [];
angular.forEach((data.tags || []), function (v,k) {
data.tagList.push({id:v, text:v});
});
angular.forEach((data.images || []), function (v,k) {
data.images.push({id:v, imageFile:v});
});
// console.log(data, data.images);
data.language = {id: data.language, text: Item.languageLookup[data.language]};
if (data.id) {
data.adoptToCollection = data.collectionId;
}
return data;
});
Item._setLanguageLookup = function(langs) {
var lookup = {};
for(var i in langs) {
if (langs[i].id && langs[i].text) {
lookup[langs[i].id] = langs[i].text;
}
if (langs[i].children) {
var children = langs[i].children;
for(var ci in children) {
lookup[children[ci].id] = children[ci].text;
}
}
}
return lookup;
};
Item.languages = [{"text":"Common","children":[{"id":"en-US","text":"English (United States)"},{"id":"ar-EG","text":"Arabic (Egypt)"},{"id":"zh-CN","text":"Chinese (China)"},{"id":"fr-FR","text":"French"},{"id":"de-DE","text":"German"},{"id":"it-IT","text":"Italian"},{"id":"ja-JA","text":"Japanese"},{"id":"ko-KO","text":"Korean"},{"id":"pt-PT","text":"Portuguese"},{"id":"ru-RU","text":"Russian"},{"id":"es-ES","text":"Spanish (Spain)"}]},{"text":"Afrikaans","children":[{"id":"af-NA","text":"Afrikaans (Namibia)"},{"id":"af-ZA","text":"Afrikaans (South Africa)"}]},{"text":"Arabic","children":[{"id":"ar-AE","text":"Arabic (United Arab Emirates)"},{"id":"ar-BH","text":"Arabic (Bahrain)"},{"id":"ar-DJ","text":"Arabic (Djibouti)"},{"id":"ar-DZ","text":"Arabic (Algeria)"},{"id":"ar-EG","text":"Arabic (Egypt)"},{"id":"ar-ER","text":"Arabic (Eritrea)"},{"id":"ar-IL","text":"Arabic (Israel)"},{"id":"ar-IQ","text":"Arabic (Iraq)"},{"id":"ar-JO","text":"Arabic (Jordan)"},{"id":"ar-KM","text":"Arabic (Comoros)"},{"id":"ar-KW","text":"Arabic (Kuwait)"},{"id":"ar-LB","text":"Arabic (Lebanon)"},{"id":"ar-LY","text":"Arabic (Libya)"},{"id":"ar-MA","text":"Arabic (Morocco)"},{"id":"ar-MR","text":"Arabic (Mauritania)"},{"id":"ar-OM","text":"Arabic (Oman)"},{"id":"ar-QA","text":"Arabic (Qatar)"},{"id":"ar-SA","text":"Arabic (Saudi Arabia)"},{"id":"ar-SD","text":"Arabic (Sudan)"},{"id":"ar-SO","text":"Arabic (Somalia)"},{"id":"ar-SY","text":"Arabic (Syrian Arab Republic)"},{"id":"ar-TD","text":"Arabic (Chad)"},{"id":"ar-TN","text":"Arabic (Tunisia)"},{"id":"ar-YE","text":"Arabic (Yemen)"}]},{"id":"bn-BD","text":"Bengali (Bangladesh)"},{"id":"bo","text":"Tibetan"},{"id":"bg-BG","text":"Bulgarian (Bulgaria)"},{"id":"ca-AD","text":"Catalan (Andorra)"},{"id":"cs-CZ","text":"Czech (Czech Republic)"},{"id":"cy","text":"Welsh"},{"id":"da-DK","text":"Danish (Denmark)"},{"text":"German","children":[{"id":"de-AT","text":"German (Austria)"},{"id":"de-BE","text":"German (Belgium)"},{"id":"de-CH","text":"German (Switzerland)"},{"id":"de-DE","text":"German (Germany)"},{"id":"de-LI","text":"German (Liechtenstein)"},{"id":"de-LU","text":"German (Luxembourg)"}]},{"text":"Modern Greek (1453-)","children":[{"id":"el-CY","text":"Modern Greek (1453-) (Cyprus)"},{"id":"el-GR","text":"Modern Greek (1453-) (Greece)"}]},{"text":"English","children":[{"id":"en-AG","text":"English (Antigua and Barbuda)"},{"id":"en-AI","text":"English (Anguilla)"},{"id":"en-AN","text":"English (Netherlands Antilles)"},{"id":"en-AS","text":"English (American Samoa)"},{"id":"en-AU","text":"English (Australia)"},{"id":"en-BB","text":"English (Barbados)"},{"id":"en-BM","text":"English (Bermuda)"},{"id":"en-BS","text":"English (Bahamas)"},{"id":"en-BW","text":"English (Botswana)"},{"id":"en-BZ","text":"English (Belize)"},{"id":"en-CA","text":"English (Canada)"},{"id":"en-CC","text":"English (Cocos (Keeling) Islands)"},{"id":"en-CK","text":"English (Cook Islands)"},{"id":"en-CM","text":"English (Cameroon)"},{"id":"en-CX","text":"English (Christmas Island)"},{"id":"en-DM","text":"English (Dominica)"},{"id":"en-ER","text":"English (Eritrea)"},{"id":"en-FJ","text":"English (Fiji)"},{"id":"en-FK","text":"English (Falkland Islands (Malvinas))"},{"id":"en-FM","text":"English (Micronesia, Federated States Of)"},{"id":"en-GD","text":"English (Grenada)"},{"id":"en-GH","text":"English (Ghana)"},{"id":"en-GI","text":"English (Gibraltar)"},{"id":"en-GM","text":"English (Gambia)"},{"id":"en-GS","text":"English (South Georgia and the South Sandwich Islands)"},{"id":"en-GU","text":"English (Guam)"},{"id":"en-GY","text":"English (Guyana)"},{"id":"en-HK","text":"English (Hong Kong)"},{"id":"en-HM","text":"English (Heard and McDonald Islands)"},{"id":"en-IE","text":"English (Ireland)"},{"id":"en-IN","text":"English (India)"},{"id":"en-IO","text":"English (British Indian Ocean Territory)"},{"id":"en-JM","text":"English (Jamaica)"},{"id":"en-KE","text":"English (Kenya)"},{"id":"en-KI","text":"English (Kiribati)"},{"id":"en-KN","text":"English (Saint Kitts And Nevis)"},{"id":"en-KY","text":"English (Cayman Islands)"},{"id":"en-LC","text":"English (Saint Lucia)"},{"id":"en-LR","text":"English (Liberia)"},{"id":"en-LS","text":"English (Lesotho)"},{"id":"en-MH","text":"English (Marshall Islands)"},{"id":"en-MP","text":"English (Northern Mariana Islands)"},{"id":"en-MS","text":"English (Montserrat)"},{"id":"en-MT","text":"English (Malta)"},{"id":"en-MU","text":"English (Mauritius)"},{"id":"en-MW","text":"English (Malawi)"},{"id":"en-MY","text":"English (Malaysia)"},{"id":"en-NA","text":"English (Namibia)"},{"id":"en-NF","text":"English (Norfolk Island)"},{"id":"en-NG","text":"English (Nigeria)"},{"id":"en-NR","text":"English (Nauru)"},{"id":"en-NU","text":"English (Niue)"},{"id":"en-NZ","text":"English (New Zealand)"},{"id":"en-PG","text":"English (Papua New Guinea)"},{"id":"en-PH","text":"English (Philippines)"},{"id":"en-PK","text":"English (Pakistan)"},{"id":"en-PN","text":"English (Pitcairn)"},{"id":"en-PR","text":"English (Puerto Rico)"},{"id":"en-PW","text":"English (Palau)"},{"id":"en-RW","text":"English (Rwanda)"},{"id":"en-SB","text":"English (Solomon Islands)"},{"id":"en-SC","text":"English (Seychelles)"},{"id":"en-SD","text":"English (Sudan)"},{"id":"en-SG","text":"English (Singapore)"},{"id":"en-SH","text":"English (Saint Helena)"},{"id":"en-SL","text":"English (Sierra Leone)"},{"id":"en-SZ","text":"English (Swaziland)"},{"id":"en-TC","text":"English (Turks and Caicos Islands)"},{"id":"en-TK","text":"English (Tokelau)"},{"id":"en-TO","text":"English (Tonga)"},{"id":"en-TT","text":"English (Trinidad and Tobago)"},{"id":"en-TV","text":"English (Tuvalu)"},{"id":"en-TZ","text":"English (Tanzania, United Republic of)"},{"id":"en-UG","text":"English (Uganda)"},{"id":"en-UM","text":"English (United States Minor Outlying Islands)"},{"id":"en-US","text":"English (United States)"},{"id":"en-VC","text":"English (Saint Vincent And The Grenedines)"},{"id":"en-VG","text":"English (Virgin Islands, British)"},{"id":"en-VI","text":"English (Virgin Islands, U.S.)"},{"id":"en-VU","text":"English (Vanuatu)"},{"id":"en-WS","text":"English (Samoa)"},{"id":"en-ZA","text":"English (South Africa)"},{"id":"en-ZM","text":"English (Zambia)"},{"id":"en-ZW","text":"English (Zimbabwe)"}]},{"id":"et-EE","text":"Estonian (Estonia)"},{"id":"eu","text":"Basque"},{"id":"fa-IR","text":"Persian (Iran, Islamic Republic Of)"},{"id":"fj-FJ","text":"Fijian (Fiji)"},{"id":"fi","text":"Finnish (Finland)"},{"text":"French","children":[{"id":"fr-BE","text":"French (Belgium)"},{"id":"fr-BF","text":"French (Burkina Faso)"},{"id":"fr-BI","text":"French (Burundi)"},{"id":"fr-BJ","text":"French (Benin)"},{"id":"fr-CA","text":"French (Canada)"},{"id":"fr-CD","text":"French (Congo, The Democratic Republic Of The)"},{"id":"fr-CF","text":"French (Central African Republic)"},{"id":"fr-CG","text":"French (Congo)"},{"id":"fr-CH","text":"French (Switzerland)"},{"id":"fr-CI","text":"French (C\u00f4te D'Ivoire)"},{"id":"fr-CM","text":"French (Cameroon)"},{"id":"fr-DJ","text":"French (Djibouti)"},{"id":"fr-EH","text":"French (Western Sahara)"},{"id":"fr-FR","text":"French (France)"},{"id":"fr-GA","text":"French (Gabon)"},{"id":"fr-GF","text":"French (French Guiana)"},{"id":"fr-GN","text":"French (Guinea)"},{"id":"fr-GP","text":"French (Guadeloupe)"},{"id":"fr-GQ","text":"French (Equatorial Guinea)"},{"id":"fr-HT","text":"French (Haiti)"},{"id":"fr-KM","text":"French (Comoros)"},{"id":"fr-LB","text":"French (Lebanon)"},{"id":"fr-LU","text":"French (Luxembourg)"},{"id":"fr-MC","text":"French (Monaco)"},{"id":"fr-MG","text":"French (Madagascar)"},{"id":"fr-ML","text":"French (Mali)"},{"id":"fr-MQ","text":"French (Martinique)"},{"id":"fr-MR","text":"French (Mauritania)"},{"id":"fr-NC","text":"French (New Caledonia)"},{"id":"fr-NE","text":"French (Niger)"},{"id":"fr-PF","text":"French (French Polynesia)"},{"id":"fr-PM","text":"French (Saint Pierre And Miquelon)"},{"id":"fr-RE","text":"French (R\u00e9union)"},{"id":"fr-RW","text":"French (Rwanda)"},{"id":"fr-SC","text":"French (Seychelles)"},{"id":"fr-SN","text":"French (Senegal)"},{"id":"fr-TD","text":"French (Chad)"},{"id":"fr-TG","text":"French (Togo)"},{"id":"fr-TN","text":"French (Tunisia)"},{"id":"fr-VU","text":"French (Vanuatu)"},{"id":"fr-WF","text":"French (Wallis and Futuna)"},{"id":"fr-YT","text":"French (Mayotte)"}]},{"id":"ga-IE","text":"Irish (Ireland)"},{"id":"gu","text":"Gujarati"},{"text":"Hebrew","children":[{"id":"he-IL","text":"Hebrew (Israel)"}]},{"text":"Hindi","children":[{"id":"hi-FJ","text":"Hindi (Fiji)"},{"id":"hi-IN","text":"Hindi (India)"}]},{"text":"Croatian","children":[{"id":"hr-BA","text":"Croatian (Bosnia and Herzegovina)"},{"id":"hr-HR","text":"Croatian (Croatia)"},{"id":"hr-ME","text":"Croatian (Montenegro)"}]},{"id":"hu-HU","text":"Hungarian (Hungary)"},{"text":"Armenian","children":[{"id":"hy-AM","text":"Armenian (Armenia)"},{"id":"hy-AZ","text":"Armenian (Azerbaijan)"},{"id":"hy-CY","text":"Armenian (Cyprus)"}]},{"id":"id-ID","text":"Indonesian (Indonesia)"},{"id":"is-IS","text":"Icelandic (Iceland)"},{"text":"Italian","children":[{"id":"it-CH","text":"Italian (Switzerland)"},{"id":"it-IT","text":"Italian (Italy)"},{"id":"it-SM","text":"Italian (San Marino)"},{"id":"it-VA","text":"Italian (Holy See (Vatican City State))"}]},{"id":"ja-JP","text":"Japanese (Japan)"},{"id":"ka-GE","text":"Georgian (Georgia)"},{"id":"km-KH","text":"Central Khmer (Cambodia)"},{"text":"Korean","children":[{"id":"ko-KP","text":"Korean (Korea, Democratic People's Republic Of)"},{"id":"ko-KR","text":"Korean (Korea, Republic of)"}]},{"id":"la-VA","text":"Latin (Holy See (Vatican City State))"},{"id":"lv-LV","text":"Latvian (Latvia)"},{"id":"lt-LT","text":"Lithuanian (Lithuania)"},{"id":"ml","text":"Malayalam"},{"id":"mr","text":"Marathi"},{"id":"mk-MK","text":"Macedonian (Macedonia, the Former Yugoslav Republic Of)"},{"id":"mt-MT","text":"Maltese (Malta)"},{"id":"mn-MN","text":"Mongolian (Mongolia)"},{"id":"mi","text":"Maori"},{"text":"Malay","children":[{"id":"ms-BN","text":"Malay (Brunei Darussalam)"},{"id":"ms-CX","text":"Malay (Christmas Island)"},{"id":"ms-SG","text":"Malay (Singapore)"}]},{"id":"ne-NP","text":"Nepali (Nepal)"},{"text":"Dutch","children":[{"id":"nl-AN","text":"Dutch (Netherlands Antilles)"},{"id":"nl-AW","text":"Dutch (Aruba)"},{"id":"nl-BE","text":"Dutch (Belgium)"},{"id":"nl-NL","text":"Dutch (Netherlands)"},{"id":"nl-SR","text":"Dutch (Suriname)"}]},{"text":"Norwegian","children":[{"id":"no-NL","text":"Norwegian (Norway)"},{"id":"no-SJ","text":"Norwegian (Svalbard And Jan Mayen)"}]},{"id":"pa","text":"Panjabi"},{"id":"pl-PL","text":"Polish (Poland)"},{"text":"Portuguese","children":[{"id":"pt-AO","text":"Portuguese (Angola)"},{"id":"pt-BR","text":"Portuguese (Brazil)"},{"id":"pt-CV","text":"Portuguese (Cape Verde)"},{"id":"pt-GW","text":"Portuguese (Guinea-Bissau)"},{"id":"pt-MO","text":"Portuguese (Macao)"},{"id":"pt-MZ","text":"Portuguese (Mozambique)"},{"id":"pt-PT","text":"Portuguese (Portugal)"},{"id":"pt-ST","text":"Portuguese (Sao Tome and Principe)"}]},{"id":"qu-BO","text":"Quechua (Bolivia)"},{"text":"Romanian","children":[{"id":"ro-MD","text":"Romanian (Moldova, Republic of)"},{"id":"ro-RO","text":"Romanian (Romania)"}]},{"text":"Russian","children":[{"id":"ru-AM","text":"Russian (Armenia)"},{"id":"ru-BY","text":"Russian (Belarus)"},{"id":"ru-KG","text":"Russian (Kyrgyzstan)"},{"id":"ru-KZ","text":"Russian (Kazakhstan)"},{"id":"ru-RU","text":"Russian (Russian Federation)"},{"id":"ru-TJ","text":"Russian (Tajikistan)"},{"id":"ru-TM","text":"Russian (Turkmenistan)"},{"id":"ru-UZ","text":"Russian (Uzbekistan)"}]},{"text":"Slovak","children":[{"id":"sk-CZ","text":"Slovak (Czech Republic)"},{"id":"sk-SK","text":"Slovak (Slovakia)"}]},{"id":"sl-SI","text":"Slovenian (Slovenia)"},{"text":"Samoan","children":[{"id":"sm-AS","text":"Samoan (American Samoa)"},{"id":"sm-WS","text":"Samoan (Samoa)"}]},{"text":"Spanish","children":[{"id":"es-AR","text":"Spanish (Argentina)"},{"id":"es-BO","text":"Spanish (Bolivia)"},{"id":"es-BZ","text":"Spanish (Belize)"},{"id":"es-CL","text":"Spanish (Chile)"},{"id":"es-CO","text":"Spanish (Colombia)"},{"id":"es-CR","text":"Spanish (Costa Rica)"},{"id":"es-CU","text":"Spanish (Cuba)"},{"id":"es-DO","text":"Spanish (Dominican Republic)"},{"id":"es-EC","text":"Spanish (Ecuador)"},{"id":"es-EH","text":"Spanish (Western Sahara)"},{"id":"es-ES","text":"Spanish (Spain)"},{"id":"es-GQ","text":"Spanish (Equatorial Guinea)"},{"id":"es-GT","text":"Spanish (Guatemala)"},{"id":"es-GU","text":"Spanish (Guam)"},{"id":"es-HN","text":"Spanish (Honduras)"},{"id":"es-MX","text":"Spanish (Mexico)"},{"id":"es-NI","text":"Spanish (Nicaragua)"},{"id":"es-PA","text":"Spanish (Panama)"},{"id":"es-PE","text":"Spanish (Peru)"},{"id":"es-PR","text":"Spanish (Puerto Rico)"},{"id":"es-PY","text":"Spanish (Paraguay)"},{"id":"es-SV","text":"Spanish (El Salvador)"},{"id":"es-UY","text":"Spanish (Uruguay)"},{"id":"es-VE","text":"Spanish (Venezuela, Bolivarian Republic of)"}]},{"text":"Albanian","children":[{"id":"sq-AL","text":"Albanian (Albania)"},{"id":"sq-ME","text":"Albanian (Montenegro)"}]},{"text":"Serbian","children":[{"id":"sr-BA","text":"Serbian (Bosnia and Herzegovina)"},{"id":"sr-ME","text":"Serbian (Montenegro)"},{"id":"sr-RS","text":"Serbian (Serbia)"}]},{"text":"Swahili","children":[{"id":"sw-CD","text":"Swahili (Congo, The Democratic Republic Of The)"},{"id":"sw-KE","text":"Swahili (Kenya)"},{"id":"sw-TZ","text":"Swahili (Tanzania, United Republic of)"},{"id":"sw-UG","text":"Swahili (Uganda)"}]},{"text":"Swedish","children":[{"id":"sv-SE","text":"Swedish (Sweden)"}]},{"text":"Tamil","children":[{"id":"ta-LK","text":"Tamil (Sri Lanka)"},{"id":"ta-SG","text":"Tamil (Singapore)"}]},{"id":"tt","text":"Tatar"},{"id":"te","text":"Telugu"},{"id":"th-TH","text":"Thai (Thailand)"},{"id":"to-TO","text":"Tonga (Tonga Islands) (Tonga)"},{"text":"Turkish","children":[{"id":"tr-CY","text":"Turkish (Cyprus)"},{"id":"tr-TR","text":"Turkish (Turkey)"}]},{"id":"uk-UA","text":"Ukrainian (Ukraine)"},{"text":"Urdu","children":[{"id":"ur-FJ","text":"Urdu (Fiji)"},{"id":"ur-PK","text":"Urdu (Pakistan)"}]},{"text":"Uzbek","children":[{"id":"uz-AF","text":"Uzbek (Afghanistan)"},{"id":"uz-UZ","text":"Uzbek (Uzbekistan)"}]},{"id":"vi-VN","text":"Vietnamese (Viet Nam)"},{"id":"xh-ZA","text":"Xhosa (South Africa)"},{"text":"Chinese","children":[{"id":"zh-CN","text":"Chinese (China)"},{"id":"zh-CX","text":"Chinese (Christmas Island)"},{"id":"zh-HK","text":"Chinese (Hong Kong)"},{"id":"zh-MO","text":"Chinese (Macao)"},{"id":"zh-TW","text":"Chinese (Taiwan, Republic Of China)"}]}];
Item.languageLookup = Item._setLanguageLookup(Item.languages);
Item.prototype.tagList2Tags = function() {
var self = this;
self.tags = [];
angular.forEach((self.tagList || []), function (v,k) {
self.tags.push(v['text']);
});
};
Item.prototype.getTitle = function () {
if (this.title) { return this.title; }
if (this.episodeTitle) { return this.episodeTitle + " : " + this.identifier; }
if (this.seriesTitle) { return this.seriesTitle + " : " + this.identifier; }
}
Item.prototype.getDescription = function () {
if (this.description) { return this.description; }
if (this.notes) { return this.notes; }
}
Item.prototype.getImages = function () {
if (this.imageFiles) {return this.imageFiles}
}
Item.prototype.getThumbClass = function () {
if (this.audioFiles && this.audioFiles.length > 0) {
return "icon-volume-up";
} else {
return "icon-file-alt"
}
}
Item.prototype.link = function () {
return "/collections/" + this.collectionId + "/items/" + this.id;
}
Item.prototype.getDurationString = function () {
var d = new Date(this.duration * 1000);
return d.getUTCHours() + ":" + d.getUTCMinutes() + ":" + d.getUTCSeconds();
}
Item.prototype.adopt = function (collectionId) {
var self = this;
this.adoptToCollection = collectionId;
return this.update().then(function (data) {
self.adoptToCollection = undefined;
return data;
});
}
Item.prototype.contributors = function (role) {
var result = [];
angular.forEach(this.contributions, function (contribution) {
if (contribution.role == role) {
result.push(contribution.person.name);
} else {
}
});
return result;
}
// Item.prototype.image = function (image) {
// var images = [];
// angular.forEach(this.images, function (images) {
// images.push(image);
// })
// }
Item.prototype.addImageFile = function (file, options ){
var options = options || {};
var item = this;
var originalFileUrl = null;
if (angular.isDefined(file.url)) {
originalFileUrl = file.url;
}
var imageFile = new ImageFile({container: "items", containerId: item.id, originalFileUrl: originalFileUrl});
imageFile.create().then( function() {
imageFile.filename = imageFile.cleanFileName(file.name);
item.imageFiles = item.imageFiles || [];
item.imageFiles.push(imageFile);
options.token = item.token;
imageFile.upload(file, options);
});
return imageFile;
}
Item.prototype.addAudioFile = function (file, options) {
var options = options || {};
var item = this;
var audioFile = new AudioFile({itemId: item.id});
audioFile.create().then( function () {
audioFile.filename = audioFile.cleanFileName(file.name);
item.audioFiles = item.audioFiles || [];
item.audioFiles.push(audioFile);
options.token = item.token;
audioFile.upload(file, options);
});
return audioFile;
}
// update existing audioFiles
Item.prototype.updateAudioFiles = function () {
var item = this;
var keepAudioFiles = [];
angular.forEach(item.audioFiles, function (audioFile, index) {
// console.log('updateAudioFiles', index, audioFile);
var af = new AudioFile(audioFile);
af.itemId = item.id;
// delete c if marked for delete
if (af._delete) {
// console.log('updateAudioFiles delete', audioFile, item);
af.delete();
} else {
keepAudioFiles.push(audioFile);
}
// else if (af.id) {
// af.update();
// }
});
item.audioFiles = keepAudioFiles;
}
Item.prototype.updateImageFiles = function () {
var item = this;
var keepImageFiles = [];
angular.forEach(item.imageFiles, function (imageFile, index) {
// console.log('updateImageFiles', index, imageFile);
var iF = new imageFile(imageFile);
iF.itemId = item.id;
// delete c if marked for delete
if (iF._delete) {
// console.log('updateImageFiles delete', audioFile, item);
iF.delete();
} else {
keepImageFiles.push(imageFile);
}
});
item.imageFiles = keepImageFiles;
}
Item.prototype.playable = function () {
return this.audioFiles && this.audioFiles.length > 0;
}
Item.prototype.entityShortList = function () {
this._entityShortList = this._entityShortList || [];
this._entityShortList.length = 0;
if (this.tags && this.tags.length >= 5) {
for (var i=0; i<5; i++) {
this._entityShortList.push(this.tags[i]);
}
} else {
angular.forEach(this.tags, function (tag) {
this._entityShortList.push(tag);
}, this);
var i = 0;
if (this.entities) {
while (i < this.entities.length && this._entityShortList.length <= 5) {
this._entityShortList.push(this.entities[i].name);
i++;
}
}
}
return this._entityShortList;
}
Item.prototype.paused = function () {
return this.playable() && !this.playing();
}
Item.prototype.loadedIntoPlayer = function () {
var me = false;
if (Player.nowPlayingUrl() && this.playable()) {
var nowPlaying = Player.nowPlayingUrl().toString().split('?')[0];
angular.forEach(this.audioFiles, function (file) {
if (file.url && (nowPlaying == file.url.split('?')[0])) {
me = true;
}
});
} else {
return false;
}
return me;
}
Item.prototype.playing = function() {
return this.loadedIntoPlayer() && !Player.paused();
}
// update existing contributions
Item.prototype.updateContributions = function () {
var item = this;
var keepContributions = [];
angular.forEach(item.contributions, function (contribution, index) {
var c = new Contribution(contribution);
c.itemId = item.id;
// delete c if marked for delete
if (c._delete) {
c.delete();
// item.contributions.splice(index, 1);
} else {
keepContributions.push(c);
if (!c.person.id || (c.person.id == 'new')) {
var p = new Person({'name':c.person.name, 'collectionId':item.collectionId});
p.create().then( function() {
c.personId = p.id;
if (!c.id || (c.id == 'new')) {
c.id = null;
c.create();
} else {
c.update();
}
});
} else if (!c.id || (c.id == 'new')) {
c.id = null;
c.personId = c.person.id;
c.create();
} else {
c.personId = c.person.id;
c.update();
}
}
});
item.contributions = keepContributions;
}
Item.prototype.play = function () {
var audioFile = new AudioFile(this.audioFiles[0]);
audioFile.itemId = this.id;
audioFile.createListen();
if (!this.loadedIntoPlayer()) {
Player.play(this.audioFiles[0].url, this.getTitle());
} else {
Player.play();
}
};
Item.prototype.pause = function () {
if (this.playing()) {
Player.pause();
}
}
Item.prototype.standardRoles = ['producer', 'interviewer', 'interviewee', 'creator', 'host','guest'];
return Item;
}])
.filter('titleize', function () {
return function (value) {
if (!angular.isString(value)) {
return value;
}
return value.slice(0,1).toUpperCase() + value.slice(1).replace(/([A-Z])/g, ' $1');
}
})
.filter('pluralize', function () {
return function (value) {
if (!angular.isString(value)) {
return value;
}
return value + "s";
}
});
| app/assets/javascripts/items/models.js | angular.module('Directory.items.models', ['RailsModel', 'Directory.audioFiles.models', 'Directory.imageFiles.models'])
.factory('Item', ['Model', '$http', '$q', 'Contribution', 'Person', 'AudioFile', 'Player', 'ImageFile', function (Model, $http, $q, Contribution, Person, AudioFile, Player, ImageFile) {
var attrAccessible = "dateBroadcast dateCreated datePeg description digitalFormat digitalLocation episodeTitle identifier language musicSoundUsed notes physicalFormat physicalLocation rights seriesTitle tags title transcription adoptToCollection tagList text id originalFileUrl".split(' ');
var Item = Model({url:'/api/collections/{{collectionId}}/items/{{id}}', name: 'item', only: attrAccessible});
Item.beforeRequest(function(data, resource) {
var dataList = [];
if (angular.isArray(data)) {
dataList = data;
} else {
dataList = [data];
}
angular.forEach(dataList, function(value, key){
value.tags = [];
value.images = [];
angular.forEach((value.tag_list || []), function (v,k) {
value.tags.push(v['text']);
});
angular.forEach((value.images || []), function (v,k) {
value.images.push(v['imageFiles']);
});
delete value.tag_list;
delete value.images;
if ((!value.id || parseInt(value.id, 10) <= 0) || (value.adoptToCollection == value.collectionId)) {
delete value.adoptToCollection;
}
// console.log("item value:", value);
if (value.language) {
value.language = value.language.id;
}
});
return data;
});
Item.beforeResponse(function(data, resource) {
// console.log("beforeResponse");
data.tagList = [];
data.images = [];
angular.forEach((data.tags || []), function (v,k) {
data.tagList.push({id:v, text:v});
});
angular.forEach((data.images || []), function (v,k) {
data.images.push({id:v, imageFile:v});
});
// console.log(data, data.images);
data.language = {id: data.language, text: Item.languageLookup[data.language]};
if (data.id) {
data.adoptToCollection = data.collectionId;
}
return data;
});
Item._setLanguageLookup = function(langs) {
var lookup = {};
for(var i in langs) {
if (langs[i].id && langs[i].text) {
lookup[langs[i].id] = langs[i].text;
}
if (langs[i].children) {
var children = langs[i].children;
for(var ci in children) {
lookup[children[ci].id] = children[ci].text;
}
}
}
return lookup;
};
Item.languages = [{"text":"Common","children":[{"id":"en-US","text":"English (United States)"},{"id":"ar-EG","text":"Arabic (Egypt)"},{"id":"zh-CN","text":"Chinese (China)"},{"id":"fr-FR","text":"French"},{"id":"de-DE","text":"German"},{"id":"it-IT","text":"Italian"},{"id":"ja-JA","text":"Japanese"},{"id":"ko-KO","text":"Korean"},{"id":"pt-PT","text":"Portuguese"},{"id":"ru-RU","text":"Russian"},{"id":"es-ES","text":"Spanish (Spain)"}]},{"text":"Afrikaans","children":[{"id":"af-NA","text":"Afrikaans (Namibia)"},{"id":"af-ZA","text":"Afrikaans (South Africa)"}]},{"text":"Arabic","children":[{"id":"ar-AE","text":"Arabic (United Arab Emirates)"},{"id":"ar-BH","text":"Arabic (Bahrain)"},{"id":"ar-DJ","text":"Arabic (Djibouti)"},{"id":"ar-DZ","text":"Arabic (Algeria)"},{"id":"ar-EG","text":"Arabic (Egypt)"},{"id":"ar-ER","text":"Arabic (Eritrea)"},{"id":"ar-IL","text":"Arabic (Israel)"},{"id":"ar-IQ","text":"Arabic (Iraq)"},{"id":"ar-JO","text":"Arabic (Jordan)"},{"id":"ar-KM","text":"Arabic (Comoros)"},{"id":"ar-KW","text":"Arabic (Kuwait)"},{"id":"ar-LB","text":"Arabic (Lebanon)"},{"id":"ar-LY","text":"Arabic (Libya)"},{"id":"ar-MA","text":"Arabic (Morocco)"},{"id":"ar-MR","text":"Arabic (Mauritania)"},{"id":"ar-OM","text":"Arabic (Oman)"},{"id":"ar-QA","text":"Arabic (Qatar)"},{"id":"ar-SA","text":"Arabic (Saudi Arabia)"},{"id":"ar-SD","text":"Arabic (Sudan)"},{"id":"ar-SO","text":"Arabic (Somalia)"},{"id":"ar-SY","text":"Arabic (Syrian Arab Republic)"},{"id":"ar-TD","text":"Arabic (Chad)"},{"id":"ar-TN","text":"Arabic (Tunisia)"},{"id":"ar-YE","text":"Arabic (Yemen)"}]},{"id":"bn-BD","text":"Bengali (Bangladesh)"},{"id":"bo","text":"Tibetan"},{"id":"bg-BG","text":"Bulgarian (Bulgaria)"},{"id":"ca-AD","text":"Catalan (Andorra)"},{"id":"cs-CZ","text":"Czech (Czech Republic)"},{"id":"cy","text":"Welsh"},{"id":"da-DK","text":"Danish (Denmark)"},{"text":"German","children":[{"id":"de-AT","text":"German (Austria)"},{"id":"de-BE","text":"German (Belgium)"},{"id":"de-CH","text":"German (Switzerland)"},{"id":"de-DE","text":"German (Germany)"},{"id":"de-LI","text":"German (Liechtenstein)"},{"id":"de-LU","text":"German (Luxembourg)"}]},{"text":"Modern Greek (1453-)","children":[{"id":"el-CY","text":"Modern Greek (1453-) (Cyprus)"},{"id":"el-GR","text":"Modern Greek (1453-) (Greece)"}]},{"text":"English","children":[{"id":"en-AG","text":"English (Antigua and Barbuda)"},{"id":"en-AI","text":"English (Anguilla)"},{"id":"en-AN","text":"English (Netherlands Antilles)"},{"id":"en-AS","text":"English (American Samoa)"},{"id":"en-AU","text":"English (Australia)"},{"id":"en-BB","text":"English (Barbados)"},{"id":"en-BM","text":"English (Bermuda)"},{"id":"en-BS","text":"English (Bahamas)"},{"id":"en-BW","text":"English (Botswana)"},{"id":"en-BZ","text":"English (Belize)"},{"id":"en-CA","text":"English (Canada)"},{"id":"en-CC","text":"English (Cocos (Keeling) Islands)"},{"id":"en-CK","text":"English (Cook Islands)"},{"id":"en-CM","text":"English (Cameroon)"},{"id":"en-CX","text":"English (Christmas Island)"},{"id":"en-DM","text":"English (Dominica)"},{"id":"en-ER","text":"English (Eritrea)"},{"id":"en-FJ","text":"English (Fiji)"},{"id":"en-FK","text":"English (Falkland Islands (Malvinas))"},{"id":"en-FM","text":"English (Micronesia, Federated States Of)"},{"id":"en-GD","text":"English (Grenada)"},{"id":"en-GH","text":"English (Ghana)"},{"id":"en-GI","text":"English (Gibraltar)"},{"id":"en-GM","text":"English (Gambia)"},{"id":"en-GS","text":"English (South Georgia and the South Sandwich Islands)"},{"id":"en-GU","text":"English (Guam)"},{"id":"en-GY","text":"English (Guyana)"},{"id":"en-HK","text":"English (Hong Kong)"},{"id":"en-HM","text":"English (Heard and McDonald Islands)"},{"id":"en-IE","text":"English (Ireland)"},{"id":"en-IN","text":"English (India)"},{"id":"en-IO","text":"English (British Indian Ocean Territory)"},{"id":"en-JM","text":"English (Jamaica)"},{"id":"en-KE","text":"English (Kenya)"},{"id":"en-KI","text":"English (Kiribati)"},{"id":"en-KN","text":"English (Saint Kitts And Nevis)"},{"id":"en-KY","text":"English (Cayman Islands)"},{"id":"en-LC","text":"English (Saint Lucia)"},{"id":"en-LR","text":"English (Liberia)"},{"id":"en-LS","text":"English (Lesotho)"},{"id":"en-MH","text":"English (Marshall Islands)"},{"id":"en-MP","text":"English (Northern Mariana Islands)"},{"id":"en-MS","text":"English (Montserrat)"},{"id":"en-MT","text":"English (Malta)"},{"id":"en-MU","text":"English (Mauritius)"},{"id":"en-MW","text":"English (Malawi)"},{"id":"en-MY","text":"English (Malaysia)"},{"id":"en-NA","text":"English (Namibia)"},{"id":"en-NF","text":"English (Norfolk Island)"},{"id":"en-NG","text":"English (Nigeria)"},{"id":"en-NR","text":"English (Nauru)"},{"id":"en-NU","text":"English (Niue)"},{"id":"en-NZ","text":"English (New Zealand)"},{"id":"en-PG","text":"English (Papua New Guinea)"},{"id":"en-PH","text":"English (Philippines)"},{"id":"en-PK","text":"English (Pakistan)"},{"id":"en-PN","text":"English (Pitcairn)"},{"id":"en-PR","text":"English (Puerto Rico)"},{"id":"en-PW","text":"English (Palau)"},{"id":"en-RW","text":"English (Rwanda)"},{"id":"en-SB","text":"English (Solomon Islands)"},{"id":"en-SC","text":"English (Seychelles)"},{"id":"en-SD","text":"English (Sudan)"},{"id":"en-SG","text":"English (Singapore)"},{"id":"en-SH","text":"English (Saint Helena)"},{"id":"en-SL","text":"English (Sierra Leone)"},{"id":"en-SZ","text":"English (Swaziland)"},{"id":"en-TC","text":"English (Turks and Caicos Islands)"},{"id":"en-TK","text":"English (Tokelau)"},{"id":"en-TO","text":"English (Tonga)"},{"id":"en-TT","text":"English (Trinidad and Tobago)"},{"id":"en-TV","text":"English (Tuvalu)"},{"id":"en-TZ","text":"English (Tanzania, United Republic of)"},{"id":"en-UG","text":"English (Uganda)"},{"id":"en-UM","text":"English (United States Minor Outlying Islands)"},{"id":"en-US","text":"English (United States)"},{"id":"en-VC","text":"English (Saint Vincent And The Grenedines)"},{"id":"en-VG","text":"English (Virgin Islands, British)"},{"id":"en-VI","text":"English (Virgin Islands, U.S.)"},{"id":"en-VU","text":"English (Vanuatu)"},{"id":"en-WS","text":"English (Samoa)"},{"id":"en-ZA","text":"English (South Africa)"},{"id":"en-ZM","text":"English (Zambia)"},{"id":"en-ZW","text":"English (Zimbabwe)"}]},{"id":"et-EE","text":"Estonian (Estonia)"},{"id":"eu","text":"Basque"},{"id":"fa-IR","text":"Persian (Iran, Islamic Republic Of)"},{"id":"fj-FJ","text":"Fijian (Fiji)"},{"id":"fi","text":"Finnish (Finland)"},{"text":"French","children":[{"id":"fr-BE","text":"French (Belgium)"},{"id":"fr-BF","text":"French (Burkina Faso)"},{"id":"fr-BI","text":"French (Burundi)"},{"id":"fr-BJ","text":"French (Benin)"},{"id":"fr-CA","text":"French (Canada)"},{"id":"fr-CD","text":"French (Congo, The Democratic Republic Of The)"},{"id":"fr-CF","text":"French (Central African Republic)"},{"id":"fr-CG","text":"French (Congo)"},{"id":"fr-CH","text":"French (Switzerland)"},{"id":"fr-CI","text":"French (C\u00f4te D'Ivoire)"},{"id":"fr-CM","text":"French (Cameroon)"},{"id":"fr-DJ","text":"French (Djibouti)"},{"id":"fr-EH","text":"French (Western Sahara)"},{"id":"fr-FR","text":"French (France)"},{"id":"fr-GA","text":"French (Gabon)"},{"id":"fr-GF","text":"French (French Guiana)"},{"id":"fr-GN","text":"French (Guinea)"},{"id":"fr-GP","text":"French (Guadeloupe)"},{"id":"fr-GQ","text":"French (Equatorial Guinea)"},{"id":"fr-HT","text":"French (Haiti)"},{"id":"fr-KM","text":"French (Comoros)"},{"id":"fr-LB","text":"French (Lebanon)"},{"id":"fr-LU","text":"French (Luxembourg)"},{"id":"fr-MC","text":"French (Monaco)"},{"id":"fr-MG","text":"French (Madagascar)"},{"id":"fr-ML","text":"French (Mali)"},{"id":"fr-MQ","text":"French (Martinique)"},{"id":"fr-MR","text":"French (Mauritania)"},{"id":"fr-NC","text":"French (New Caledonia)"},{"id":"fr-NE","text":"French (Niger)"},{"id":"fr-PF","text":"French (French Polynesia)"},{"id":"fr-PM","text":"French (Saint Pierre And Miquelon)"},{"id":"fr-RE","text":"French (R\u00e9union)"},{"id":"fr-RW","text":"French (Rwanda)"},{"id":"fr-SC","text":"French (Seychelles)"},{"id":"fr-SN","text":"French (Senegal)"},{"id":"fr-TD","text":"French (Chad)"},{"id":"fr-TG","text":"French (Togo)"},{"id":"fr-TN","text":"French (Tunisia)"},{"id":"fr-VU","text":"French (Vanuatu)"},{"id":"fr-WF","text":"French (Wallis and Futuna)"},{"id":"fr-YT","text":"French (Mayotte)"}]},{"id":"ga-IE","text":"Irish (Ireland)"},{"id":"gu","text":"Gujarati"},{"text":"Hebrew","children":[{"id":"he-IL","text":"Hebrew (Israel)"}]},{"text":"Hindi","children":[{"id":"hi-FJ","text":"Hindi (Fiji)"},{"id":"hi-IN","text":"Hindi (India)"}]},{"text":"Croatian","children":[{"id":"hr-BA","text":"Croatian (Bosnia and Herzegovina)"},{"id":"hr-HR","text":"Croatian (Croatia)"},{"id":"hr-ME","text":"Croatian (Montenegro)"}]},{"id":"hu-HU","text":"Hungarian (Hungary)"},{"text":"Armenian","children":[{"id":"hy-AM","text":"Armenian (Armenia)"},{"id":"hy-AZ","text":"Armenian (Azerbaijan)"},{"id":"hy-CY","text":"Armenian (Cyprus)"}]},{"id":"id-ID","text":"Indonesian (Indonesia)"},{"id":"is-IS","text":"Icelandic (Iceland)"},{"text":"Italian","children":[{"id":"it-CH","text":"Italian (Switzerland)"},{"id":"it-IT","text":"Italian (Italy)"},{"id":"it-SM","text":"Italian (San Marino)"},{"id":"it-VA","text":"Italian (Holy See (Vatican City State))"}]},{"id":"ja-JP","text":"Japanese (Japan)"},{"id":"ka-GE","text":"Georgian (Georgia)"},{"id":"km-KH","text":"Central Khmer (Cambodia)"},{"text":"Korean","children":[{"id":"ko-KP","text":"Korean (Korea, Democratic People's Republic Of)"},{"id":"ko-KR","text":"Korean (Korea, Republic of)"}]},{"id":"la-VA","text":"Latin (Holy See (Vatican City State))"},{"id":"lv-LV","text":"Latvian (Latvia)"},{"id":"lt-LT","text":"Lithuanian (Lithuania)"},{"id":"ml","text":"Malayalam"},{"id":"mr","text":"Marathi"},{"id":"mk-MK","text":"Macedonian (Macedonia, the Former Yugoslav Republic Of)"},{"id":"mt-MT","text":"Maltese (Malta)"},{"id":"mn-MN","text":"Mongolian (Mongolia)"},{"id":"mi","text":"Maori"},{"text":"Malay","children":[{"id":"ms-BN","text":"Malay (Brunei Darussalam)"},{"id":"ms-CX","text":"Malay (Christmas Island)"},{"id":"ms-SG","text":"Malay (Singapore)"}]},{"id":"ne-NP","text":"Nepali (Nepal)"},{"text":"Dutch","children":[{"id":"nl-AN","text":"Dutch (Netherlands Antilles)"},{"id":"nl-AW","text":"Dutch (Aruba)"},{"id":"nl-BE","text":"Dutch (Belgium)"},{"id":"nl-NL","text":"Dutch (Netherlands)"},{"id":"nl-SR","text":"Dutch (Suriname)"}]},{"text":"Norwegian","children":[{"id":"no-NL","text":"Norwegian (Norway)"},{"id":"no-SJ","text":"Norwegian (Svalbard And Jan Mayen)"}]},{"id":"pa","text":"Panjabi"},{"id":"pl-PL","text":"Polish (Poland)"},{"text":"Portuguese","children":[{"id":"pt-AO","text":"Portuguese (Angola)"},{"id":"pt-BR","text":"Portuguese (Brazil)"},{"id":"pt-CV","text":"Portuguese (Cape Verde)"},{"id":"pt-GW","text":"Portuguese (Guinea-Bissau)"},{"id":"pt-MO","text":"Portuguese (Macao)"},{"id":"pt-MZ","text":"Portuguese (Mozambique)"},{"id":"pt-PT","text":"Portuguese (Portugal)"},{"id":"pt-ST","text":"Portuguese (Sao Tome and Principe)"}]},{"id":"qu-BO","text":"Quechua (Bolivia)"},{"text":"Romanian","children":[{"id":"ro-MD","text":"Romanian (Moldova, Republic of)"},{"id":"ro-RO","text":"Romanian (Romania)"}]},{"text":"Russian","children":[{"id":"ru-AM","text":"Russian (Armenia)"},{"id":"ru-BY","text":"Russian (Belarus)"},{"id":"ru-KG","text":"Russian (Kyrgyzstan)"},{"id":"ru-KZ","text":"Russian (Kazakhstan)"},{"id":"ru-RU","text":"Russian (Russian Federation)"},{"id":"ru-TJ","text":"Russian (Tajikistan)"},{"id":"ru-TM","text":"Russian (Turkmenistan)"},{"id":"ru-UZ","text":"Russian (Uzbekistan)"}]},{"text":"Slovak","children":[{"id":"sk-CZ","text":"Slovak (Czech Republic)"},{"id":"sk-SK","text":"Slovak (Slovakia)"}]},{"id":"sl-SI","text":"Slovenian (Slovenia)"},{"text":"Samoan","children":[{"id":"sm-AS","text":"Samoan (American Samoa)"},{"id":"sm-WS","text":"Samoan (Samoa)"}]},{"text":"Spanish","children":[{"id":"es-AR","text":"Spanish (Argentina)"},{"id":"es-BO","text":"Spanish (Bolivia)"},{"id":"es-BZ","text":"Spanish (Belize)"},{"id":"es-CL","text":"Spanish (Chile)"},{"id":"es-CO","text":"Spanish (Colombia)"},{"id":"es-CR","text":"Spanish (Costa Rica)"},{"id":"es-CU","text":"Spanish (Cuba)"},{"id":"es-DO","text":"Spanish (Dominican Republic)"},{"id":"es-EC","text":"Spanish (Ecuador)"},{"id":"es-EH","text":"Spanish (Western Sahara)"},{"id":"es-ES","text":"Spanish (Spain)"},{"id":"es-GQ","text":"Spanish (Equatorial Guinea)"},{"id":"es-GT","text":"Spanish (Guatemala)"},{"id":"es-GU","text":"Spanish (Guam)"},{"id":"es-HN","text":"Spanish (Honduras)"},{"id":"es-MX","text":"Spanish (Mexico)"},{"id":"es-NI","text":"Spanish (Nicaragua)"},{"id":"es-PA","text":"Spanish (Panama)"},{"id":"es-PE","text":"Spanish (Peru)"},{"id":"es-PR","text":"Spanish (Puerto Rico)"},{"id":"es-PY","text":"Spanish (Paraguay)"},{"id":"es-SV","text":"Spanish (El Salvador)"},{"id":"es-UY","text":"Spanish (Uruguay)"},{"id":"es-VE","text":"Spanish (Venezuela, Bolivarian Republic of)"}]},{"text":"Albanian","children":[{"id":"sq-AL","text":"Albanian (Albania)"},{"id":"sq-ME","text":"Albanian (Montenegro)"}]},{"text":"Serbian","children":[{"id":"sr-BA","text":"Serbian (Bosnia and Herzegovina)"},{"id":"sr-ME","text":"Serbian (Montenegro)"},{"id":"sr-RS","text":"Serbian (Serbia)"}]},{"text":"Swahili","children":[{"id":"sw-CD","text":"Swahili (Congo, The Democratic Republic Of The)"},{"id":"sw-KE","text":"Swahili (Kenya)"},{"id":"sw-TZ","text":"Swahili (Tanzania, United Republic of)"},{"id":"sw-UG","text":"Swahili (Uganda)"}]},{"text":"Swedish","children":[{"id":"sv-SE","text":"Swedish (Sweden)"}]},{"text":"Tamil","children":[{"id":"ta-LK","text":"Tamil (Sri Lanka)"},{"id":"ta-SG","text":"Tamil (Singapore)"}]},{"id":"tt","text":"Tatar"},{"id":"te","text":"Telugu"},{"id":"th-TH","text":"Thai (Thailand)"},{"id":"to-TO","text":"Tonga (Tonga Islands) (Tonga)"},{"text":"Turkish","children":[{"id":"tr-CY","text":"Turkish (Cyprus)"},{"id":"tr-TR","text":"Turkish (Turkey)"}]},{"id":"uk-UA","text":"Ukrainian (Ukraine)"},{"text":"Urdu","children":[{"id":"ur-FJ","text":"Urdu (Fiji)"},{"id":"ur-PK","text":"Urdu (Pakistan)"}]},{"text":"Uzbek","children":[{"id":"uz-AF","text":"Uzbek (Afghanistan)"},{"id":"uz-UZ","text":"Uzbek (Uzbekistan)"}]},{"id":"vi-VN","text":"Vietnamese (Viet Nam)"},{"id":"xh-ZA","text":"Xhosa (South Africa)"},{"text":"Chinese","children":[{"id":"zh-CN","text":"Chinese (China)"},{"id":"zh-CX","text":"Chinese (Christmas Island)"},{"id":"zh-HK","text":"Chinese (Hong Kong)"},{"id":"zh-MO","text":"Chinese (Macao)"},{"id":"zh-TW","text":"Chinese (Taiwan, Republic Of China)"}]}];
Item.languageLookup = Item._setLanguageLookup(Item.languages);
Item.prototype.tagList2Tags = function() {
var self = this;
self.tags = [];
angular.forEach((self.tagList || []), function (v,k) {
self.tags.push(v['text']);
});
};
Item.prototype.getTitle = function () {
if (this.title) { return this.title; }
if (this.episodeTitle) { return this.episodeTitle + " : " + this.identifier; }
if (this.seriesTitle) { return this.seriesTitle + " : " + this.identifier; }
}
Item.prototype.getDescription = function () {
if (this.description) { return this.description; }
if (this.notes) { return this.notes; }
}
Item.prototype.getImages = function () {
if (this.imageFiles) {return this.imageFiles}
}
Item.prototype.getThumbClass = function () {
if (this.audioFiles && this.audioFiles.length > 0) {
return "icon-volume-up";
} else {
return "icon-file-alt"
}
}
Item.prototype.link = function () {
return "/collections/" + this.collectionId + "/items/" + this.id;
}
Item.prototype.getDurationString = function () {
var d = new Date(this.duration * 1000);
return d.getUTCHours() + ":" + d.getUTCMinutes() + ":" + d.getUTCSeconds();
}
Item.prototype.adopt = function (collectionId) {
var self = this;
this.adoptToCollection = collectionId;
return this.update().then(function (data) {
self.adoptToCollection = undefined;
return data;
});
}
Item.prototype.contributors = function (role) {
var result = [];
angular.forEach(this.contributions, function (contribution) {
if (contribution.role == role) {
result.push(contribution.person.name);
} else {
}
});
return result;
}
// Item.prototype.image = function (image) {
// var images = [];
// angular.forEach(this.images, function (images) {
// images.push(image);
// })
// }
Item.prototype.addImageFile = function (file, options ){
var options = options || {};
var item = this;
var originalFileUrl = null;
if (angular.isDefined(file.url)) {
originalFileUrl = file.url;
}
var imageFile = new ImageFile({itemId: item.id, originalFileUrl: originalFileUrl});
imageFile.create().then( function() {
imageFile.filename = imageFile.cleanFileName(file.name);
item.imageFiles = item.imageFiles || [];
item.imageFiles.push(imageFile);
options.token = item.token;
imageFile.upload(file, options);
});
return imageFile;
}
Item.prototype.addAudioFile = function (file, options) {
var options = options || {};
var item = this;
var audioFile = new AudioFile({itemId: item.id});
audioFile.create().then( function () {
audioFile.filename = audioFile.cleanFileName(file.name);
item.audioFiles = item.audioFiles || [];
item.audioFiles.push(audioFile);
options.token = item.token;
audioFile.upload(file, options);
});
return audioFile;
}
// update existing audioFiles
Item.prototype.updateAudioFiles = function () {
var item = this;
var keepAudioFiles = [];
angular.forEach(item.audioFiles, function (audioFile, index) {
// console.log('updateAudioFiles', index, audioFile);
var af = new AudioFile(audioFile);
af.itemId = item.id;
// delete c if marked for delete
if (af._delete) {
// console.log('updateAudioFiles delete', audioFile, item);
af.delete();
} else {
keepAudioFiles.push(audioFile);
}
// else if (af.id) {
// af.update();
// }
});
item.audioFiles = keepAudioFiles;
}
Item.prototype.updateImageFiles = function () {
var item = this;
var keepImageFiles = [];
angular.forEach(item.imageFiles, function (imageFile, index) {
// console.log('updateImageFiles', index, imageFile);
var iF = new imageFile(imageFile);
iF.itemId = item.id;
// delete c if marked for delete
if (iF._delete) {
// console.log('updateImageFiles delete', audioFile, item);
iF.delete();
} else {
keepImageFiles.push(imageFile);
}
});
item.imageFiles = keepImageFiles;
}
Item.prototype.playable = function () {
return this.audioFiles && this.audioFiles.length > 0;
}
Item.prototype.entityShortList = function () {
this._entityShortList = this._entityShortList || [];
this._entityShortList.length = 0;
if (this.tags && this.tags.length >= 5) {
for (var i=0; i<5; i++) {
this._entityShortList.push(this.tags[i]);
}
} else {
angular.forEach(this.tags, function (tag) {
this._entityShortList.push(tag);
}, this);
var i = 0;
if (this.entities) {
while (i < this.entities.length && this._entityShortList.length <= 5) {
this._entityShortList.push(this.entities[i].name);
i++;
}
}
}
return this._entityShortList;
}
Item.prototype.paused = function () {
return this.playable() && !this.playing();
}
Item.prototype.loadedIntoPlayer = function () {
var me = false;
if (Player.nowPlayingUrl() && this.playable()) {
var nowPlaying = Player.nowPlayingUrl().toString().split('?')[0];
angular.forEach(this.audioFiles, function (file) {
if (file.url && (nowPlaying == file.url.split('?')[0])) {
me = true;
}
});
} else {
return false;
}
return me;
}
Item.prototype.playing = function() {
return this.loadedIntoPlayer() && !Player.paused();
}
// update existing contributions
Item.prototype.updateContributions = function () {
var item = this;
var keepContributions = [];
angular.forEach(item.contributions, function (contribution, index) {
var c = new Contribution(contribution);
c.itemId = item.id;
// delete c if marked for delete
if (c._delete) {
c.delete();
// item.contributions.splice(index, 1);
} else {
keepContributions.push(c);
if (!c.person.id || (c.person.id == 'new')) {
var p = new Person({'name':c.person.name, 'collectionId':item.collectionId});
p.create().then( function() {
c.personId = p.id;
if (!c.id || (c.id == 'new')) {
c.id = null;
c.create();
} else {
c.update();
}
});
} else if (!c.id || (c.id == 'new')) {
c.id = null;
c.personId = c.person.id;
c.create();
} else {
c.personId = c.person.id;
c.update();
}
}
});
item.contributions = keepContributions;
}
Item.prototype.play = function () {
var audioFile = new AudioFile(this.audioFiles[0]);
audioFile.itemId = this.id;
audioFile.createListen();
if (!this.loadedIntoPlayer()) {
Player.play(this.audioFiles[0].url, this.getTitle());
} else {
Player.play();
}
};
Item.prototype.pause = function () {
if (this.playing()) {
Player.pause();
}
}
Item.prototype.standardRoles = ['producer', 'interviewer', 'interviewee', 'creator', 'host','guest'];
return Item;
}])
.filter('titleize', function () {
return function (value) {
if (!angular.isString(value)) {
return value;
}
return value.slice(0,1).toUpperCase() + value.slice(1).replace(/([A-Z])/g, ' $1');
}
})
.filter('pluralize', function () {
return function (value) {
if (!angular.isString(value)) {
return value;
}
return value + "s";
}
});
| Added the container properties to the new image object
| app/assets/javascripts/items/models.js | Added the container properties to the new image object | <ide><path>pp/assets/javascripts/items/models.js
<ide>
<ide> Item.beforeResponse(function(data, resource) {
<ide> // console.log("beforeResponse");
<add> console.log(data);
<ide> data.tagList = [];
<ide> data.images = [];
<ide> angular.forEach((data.tags || []), function (v,k) {
<ide> if (angular.isDefined(file.url)) {
<ide> originalFileUrl = file.url;
<ide> }
<del> var imageFile = new ImageFile({itemId: item.id, originalFileUrl: originalFileUrl});
<add> var imageFile = new ImageFile({container: "items", containerId: item.id, originalFileUrl: originalFileUrl});
<ide>
<ide> imageFile.create().then( function() {
<ide> imageFile.filename = imageFile.cleanFileName(file.name); |
|
Java | apache-2.0 | 41f104717ecb97409832180c94a720e6c7601985 | 0 | sreedishps/pintail,rajubairishetti/pintail,sreedishps/pintail,InMobi/pintail,rajubairishetti/pintail,InMobi/pintail | package com.inmobi.databus.readers;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import com.inmobi.databus.files.FileMap;
import com.inmobi.databus.files.HadoopStreamFile;
import com.inmobi.databus.partition.PartitionCheckpoint;
import com.inmobi.databus.partition.PartitionCheckpointList;
import com.inmobi.databus.partition.PartitionId;
import com.inmobi.messaging.Message;
import com.inmobi.messaging.metrics.PartitionReaderStatsExposer;
public class DatabusStreamWaitingReader
extends DatabusStreamReader<HadoopStreamFile> {
private static final Log LOG = LogFactory.getLog(
DatabusStreamWaitingReader.class);
private int currentMin;
private final Set<Integer> partitionMinList;
private PartitionCheckpointList partitionCheckpointList;
private boolean movedToNext;
private int prevMin;
private long numOfLinesReadInMinute;
private Map<Integer, Date> checkpointTimeStampMap;
private Map<Integer, PartitionCheckpoint> pChkpoints;
public DatabusStreamWaitingReader(PartitionId partitionId, FileSystem fs,
Path streamDir, String inputFormatClass, Configuration conf,
long waitTimeForFileCreate, PartitionReaderStatsExposer metrics,
boolean noNewFiles, Set<Integer> partitionMinList,
PartitionCheckpointList partitionCheckpointList, Date stopTime)
throws IOException {
super(partitionId, fs, streamDir, inputFormatClass, conf,
waitTimeForFileCreate, metrics, noNewFiles, stopTime);
this.partitionCheckpointList = partitionCheckpointList;
this.partitionMinList = partitionMinList;
this.stopTime = stopTime;
currentMin = -1;
numOfLinesReadInMinute = 0;
this.checkpointTimeStampMap = new HashMap<Integer, Date>();
if (partitionCheckpointList != null) {
pChkpoints = partitionCheckpointList.getCheckpoints();
prepareTimeStampsOfCheckpoints();
}
}
public void prepareTimeStampsOfCheckpoints() {
PartitionCheckpoint partitionCheckpoint = null;
for (Integer min : partitionMinList) {
partitionCheckpoint = pChkpoints.get(min);
if (partitionCheckpoint != null) {
Date checkpointedTimestamp = getDateFromCheckpointPath(
partitionCheckpoint.getFileName());
checkpointTimeStampMap.put(min, checkpointedTimestamp);
} else {
checkpointTimeStampMap.put(min, null);
}
}
}
/**
* This method is used to check whether the given minute directory is
* completely read or not. It takes the current time stamp and the minute
* on which the reader is currently working. It retrieves the partition checkpoint
* for that minute if it contains. It compares the current time stamp with
* the checkpointed time stamp. If current time stamp is before the
* checkpointed time stamp then that minute directory for the current hour is
* completely read. If both the time stamps are same then it checks line number.
* If line num is -1 means all the files in that minute dir are already read.
*/
public boolean isRead(Date currentTimeStamp, int minute) {
Date checkpointedTimestamp = checkpointTimeStampMap.get(
Integer.valueOf(minute));
if (checkpointedTimestamp == null) {
return false;
}
if (currentTimeStamp.before(checkpointedTimestamp)) {
return true;
} else if (currentTimeStamp.equals(checkpointedTimestamp)) {
PartitionCheckpoint partitionCheckpoint = pChkpoints.get(
Integer.valueOf(minute));
if (partitionCheckpoint != null && partitionCheckpoint.getLineNum() == -1)
{
return true;
}
}
return false;
}
/**
* It reads from the next checkpoint. It retrieves the first file from the filemap.
* Get the minute id from the file and see the checkpoint value. If the
* checkpointed file is not same as current file then it sets the iterator to
* the checkpointed file if the checkpointed file exists.
*/
public boolean initFromNextCheckPoint() throws IOException {
initCurrentFile();
currentFile = getFirstFileInStream();
Date date = DatabusStreamWaitingReader.getDateFromStreamDir(streamDir,
currentFile.getPath().getParent());
Calendar current = Calendar.getInstance();
current.setTime(date);
int currentMinute =current.get(Calendar.MINUTE);
PartitionCheckpoint partitioncheckpoint = partitionCheckpointList.
getCheckpoints().get(currentMinute);
if (partitioncheckpoint != null) {
Path checkpointedFileName =new Path(streamDir,
partitioncheckpoint.getFileName());
if (!(currentFile.getPath()).equals(checkpointedFileName)) {
if(fs.exists(checkpointedFileName)) {
currentFile = fs.getFileStatus(checkpointedFileName);
currentLineNum = partitioncheckpoint.getLineNum();
} else {
currentLineNum = 0;
}
} else {
currentLineNum = partitioncheckpoint.getLineNum();
}
}
if (currentFile != null) {
LOG.debug("CurrentFile:" + getCurrentFile() + " currentLineNum:" +
currentLineNum);
setIterator();
}
return currentFile != null;
}
@Override
protected void buildListing(FileMap<HadoopStreamFile> fmap,
PathFilter pathFilter) throws IOException {
Calendar current = Calendar.getInstance();
Date now = current.getTime();
current.setTime(buildTimestamp);
boolean breakListing = false;
while (current.getTime().before(now)) {
Path hhDir = getHourDirPath(streamDir, current.getTime());
int hour = current.get(Calendar.HOUR_OF_DAY);
if (fs.exists(hhDir)) {
while (current.getTime().before(now) &&
hour == current.get(Calendar.HOUR_OF_DAY)) {
// stop the file listing if stop date is beyond current time.
if (checkAndSetstopTimeReached(current)) {
breakListing = true;
break;
}
int min = current.get(Calendar.MINUTE);
Date currenTimestamp = current.getTime();
// Move the current minute to next minute
current.add(Calendar.MINUTE, 1);
if (partitionMinList.contains(Integer.valueOf(min))
&& !isRead(currenTimestamp, min)) {
Path dir = getMinuteDirPath(streamDir, currenTimestamp);
if (fs.exists(dir)) {
Path nextMinDir = getMinuteDirPath(streamDir, current.getTime());
if (fs.exists(nextMinDir)) {
doRecursiveListing(dir, pathFilter, fmap);
} else {
LOG.info("Reached end of file listing. Not looking at the last" +
" minute directory:" + dir);
breakListing = true;
break;
}
}
}
}
} else {
// go to next hour
LOG.info("Hour directory " + hhDir + " does not exist");
current.add(Calendar.HOUR_OF_DAY, 1);
current.set(Calendar.MINUTE, 0);
}
if (breakListing) {
break;
}
}
if (getFirstFileInStream() != null && (currentMin == -1)) {
FileStatus firstFileInStream = getFirstFileInStream();
currentMin = getMinuteFromFile(firstFileInStream);
}
}
/*
* check whether reached stopTime and stop the File listing if it reached stopTime
*/
private boolean checkAndSetstopTimeReached(Calendar current) {
if (stopTime != null && stopTime.before(current.getTime())) {
LOG.info("Reached stopTime. Not listing from after" +
" the stop date ");
stopListing();
return true;
}
return false;
}
/**
* This method does the required setup before moving to next file. First it
* checks whether the both current file and next file belongs to same minute
* or different minutes. If files exists on across minutes then it has to
* check the next file is same as checkpointed file. If not same and checkpointed
* file exists then sets the iterator to the checkpointed file.
* @return false if it reads from the checkpointed file.
*/
@Override
public boolean prepareMoveToNext(FileStatus currentFile, FileStatus nextFile)
throws IOException {
Date currentFileTimeStamp = getDateFromStreamDir(streamDir,
currentFile.getPath().getParent());
Calendar now = Calendar.getInstance();
now.setTime(currentFileTimeStamp);
currentMin = now.get(Calendar.MINUTE);
Date nextFileTimeStamp = getDateFromStreamDir(streamDir,
nextFile.getPath().getParent());
now.setTime(nextFileTimeStamp);
numOfLinesReadInMinute += getCurrentLineNum();
boolean readFromCheckpoint = false;
FileStatus fileToRead = nextFile;
if (currentMin != now.get(Calendar.MINUTE)) {
if (numOfLinesReadInMinute > 0) {
//We are moving to next file, set the flags so that Message checkpoints
//can be populated.
movedToNext = true;
prevMin = currentMin;
numOfLinesReadInMinute = 0;
}
currentMin = now.get(Calendar.MINUTE);
PartitionCheckpoint partitionCheckpoint = partitionCheckpointList.
getCheckpoints().get(currentMin);
if (partitionCheckpoint != null && partitionCheckpoint.getLineNum() != -1)
{
Path checkPointedFileName = new Path(streamDir,
partitionCheckpoint.getFileName());
//set iterator to checkpoointed file if there is a checkpoint
if(!fileToRead.getPath().equals(checkPointedFileName)) {
if (fs.exists(checkPointedFileName)) {
fileToRead = fs.getFileStatus(checkPointedFileName);
currentLineNum = partitionCheckpoint.getLineNum();
} else {
currentLineNum = 0;
}
} else {
currentLineNum = partitionCheckpoint.getLineNum();
}
readFromCheckpoint = true;
}
updatePartitionCheckpointList(prevMin);
}
this.currentFile = fileToRead;
setIterator();
return !readFromCheckpoint;
}
private void updatePartitionCheckpointList(int prevMin) {
Map<Integer, PartitionCheckpoint> pckList = partitionCheckpointList.
getCheckpoints();
pckList.remove(prevMin);
partitionCheckpointList.setCheckpoint(pckList);
}
@Override
protected HadoopStreamFile getStreamFile(Date timestamp) {
return new HadoopStreamFile(getMinuteDirPath(streamDir, timestamp),
null, null);
}
protected HadoopStreamFile getStreamFile(FileStatus status) {
return getHadoopStreamFile(status);
}
protected void startFromNextHigher(FileStatus file)
throws IOException, InterruptedException {
if (!setNextHigherAndOpen(file)) {
waitForNextFileCreation(file);
}
}
private void waitForNextFileCreation(FileStatus file)
throws IOException, InterruptedException {
while (!closed && !setNextHigherAndOpen(file) && !hasReadFully()) {
LOG.info("Waiting for next file creation");
waitForFileCreate();
build();
}
}
@Override
public Message readLine() throws IOException, InterruptedException {
Message line = readNextLine();
while (line == null) { // reached end of file
LOG.info("Read " + getCurrentFile() + " with lines:" + currentLineNum);
if (closed) {
LOG.info("Stream closed");
break;
}
if (!nextFile()) { // reached end of file list
LOG.info("could not find next file. Rebuilding");
build(getDateFromStreamDir(streamDir,
getCurrentFile()));
if (!nextFile()) { // reached end of stream
// stop reading if read till stopTime
if (hasReadFully()) {
LOG.info("read all files till stop date");
break;
}
LOG.info("Could not find next file");
startFromNextHigher(currentFile);
LOG.info("Reading from next higher file "+ getCurrentFile());
} else {
LOG.info("Reading from " + getCurrentFile() + " after rebuild");
}
} else {
// read line from next file
LOG.info("Reading from next file " + getCurrentFile());
}
line = readNextLine();
}
return line;
}
@Override
protected FileMap<HadoopStreamFile> createFileMap() throws IOException {
return new FileMap<HadoopStreamFile>() {
@Override
protected void buildList() throws IOException {
buildListing(this, pathFilter);
}
@Override
protected TreeMap<HadoopStreamFile, FileStatus> createFilesMap() {
return new TreeMap<HadoopStreamFile, FileStatus>();
}
@Override
protected HadoopStreamFile getStreamFile(String fileName) {
throw new RuntimeException("Not implemented");
}
@Override
protected HadoopStreamFile getStreamFile(FileStatus file) {
return HadoopStreamFile.create(file);
}
@Override
protected PathFilter createPathFilter() {
return new PathFilter() {
@Override
public boolean accept(Path path) {
if (path.getName().startsWith("_")) {
return false;
}
return true;
}
};
}
};
}
public static Date getBuildTimestamp(Path streamDir,
PartitionCheckpoint partitionCheckpoint) {
try {
return getDateFromCheckpointPath(partitionCheckpoint.getFileName());
} catch (Exception e) {
throw new IllegalArgumentException("Invalid checkpoint:" +
partitionCheckpoint.getStreamFile(), e);
}
}
public static HadoopStreamFile getHadoopStreamFile(FileStatus status) {
return HadoopStreamFile.create(status);
}
public void resetMoveToNextFlags() {
movedToNext = false;
prevMin = -1;
}
public boolean isMovedToNext() {
return movedToNext;
}
public int getPrevMin() {
return this.prevMin;
}
public int getCurrentMin() {
return this.currentMin;
}
/**
* @returns Zero if checkpoint is not present for that minute or
* checkpoint file and current file were not same.
* Line number from checkpoint
*/
@Override
protected long getLineNumberForFirstFile(FileStatus firstFile) {
int minute = getMinuteFromFile(firstFile);
PartitionCheckpoint partitionChkPoint = pChkpoints.get(
Integer.valueOf(minute));
if (partitionChkPoint != null) {
Path checkPointedFileName = new Path(streamDir, partitionChkPoint.
getFileName());
// check whether current file and checkpoint file are same
if (checkPointedFileName.equals(firstFile.getPath())) {
return partitionChkPoint.getLineNum();
}
}
return 0;
}
private int getMinuteFromFile(FileStatus firstFile) {
Date currentTimeStamp = getDateFromStreamDir(streamDir, firstFile.
getPath().getParent());
Calendar cal = Calendar.getInstance();
cal.setTime(currentTimeStamp);
return cal.get(Calendar.MINUTE);
}
} | messaging-client-databus/src/main/java/com/inmobi/databus/readers/DatabusStreamWaitingReader.java | package com.inmobi.databus.readers;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import com.inmobi.databus.files.FileMap;
import com.inmobi.databus.files.HadoopStreamFile;
import com.inmobi.databus.partition.PartitionCheckpoint;
import com.inmobi.databus.partition.PartitionCheckpointList;
import com.inmobi.databus.partition.PartitionId;
import com.inmobi.messaging.Message;
import com.inmobi.messaging.metrics.PartitionReaderStatsExposer;
public class DatabusStreamWaitingReader
extends DatabusStreamReader<HadoopStreamFile> {
private static final Log LOG = LogFactory.getLog(
DatabusStreamWaitingReader.class);
private int currentMin;
private final Set<Integer> partitionMinList;
private PartitionCheckpointList partitionCheckpointList;
private boolean movedToNext;
private int prevMin;
private Map<Integer, Date> checkpointTimeStampMap;
private Map<Integer, PartitionCheckpoint> pChkpoints;
public DatabusStreamWaitingReader(PartitionId partitionId, FileSystem fs,
Path streamDir, String inputFormatClass, Configuration conf,
long waitTimeForFileCreate, PartitionReaderStatsExposer metrics,
boolean noNewFiles, Set<Integer> partitionMinList,
PartitionCheckpointList partitionCheckpointList, Date stopTime)
throws IOException {
super(partitionId, fs, streamDir, inputFormatClass, conf,
waitTimeForFileCreate, metrics, noNewFiles, stopTime);
this.partitionCheckpointList = partitionCheckpointList;
this.partitionMinList = partitionMinList;
this.stopTime = stopTime;
currentMin = -1;
this.checkpointTimeStampMap = new HashMap<Integer, Date>();
if (partitionCheckpointList != null) {
pChkpoints = partitionCheckpointList.getCheckpoints();
prepareTimeStampsOfCheckpoints();
}
}
public void prepareTimeStampsOfCheckpoints() {
PartitionCheckpoint partitionCheckpoint = null;
for (Integer min : partitionMinList) {
partitionCheckpoint = pChkpoints.get(min);
if (partitionCheckpoint != null) {
Date checkpointedTimestamp = getDateFromCheckpointPath(
partitionCheckpoint.getFileName());
checkpointTimeStampMap.put(min, checkpointedTimestamp);
} else {
checkpointTimeStampMap.put(min, null);
}
}
}
/**
* This method is used to check whether the given minute directory is
* completely read or not. It takes the current time stamp and the minute
* on which the reader is currently working. It retrieves the partition checkpoint
* for that minute if it contains. It compares the current time stamp with
* the checkpointed time stamp. If current time stamp is before the
* checkpointed time stamp then that minute directory for the current hour is
* completely read. If both the time stamps are same then it checks line number.
* If line num is -1 means all the files in that minute dir are already read.
*/
public boolean isRead(Date currentTimeStamp, int minute) {
Date checkpointedTimestamp = checkpointTimeStampMap.get(
Integer.valueOf(minute));
if (checkpointedTimestamp == null) {
return false;
}
if (currentTimeStamp.before(checkpointedTimestamp)) {
return true;
} else if (currentTimeStamp.equals(checkpointedTimestamp)) {
PartitionCheckpoint partitionCheckpoint = pChkpoints.get(
Integer.valueOf(minute));
if (partitionCheckpoint != null && partitionCheckpoint.getLineNum() == -1)
{
return true;
}
}
return false;
}
/**
* It reads from the next checkpoint. It retrieves the first file from the filemap.
* Get the minute id from the file and see the checkpoint value. If the
* checkpointed file is not same as current file then it sets the iterator to
* the checkpointed file if the checkpointed file exists.
*/
public boolean initFromNextCheckPoint() throws IOException {
initCurrentFile();
currentFile = getFirstFileInStream();
Date date = DatabusStreamWaitingReader.getDateFromStreamDir(streamDir,
currentFile.getPath().getParent());
Calendar current = Calendar.getInstance();
current.setTime(date);
int currentMinute =current.get(Calendar.MINUTE);
PartitionCheckpoint partitioncheckpoint = partitionCheckpointList.
getCheckpoints().get(currentMinute);
if (partitioncheckpoint != null) {
Path checkpointedFileName =new Path(streamDir,
partitioncheckpoint.getFileName());
if (!(currentFile.getPath()).equals(checkpointedFileName)) {
if(fs.exists(checkpointedFileName)) {
currentFile = fs.getFileStatus(checkpointedFileName);
currentLineNum = partitioncheckpoint.getLineNum();
} else {
currentLineNum = 0;
}
} else {
currentLineNum = partitioncheckpoint.getLineNum();
}
}
if (currentFile != null) {
LOG.debug("CurrentFile:" + getCurrentFile() + " currentLineNum:" +
currentLineNum);
setIterator();
}
return currentFile != null;
}
@Override
protected void buildListing(FileMap<HadoopStreamFile> fmap,
PathFilter pathFilter) throws IOException {
Calendar current = Calendar.getInstance();
Date now = current.getTime();
current.setTime(buildTimestamp);
boolean breakListing = false;
while (current.getTime().before(now)) {
Path hhDir = getHourDirPath(streamDir, current.getTime());
int hour = current.get(Calendar.HOUR_OF_DAY);
if (fs.exists(hhDir)) {
while (current.getTime().before(now) &&
hour == current.get(Calendar.HOUR_OF_DAY)) {
// stop the file listing if stop date is beyond current time.
if (checkAndSetstopTimeReached(current)) {
breakListing = true;
break;
}
int min = current.get(Calendar.MINUTE);
Date currenTimestamp = current.getTime();
// Move the current minute to next minute
current.add(Calendar.MINUTE, 1);
if (partitionMinList.contains(Integer.valueOf(min))
&& !isRead(currenTimestamp, min)) {
Path dir = getMinuteDirPath(streamDir, currenTimestamp);
if (fs.exists(dir)) {
Path nextMinDir = getMinuteDirPath(streamDir, current.getTime());
if (fs.exists(nextMinDir)) {
doRecursiveListing(dir, pathFilter, fmap);
} else {
LOG.info("Reached end of file listing. Not looking at the last" +
" minute directory:" + dir);
breakListing = true;
break;
}
}
}
}
} else {
// go to next hour
LOG.info("Hour directory " + hhDir + " does not exist");
current.add(Calendar.HOUR_OF_DAY, 1);
current.set(Calendar.MINUTE, 0);
}
if (breakListing) {
break;
}
}
if (getFirstFileInStream() != null && (currentMin == -1)) {
FileStatus firstFileInStream = getFirstFileInStream();
currentMin = getMinuteFromFile(firstFileInStream);
}
}
/*
* check whether reached stopTime and stop the File listing if it reached stopTime
*/
private boolean checkAndSetstopTimeReached(Calendar current) {
if (stopTime != null && stopTime.before(current.getTime())) {
LOG.info("Reached stopTime. Not listing from after" +
" the stop date ");
stopListing();
return true;
}
return false;
}
/**
* This method does the required setup before moving to next file. First it
* checks whether the both current file and next file belongs to same minute
* or different minutes. If files exists on across minutes then it has to
* check the next file is same as checkpointed file. If not same and checkpointed
* file exists then sets the iterator to the checkpointed file.
* @return false if it reads from the checkpointed file.
*/
@Override
public boolean prepareMoveToNext(FileStatus currentFile, FileStatus nextFile)
throws IOException {
Date currentFileTimeStamp = getDateFromStreamDir(streamDir,
currentFile.getPath().getParent());
Calendar now = Calendar.getInstance();
now.setTime(currentFileTimeStamp);
currentMin = now.get(Calendar.MINUTE);
Date nextFileTimeStamp = getDateFromStreamDir(streamDir,
nextFile.getPath().getParent());
now.setTime(nextFileTimeStamp);
boolean readFromCheckpoint = false;
FileStatus fileToRead = nextFile;
if (currentMin != now.get(Calendar.MINUTE)) {
//We are moving to next file, set the flags so that Message checkpoints
//can be populated.
movedToNext = true;
prevMin = currentMin;
currentMin = now.get(Calendar.MINUTE);
PartitionCheckpoint partitionCheckpoint = partitionCheckpointList.
getCheckpoints().get(currentMin);
if (partitionCheckpoint != null && partitionCheckpoint.getLineNum() != -1)
{
Path checkPointedFileName = new Path(streamDir,
partitionCheckpoint.getFileName());
//set iterator to checkpoointed file if there is a checkpoint
if(!fileToRead.getPath().equals(checkPointedFileName)) {
if (fs.exists(checkPointedFileName)) {
fileToRead = fs.getFileStatus(checkPointedFileName);
currentLineNum = partitionCheckpoint.getLineNum();
} else {
currentLineNum = 0;
}
} else {
currentLineNum = partitionCheckpoint.getLineNum();
}
readFromCheckpoint = true;
}
updatePartitionCheckpointList(prevMin);
}
this.currentFile = fileToRead;
setIterator();
return !readFromCheckpoint;
}
private void updatePartitionCheckpointList(int prevMin) {
Map<Integer, PartitionCheckpoint> pckList = partitionCheckpointList.
getCheckpoints();
pckList.remove(prevMin);
partitionCheckpointList.setCheckpoint(pckList);
}
@Override
protected HadoopStreamFile getStreamFile(Date timestamp) {
return new HadoopStreamFile(getMinuteDirPath(streamDir, timestamp),
null, null);
}
protected HadoopStreamFile getStreamFile(FileStatus status) {
return getHadoopStreamFile(status);
}
protected void startFromNextHigher(FileStatus file)
throws IOException, InterruptedException {
if (!setNextHigherAndOpen(file)) {
waitForNextFileCreation(file);
}
}
private void waitForNextFileCreation(FileStatus file)
throws IOException, InterruptedException {
while (!closed && !setNextHigherAndOpen(file) && !hasReadFully()) {
LOG.info("Waiting for next file creation");
waitForFileCreate();
build();
}
}
@Override
public Message readLine() throws IOException, InterruptedException {
Message line = readNextLine();
while (line == null) { // reached end of file
LOG.info("Read " + getCurrentFile() + " with lines:" + currentLineNum);
if (closed) {
LOG.info("Stream closed");
break;
}
if (!nextFile()) { // reached end of file list
LOG.info("could not find next file. Rebuilding");
build(getDateFromStreamDir(streamDir,
getCurrentFile()));
if (!nextFile()) { // reached end of stream
// stop reading if read till stopTime
if (hasReadFully()) {
LOG.info("read all files till stop date");
break;
}
LOG.info("Could not find next file");
startFromNextHigher(currentFile);
LOG.info("Reading from next higher file "+ getCurrentFile());
} else {
LOG.info("Reading from " + getCurrentFile() + " after rebuild");
}
} else {
// read line from next file
LOG.info("Reading from next file " + getCurrentFile());
}
line = readNextLine();
}
return line;
}
@Override
protected FileMap<HadoopStreamFile> createFileMap() throws IOException {
return new FileMap<HadoopStreamFile>() {
@Override
protected void buildList() throws IOException {
buildListing(this, pathFilter);
}
@Override
protected TreeMap<HadoopStreamFile, FileStatus> createFilesMap() {
return new TreeMap<HadoopStreamFile, FileStatus>();
}
@Override
protected HadoopStreamFile getStreamFile(String fileName) {
throw new RuntimeException("Not implemented");
}
@Override
protected HadoopStreamFile getStreamFile(FileStatus file) {
return HadoopStreamFile.create(file);
}
@Override
protected PathFilter createPathFilter() {
return new PathFilter() {
@Override
public boolean accept(Path path) {
if (path.getName().startsWith("_")) {
return false;
}
return true;
}
};
}
};
}
public static Date getBuildTimestamp(Path streamDir,
PartitionCheckpoint partitionCheckpoint) {
try {
return getDateFromCheckpointPath(partitionCheckpoint.getFileName());
} catch (Exception e) {
throw new IllegalArgumentException("Invalid checkpoint:" +
partitionCheckpoint.getStreamFile(), e);
}
}
public static HadoopStreamFile getHadoopStreamFile(FileStatus status) {
return HadoopStreamFile.create(status);
}
public void resetMoveToNextFlags() {
movedToNext = false;
prevMin = -1;
}
public boolean isMovedToNext() {
return movedToNext;
}
public int getPrevMin() {
return this.prevMin;
}
public int getCurrentMin() {
return this.currentMin;
}
/**
* @returns Zero if checkpoint is not present for that minute or
* checkpoint file and current file were not same.
* Line number from checkpoint
*/
@Override
protected long getLineNumberForFirstFile(FileStatus firstFile) {
int minute = getMinuteFromFile(firstFile);
PartitionCheckpoint partitionChkPoint = pChkpoints.get(
Integer.valueOf(minute));
if (partitionChkPoint != null) {
Path checkPointedFileName = new Path(streamDir, partitionChkPoint.
getFileName());
// check whether current file and checkpoint file are same
if (checkPointedFileName.equals(firstFile.getPath())) {
return partitionChkPoint.getLineNum();
}
}
return 0;
}
private int getMinuteFromFile(FileStatus firstFile) {
Date currentTimeStamp = getDateFromStreamDir(streamDir, firstFile.
getPath().getParent());
Calendar cal = Calendar.getInstance();
cal.setTime(currentTimeStamp);
return cal.get(Calendar.MINUTE);
}
} | skip the setting of checkpoint for minute which has all empty files
| messaging-client-databus/src/main/java/com/inmobi/databus/readers/DatabusStreamWaitingReader.java | skip the setting of checkpoint for minute which has all empty files | <ide><path>essaging-client-databus/src/main/java/com/inmobi/databus/readers/DatabusStreamWaitingReader.java
<ide> private PartitionCheckpointList partitionCheckpointList;
<ide> private boolean movedToNext;
<ide> private int prevMin;
<add> private long numOfLinesReadInMinute;
<ide> private Map<Integer, Date> checkpointTimeStampMap;
<ide> private Map<Integer, PartitionCheckpoint> pChkpoints;
<ide>
<ide> this.partitionMinList = partitionMinList;
<ide> this.stopTime = stopTime;
<ide> currentMin = -1;
<add> numOfLinesReadInMinute = 0;
<ide> this.checkpointTimeStampMap = new HashMap<Integer, Date>();
<ide> if (partitionCheckpointList != null) {
<ide> pChkpoints = partitionCheckpointList.getCheckpoints();
<ide> nextFile.getPath().getParent());
<ide> now.setTime(nextFileTimeStamp);
<ide>
<add> numOfLinesReadInMinute += getCurrentLineNum();
<ide> boolean readFromCheckpoint = false;
<ide> FileStatus fileToRead = nextFile;
<ide> if (currentMin != now.get(Calendar.MINUTE)) {
<del> //We are moving to next file, set the flags so that Message checkpoints
<del> //can be populated.
<del> movedToNext = true;
<del> prevMin = currentMin;
<add> if (numOfLinesReadInMinute > 0) {
<add> //We are moving to next file, set the flags so that Message checkpoints
<add> //can be populated.
<add> movedToNext = true;
<add> prevMin = currentMin;
<add> numOfLinesReadInMinute = 0;
<add> }
<ide> currentMin = now.get(Calendar.MINUTE);
<ide> PartitionCheckpoint partitionCheckpoint = partitionCheckpointList.
<ide> getCheckpoints().get(currentMin); |
|
Java | mit | d980d5d4af20dc32ec16e44cb99284a5969d7bcf | 0 | maikeffi/hudson,verbitan/jenkins,tangkun75/jenkins,maikeffi/hudson,evernat/jenkins,mrooney/jenkins,jzjzjzj/jenkins,iterate/coding-dojo,chbiel/jenkins,Vlatombe/jenkins,hplatou/jenkins,duzifang/my-jenkins,recena/jenkins,khmarbaise/jenkins,rlugojr/jenkins,paulwellnerbou/jenkins,batmat/jenkins,hashar/jenkins,mpeltonen/jenkins,mpeltonen/jenkins,vjuranek/jenkins,gusreiber/jenkins,aduprat/jenkins,tangkun75/jenkins,gitaccountforprashant/gittest,Vlatombe/jenkins,vijayto/jenkins,aheritier/jenkins,aldaris/jenkins,andresrc/jenkins,FTG-003/jenkins,noikiy/jenkins,jcarrothers-sap/jenkins,bkmeneguello/jenkins,CodeShane/jenkins,lvotypko/jenkins3,albers/jenkins,Ykus/jenkins,Jimilian/jenkins,thomassuckow/jenkins,csimons/jenkins,alvarolobato/jenkins,ydubreuil/jenkins,samatdav/jenkins,jcarrothers-sap/jenkins,kohsuke/hudson,aldaris/jenkins,NehemiahMi/jenkins,ydubreuil/jenkins,jcsirot/jenkins,csimons/jenkins,elkingtonmcb/jenkins,seanlin816/jenkins,kohsuke/hudson,petermarcoen/jenkins,my7seven/jenkins,aduprat/jenkins,paulmillar/jenkins,yonglehou/jenkins,v1v/jenkins,nandan4/Jenkins,verbitan/jenkins,soenter/jenkins,iqstack/jenkins,msrb/jenkins,keyurpatankar/hudson,liorhson/jenkins,samatdav/jenkins,lvotypko/jenkins,brunocvcunha/jenkins,batmat/jenkins,protazy/jenkins,MarkEWaite/jenkins,6WIND/jenkins,DoctorQ/jenkins,v1v/jenkins,guoxu0514/jenkins,SenolOzer/jenkins,wuwen5/jenkins,MichaelPranovich/jenkins_sc,hashar/jenkins,iqstack/jenkins,jglick/jenkins,everyonce/jenkins,daspilker/jenkins,pselle/jenkins,ikedam/jenkins,yonglehou/jenkins,paulmillar/jenkins,mattclark/jenkins,SebastienGllmt/jenkins,MichaelPranovich/jenkins_sc,bpzhang/jenkins,ErikVerheul/jenkins,liorhson/jenkins,tfennelly/jenkins,kohsuke/hudson,aldaris/jenkins,elkingtonmcb/jenkins,CodeShane/jenkins,DanielWeber/jenkins,godfath3r/jenkins,lvotypko/jenkins2,FarmGeek4Life/jenkins,NehemiahMi/jenkins,CodeShane/jenkins,soenter/jenkins,vlajos/jenkins,292388900/jenkins,shahharsh/jenkins,damianszczepanik/jenkins,scoheb/jenkins,godfath3r/jenkins,ydubreuil/jenkins,jpederzolli/jenkins-1,wangyikai/jenkins,vijayto/jenkins,alvarolobato/jenkins,patbos/jenkins,arcivanov/jenkins,protazy/jenkins,jzjzjzj/jenkins,KostyaSha/jenkins,thomassuckow/jenkins,lilyJi/jenkins,pantheon-systems/jenkins,escoem/jenkins,MarkEWaite/jenkins,chbiel/jenkins,batmat/jenkins,shahharsh/jenkins,jpederzolli/jenkins-1,huybrechts/hudson,jcsirot/jenkins,brunocvcunha/jenkins,dennisjlee/jenkins,DanielWeber/jenkins,stefanbrausch/hudson-main,noikiy/jenkins,ajshastri/jenkins,jzjzjzj/jenkins,292388900/jenkins,lindzh/jenkins,mpeltonen/jenkins,brunocvcunha/jenkins,shahharsh/jenkins,MarkEWaite/jenkins,singh88/jenkins,gusreiber/jenkins,elkingtonmcb/jenkins,huybrechts/hudson,recena/jenkins,stephenc/jenkins,ikedam/jenkins,stefanbrausch/hudson-main,synopsys-arc-oss/jenkins,hplatou/jenkins,lordofthejars/jenkins,Vlatombe/jenkins,kzantow/jenkins,petermarcoen/jenkins,keyurpatankar/hudson,ns163/jenkins,jglick/jenkins,jtnord/jenkins,lilyJi/jenkins,aheritier/jenkins,tastatur/jenkins,albers/jenkins,Vlatombe/jenkins,soenter/jenkins,SenolOzer/jenkins,stephenc/jenkins,petermarcoen/jenkins,petermarcoen/jenkins,mcanthony/jenkins,arcivanov/jenkins,jcsirot/jenkins,lvotypko/jenkins2,albers/jenkins,SenolOzer/jenkins,SebastienGllmt/jenkins,kohsuke/hudson,tangkun75/jenkins,ChrisA89/jenkins,jzjzjzj/jenkins,h4ck3rm1k3/jenkins,MadsNielsen/jtemp,daniel-beck/jenkins,iterate/coding-dojo,MarkEWaite/jenkins,lindzh/jenkins,tastatur/jenkins,NehemiahMi/jenkins,6WIND/jenkins,jenkinsci/jenkins,dbroady1/jenkins,oleg-nenashev/jenkins,pjanouse/jenkins,jk47/jenkins,kzantow/jenkins,aldaris/jenkins,everyonce/jenkins,ydubreuil/jenkins,jhoblitt/jenkins,evernat/jenkins,aduprat/jenkins,vjuranek/jenkins,duzifang/my-jenkins,ikedam/jenkins,varmenise/jenkins,alvarolobato/jenkins,Wilfred/jenkins,luoqii/jenkins,jhoblitt/jenkins,pjanouse/jenkins,gorcz/jenkins,stefanbrausch/hudson-main,jpbriend/jenkins,292388900/jenkins,seanlin816/jenkins,hplatou/jenkins,stephenc/jenkins,DoctorQ/jenkins,hudson/hudson-2.x,elkingtonmcb/jenkins,mrooney/jenkins,patbos/jenkins,Jochen-A-Fuerbacher/jenkins,vijayto/jenkins,mcanthony/jenkins,AustinKwang/jenkins,goldchang/jenkins,pantheon-systems/jenkins,rsandell/jenkins,abayer/jenkins,paulwellnerbou/jenkins,goldchang/jenkins,keyurpatankar/hudson,mrooney/jenkins,keyurpatankar/hudson,akshayabd/jenkins,KostyaSha/jenkins,stephenc/jenkins,tangkun75/jenkins,Jimilian/jenkins,SebastienGllmt/jenkins,aduprat/jenkins,verbitan/jenkins,shahharsh/jenkins,petermarcoen/jenkins,viqueen/jenkins,vivek/hudson,mrobinet/jenkins,KostyaSha/jenkins,MadsNielsen/jtemp,rsandell/jenkins,evernat/jenkins,gorcz/jenkins,bpzhang/jenkins,stephenc/jenkins,1and1/jenkins,bpzhang/jenkins,lordofthejars/jenkins,ndeloof/jenkins,synopsys-arc-oss/jenkins,rlugojr/jenkins,lvotypko/jenkins,protazy/jenkins,guoxu0514/jenkins,evernat/jenkins,khmarbaise/jenkins,daniel-beck/jenkins,DoctorQ/jenkins,goldchang/jenkins,csimons/jenkins,oleg-nenashev/jenkins,paulwellnerbou/jenkins,svanoort/jenkins,liorhson/jenkins,nandan4/Jenkins,rlugojr/jenkins,gorcz/jenkins,guoxu0514/jenkins,jpbriend/jenkins,noikiy/jenkins,recena/jenkins,evernat/jenkins,lordofthejars/jenkins,synopsys-arc-oss/jenkins,brunocvcunha/jenkins,scoheb/jenkins,mcanthony/jenkins,h4ck3rm1k3/jenkins,vvv444/jenkins,fbelzunc/jenkins,protazy/jenkins,verbitan/jenkins,iterate/coding-dojo,singh88/jenkins,jk47/jenkins,AustinKwang/jenkins,albers/jenkins,fbelzunc/jenkins,ns163/jenkins,svanoort/jenkins,pantheon-systems/jenkins,MichaelPranovich/jenkins_sc,rlugojr/jenkins,verbitan/jenkins,gorcz/jenkins,MarkEWaite/jenkins,v1v/jenkins,ikedam/jenkins,6WIND/jenkins,duzifang/my-jenkins,gusreiber/jenkins,csimons/jenkins,jglick/jenkins,292388900/jenkins,deadmoose/jenkins,wuwen5/jenkins,Wilfred/jenkins,Jochen-A-Fuerbacher/jenkins,azweb76/jenkins,brunocvcunha/jenkins,noikiy/jenkins,jenkinsci/jenkins,akshayabd/jenkins,andresrc/jenkins,albers/jenkins,svanoort/jenkins,goldchang/jenkins,everyonce/jenkins,jpederzolli/jenkins-1,github-api-test-org/jenkins,andresrc/jenkins,hplatou/jenkins,KostyaSha/jenkins,mrobinet/jenkins,scoheb/jenkins,oleg-nenashev/jenkins,Jochen-A-Fuerbacher/jenkins,rashmikanta-1984/jenkins,singh88/jenkins,godfath3r/jenkins,azweb76/jenkins,seanlin816/jenkins,jk47/jenkins,oleg-nenashev/jenkins,wuwen5/jenkins,Ykus/jenkins,akshayabd/jenkins,vlajos/jenkins,lvotypko/jenkins3,sathiya-mit/jenkins,gitaccountforprashant/gittest,pantheon-systems/jenkins,chbiel/jenkins,KostyaSha/jenkins,arcivanov/jenkins,6WIND/jenkins,lvotypko/jenkins2,godfath3r/jenkins,maikeffi/hudson,amuniz/jenkins,AustinKwang/jenkins,daspilker/jenkins,jpbriend/jenkins,christ66/jenkins,ChrisA89/jenkins,iqstack/jenkins,gusreiber/jenkins,pjanouse/jenkins,nandan4/Jenkins,jzjzjzj/jenkins,abayer/jenkins,tfennelly/jenkins,evernat/jenkins,iqstack/jenkins,petermarcoen/jenkins,vivek/hudson,hashar/jenkins,pjanouse/jenkins,tangkun75/jenkins,huybrechts/hudson,jk47/jenkins,luoqii/jenkins,morficus/jenkins,mrooney/jenkins,rsandell/jenkins,soenter/jenkins,stefanbrausch/hudson-main,ChrisA89/jenkins,jpederzolli/jenkins-1,DanielWeber/jenkins,aduprat/jenkins,viqueen/jenkins,pselle/jenkins,ydubreuil/jenkins,chbiel/jenkins,liorhson/jenkins,Wilfred/jenkins,mattclark/jenkins,abayer/jenkins,github-api-test-org/jenkins,azweb76/jenkins,ns163/jenkins,paulwellnerbou/jenkins,amruthsoft9/Jenkis,FarmGeek4Life/jenkins,1and1/jenkins,lordofthejars/jenkins,vivek/hudson,292388900/jenkins,arcivanov/jenkins,aquarellian/jenkins,vivek/hudson,keyurpatankar/hudson,damianszczepanik/jenkins,SebastienGllmt/jenkins,christ66/jenkins,yonglehou/jenkins,Krasnyanskiy/jenkins,vijayto/jenkins,liupugong/jenkins,albers/jenkins,mattclark/jenkins,varmenise/jenkins,intelchen/jenkins,Ykus/jenkins,svanoort/jenkins,mpeltonen/jenkins,CodeShane/jenkins,jcarrothers-sap/jenkins,guoxu0514/jenkins,paulwellnerbou/jenkins,liorhson/jenkins,mdonohue/jenkins,ajshastri/jenkins,MarkEWaite/jenkins,FTG-003/jenkins,liupugong/jenkins,escoem/jenkins,deadmoose/jenkins,vvv444/jenkins,akshayabd/jenkins,bpzhang/jenkins,aheritier/jenkins,jhoblitt/jenkins,singh88/jenkins,seanlin816/jenkins,MichaelPranovich/jenkins_sc,pselle/jenkins,mdonohue/jenkins,godfath3r/jenkins,lvotypko/jenkins3,mattclark/jenkins,bkmeneguello/jenkins,damianszczepanik/jenkins,aheritier/jenkins,msrb/jenkins,azweb76/jenkins,iterate/coding-dojo,fbelzunc/jenkins,hashar/jenkins,hashar/jenkins,msrb/jenkins,tastatur/jenkins,oleg-nenashev/jenkins,mrobinet/jenkins,lilyJi/jenkins,Jimilian/jenkins,daspilker/jenkins,daniel-beck/jenkins,protazy/jenkins,tfennelly/jenkins,paulmillar/jenkins,patbos/jenkins,jpbriend/jenkins,aldaris/jenkins,mcanthony/jenkins,singh88/jenkins,Wilfred/jenkins,khmarbaise/jenkins,christ66/jenkins,samatdav/jenkins,lilyJi/jenkins,khmarbaise/jenkins,h4ck3rm1k3/jenkins,bkmeneguello/jenkins,soenter/jenkins,mdonohue/jenkins,v1v/jenkins,verbitan/jenkins,Ykus/jenkins,mattclark/jenkins,petermarcoen/jenkins,thomassuckow/jenkins,fbelzunc/jenkins,wangyikai/jenkins,svanoort/jenkins,singh88/jenkins,vjuranek/jenkins,ikedam/jenkins,DoctorQ/jenkins,arcivanov/jenkins,MichaelPranovich/jenkins_sc,AustinKwang/jenkins,paulwellnerbou/jenkins,deadmoose/jenkins,mrobinet/jenkins,huybrechts/hudson,ikedam/jenkins,paulmillar/jenkins,olivergondza/jenkins,Krasnyanskiy/jenkins,FarmGeek4Life/jenkins,NehemiahMi/jenkins,maikeffi/hudson,my7seven/jenkins,olivergondza/jenkins,arunsingh/jenkins,jenkinsci/jenkins,dariver/jenkins,synopsys-arc-oss/jenkins,dbroady1/jenkins,seanlin816/jenkins,stephenc/jenkins,patbos/jenkins,everyonce/jenkins,jglick/jenkins,escoem/jenkins,Jimilian/jenkins,daspilker/jenkins,amruthsoft9/Jenkis,jpbriend/jenkins,oleg-nenashev/jenkins,hemantojhaa/jenkins,lvotypko/jenkins2,svanoort/jenkins,mcanthony/jenkins,kohsuke/hudson,FTG-003/jenkins,stephenc/jenkins,rsandell/jenkins,jcsirot/jenkins,dbroady1/jenkins,morficus/jenkins,deadmoose/jenkins,v1v/jenkins,ErikVerheul/jenkins,mrooney/jenkins,morficus/jenkins,jpederzolli/jenkins-1,kohsuke/hudson,sathiya-mit/jenkins,arcivanov/jenkins,Vlatombe/jenkins,vivek/hudson,noikiy/jenkins,elkingtonmcb/jenkins,SebastienGllmt/jenkins,6WIND/jenkins,DoctorQ/jenkins,bkmeneguello/jenkins,damianszczepanik/jenkins,damianszczepanik/jenkins,jpederzolli/jenkins-1,rashmikanta-1984/jenkins,dariver/jenkins,vivek/hudson,intelchen/jenkins,escoem/jenkins,lindzh/jenkins,deadmoose/jenkins,dennisjlee/jenkins,lvotypko/jenkins3,jk47/jenkins,samatdav/jenkins,kohsuke/hudson,hemantojhaa/jenkins,everyonce/jenkins,Jochen-A-Fuerbacher/jenkins,lindzh/jenkins,olivergondza/jenkins,elkingtonmcb/jenkins,liupugong/jenkins,batmat/jenkins,morficus/jenkins,arunsingh/jenkins,lindzh/jenkins,kzantow/jenkins,hplatou/jenkins,recena/jenkins,hudson/hudson-2.x,FTG-003/jenkins,huybrechts/hudson,wuwen5/jenkins,arunsingh/jenkins,huybrechts/hudson,scoheb/jenkins,tfennelly/jenkins,brunocvcunha/jenkins,jtnord/jenkins,Vlatombe/jenkins,hplatou/jenkins,tangkun75/jenkins,SenolOzer/jenkins,gusreiber/jenkins,evernat/jenkins,fbelzunc/jenkins,jzjzjzj/jenkins,rsandell/jenkins,FTG-003/jenkins,mdonohue/jenkins,vjuranek/jenkins,chbiel/jenkins,khmarbaise/jenkins,arunsingh/jenkins,tastatur/jenkins,ajshastri/jenkins,jglick/jenkins,andresrc/jenkins,andresrc/jenkins,kzantow/jenkins,bkmeneguello/jenkins,rashmikanta-1984/jenkins,patbos/jenkins,vlajos/jenkins,aheritier/jenkins,christ66/jenkins,SebastienGllmt/jenkins,aquarellian/jenkins,intelchen/jenkins,h4ck3rm1k3/jenkins,mpeltonen/jenkins,maikeffi/hudson,bkmeneguello/jenkins,guoxu0514/jenkins,MadsNielsen/jtemp,v1v/jenkins,thomassuckow/jenkins,daniel-beck/jenkins,huybrechts/hudson,lvotypko/jenkins2,ns163/jenkins,varmenise/jenkins,vjuranek/jenkins,dbroady1/jenkins,viqueen/jenkins,my7seven/jenkins,yonglehou/jenkins,vijayto/jenkins,amruthsoft9/Jenkis,KostyaSha/jenkins,batmat/jenkins,1and1/jenkins,MadsNielsen/jtemp,vjuranek/jenkins,nandan4/Jenkins,akshayabd/jenkins,seanlin816/jenkins,Ykus/jenkins,dbroady1/jenkins,aduprat/jenkins,jhoblitt/jenkins,6WIND/jenkins,pselle/jenkins,pjanouse/jenkins,liorhson/jenkins,rsandell/jenkins,Vlatombe/jenkins,csimons/jenkins,vlajos/jenkins,jtnord/jenkins,stefanbrausch/hudson-main,stefanbrausch/hudson-main,ndeloof/jenkins,iterate/coding-dojo,ikedam/jenkins,samatdav/jenkins,Wilfred/jenkins,DanielWeber/jenkins,ajshastri/jenkins,jcsirot/jenkins,vivek/hudson,1and1/jenkins,MadsNielsen/jtemp,mrobinet/jenkins,akshayabd/jenkins,keyurpatankar/hudson,dennisjlee/jenkins,jglick/jenkins,escoem/jenkins,wuwen5/jenkins,maikeffi/hudson,daniel-beck/jenkins,escoem/jenkins,NehemiahMi/jenkins,sathiya-mit/jenkins,christ66/jenkins,khmarbaise/jenkins,MichaelPranovich/jenkins_sc,guoxu0514/jenkins,ErikVerheul/jenkins,fbelzunc/jenkins,hemantojhaa/jenkins,rashmikanta-1984/jenkins,vijayto/jenkins,lvotypko/jenkins3,tfennelly/jenkins,rashmikanta-1984/jenkins,ChrisA89/jenkins,gitaccountforprashant/gittest,FarmGeek4Life/jenkins,MarkEWaite/jenkins,6WIND/jenkins,Krasnyanskiy/jenkins,luoqii/jenkins,ns163/jenkins,arunsingh/jenkins,iqstack/jenkins,pjanouse/jenkins,MadsNielsen/jtemp,viqueen/jenkins,olivergondza/jenkins,mpeltonen/jenkins,rlugojr/jenkins,amruthsoft9/Jenkis,wangyikai/jenkins,morficus/jenkins,gorcz/jenkins,pselle/jenkins,christ66/jenkins,lvotypko/jenkins,yonglehou/jenkins,everyonce/jenkins,paulwellnerbou/jenkins,alvarolobato/jenkins,CodeShane/jenkins,intelchen/jenkins,guoxu0514/jenkins,luoqii/jenkins,synopsys-arc-oss/jenkins,chbiel/jenkins,wuwen5/jenkins,hashar/jenkins,jcarrothers-sap/jenkins,kzantow/jenkins,v1v/jenkins,jhoblitt/jenkins,aquarellian/jenkins,luoqii/jenkins,gitaccountforprashant/gittest,deadmoose/jenkins,iterate/coding-dojo,alvarolobato/jenkins,akshayabd/jenkins,gitaccountforprashant/gittest,ChrisA89/jenkins,brunocvcunha/jenkins,dariver/jenkins,thomassuckow/jenkins,iqstack/jenkins,aldaris/jenkins,pantheon-systems/jenkins,paulmillar/jenkins,viqueen/jenkins,aquarellian/jenkins,1and1/jenkins,jtnord/jenkins,abayer/jenkins,hudson/hudson-2.x,deadmoose/jenkins,noikiy/jenkins,Krasnyanskiy/jenkins,goldchang/jenkins,dennisjlee/jenkins,SenolOzer/jenkins,jhoblitt/jenkins,morficus/jenkins,abayer/jenkins,hplatou/jenkins,ajshastri/jenkins,intelchen/jenkins,pantheon-systems/jenkins,jk47/jenkins,lvotypko/jenkins,batmat/jenkins,mattclark/jenkins,lordofthejars/jenkins,hashar/jenkins,andresrc/jenkins,hemantojhaa/jenkins,hudson/hudson-2.x,arunsingh/jenkins,ErikVerheul/jenkins,lilyJi/jenkins,jcsirot/jenkins,ErikVerheul/jenkins,kzantow/jenkins,scoheb/jenkins,aquarellian/jenkins,ajshastri/jenkins,jglick/jenkins,samatdav/jenkins,pselle/jenkins,h4ck3rm1k3/jenkins,amuniz/jenkins,jcsirot/jenkins,hemantojhaa/jenkins,liorhson/jenkins,oleg-nenashev/jenkins,jenkinsci/jenkins,godfath3r/jenkins,MadsNielsen/jtemp,Krasnyanskiy/jenkins,Jimilian/jenkins,liupugong/jenkins,abayer/jenkins,intelchen/jenkins,shahharsh/jenkins,csimons/jenkins,jcarrothers-sap/jenkins,daniel-beck/jenkins,FTG-003/jenkins,arcivanov/jenkins,bkmeneguello/jenkins,jk47/jenkins,gorcz/jenkins,jtnord/jenkins,verbitan/jenkins,noikiy/jenkins,yonglehou/jenkins,escoem/jenkins,pantheon-systems/jenkins,daspilker/jenkins,gitaccountforprashant/gittest,kohsuke/hudson,dariver/jenkins,chbiel/jenkins,vvv444/jenkins,bpzhang/jenkins,DoctorQ/jenkins,protazy/jenkins,tangkun75/jenkins,fbelzunc/jenkins,nandan4/Jenkins,my7seven/jenkins,batmat/jenkins,aduprat/jenkins,mrobinet/jenkins,dariver/jenkins,ChrisA89/jenkins,mrobinet/jenkins,MarkEWaite/jenkins,DanielWeber/jenkins,github-api-test-org/jenkins,KostyaSha/jenkins,luoqii/jenkins,ajshastri/jenkins,gorcz/jenkins,hemantojhaa/jenkins,nandan4/Jenkins,jpbriend/jenkins,varmenise/jenkins,mdonohue/jenkins,varmenise/jenkins,mdonohue/jenkins,everyonce/jenkins,synopsys-arc-oss/jenkins,amruthsoft9/Jenkis,keyurpatankar/hudson,DoctorQ/jenkins,lordofthejars/jenkins,NehemiahMi/jenkins,ikedam/jenkins,rsandell/jenkins,dennisjlee/jenkins,wangyikai/jenkins,arunsingh/jenkins,christ66/jenkins,ndeloof/jenkins,jcarrothers-sap/jenkins,abayer/jenkins,azweb76/jenkins,SebastienGllmt/jenkins,alvarolobato/jenkins,jtnord/jenkins,stefanbrausch/hudson-main,jcarrothers-sap/jenkins,AustinKwang/jenkins,jenkinsci/jenkins,keyurpatankar/hudson,DanielWeber/jenkins,elkingtonmcb/jenkins,scoheb/jenkins,soenter/jenkins,FarmGeek4Life/jenkins,h4ck3rm1k3/jenkins,recena/jenkins,vlajos/jenkins,msrb/jenkins,iterate/coding-dojo,lvotypko/jenkins3,jenkinsci/jenkins,vlajos/jenkins,1and1/jenkins,maikeffi/hudson,mdonohue/jenkins,lilyJi/jenkins,jpbriend/jenkins,shahharsh/jenkins,my7seven/jenkins,rashmikanta-1984/jenkins,wangyikai/jenkins,ErikVerheul/jenkins,amuniz/jenkins,lvotypko/jenkins3,mattclark/jenkins,goldchang/jenkins,varmenise/jenkins,alvarolobato/jenkins,aquarellian/jenkins,lvotypko/jenkins,viqueen/jenkins,olivergondza/jenkins,duzifang/my-jenkins,vlajos/jenkins,damianszczepanik/jenkins,aheritier/jenkins,lvotypko/jenkins,rlugojr/jenkins,nandan4/Jenkins,vvv444/jenkins,Ykus/jenkins,jenkinsci/jenkins,csimons/jenkins,tastatur/jenkins,tfennelly/jenkins,jzjzjzj/jenkins,msrb/jenkins,andresrc/jenkins,damianszczepanik/jenkins,tastatur/jenkins,CodeShane/jenkins,msrb/jenkins,amruthsoft9/Jenkis,Jochen-A-Fuerbacher/jenkins,ns163/jenkins,sathiya-mit/jenkins,vvv444/jenkins,NehemiahMi/jenkins,svanoort/jenkins,my7seven/jenkins,lordofthejars/jenkins,msrb/jenkins,vjuranek/jenkins,FarmGeek4Life/jenkins,ydubreuil/jenkins,vijayto/jenkins,DoctorQ/jenkins,patbos/jenkins,ndeloof/jenkins,github-api-test-org/jenkins,amuniz/jenkins,wangyikai/jenkins,olivergondza/jenkins,mpeltonen/jenkins,Jochen-A-Fuerbacher/jenkins,gorcz/jenkins,dbroady1/jenkins,Jochen-A-Fuerbacher/jenkins,hudson/hudson-2.x,goldchang/jenkins,azweb76/jenkins,yonglehou/jenkins,FTG-003/jenkins,jzjzjzj/jenkins,paulmillar/jenkins,FarmGeek4Life/jenkins,shahharsh/jenkins,aquarellian/jenkins,lvotypko/jenkins2,daniel-beck/jenkins,gusreiber/jenkins,kzantow/jenkins,mrooney/jenkins,seanlin816/jenkins,aldaris/jenkins,gusreiber/jenkins,dariver/jenkins,bpzhang/jenkins,liupugong/jenkins,dbroady1/jenkins,maikeffi/hudson,jcarrothers-sap/jenkins,duzifang/my-jenkins,protazy/jenkins,ns163/jenkins,h4ck3rm1k3/jenkins,samatdav/jenkins,amuniz/jenkins,aheritier/jenkins,ndeloof/jenkins,MichaelPranovich/jenkins_sc,damianszczepanik/jenkins,mcanthony/jenkins,thomassuckow/jenkins,rsandell/jenkins,pjanouse/jenkins,amruthsoft9/Jenkis,vvv444/jenkins,daniel-beck/jenkins,hudson/hudson-2.x,liupugong/jenkins,jtnord/jenkins,morficus/jenkins,SenolOzer/jenkins,ydubreuil/jenkins,ndeloof/jenkins,synopsys-arc-oss/jenkins,sathiya-mit/jenkins,daspilker/jenkins,AustinKwang/jenkins,vvv444/jenkins,daspilker/jenkins,Jimilian/jenkins,my7seven/jenkins,vivek/hudson,viqueen/jenkins,CodeShane/jenkins,pselle/jenkins,github-api-test-org/jenkins,soenter/jenkins,dennisjlee/jenkins,rlugojr/jenkins,singh88/jenkins,sathiya-mit/jenkins,292388900/jenkins,godfath3r/jenkins,lvotypko/jenkins2,lilyJi/jenkins,paulmillar/jenkins,github-api-test-org/jenkins,luoqii/jenkins,goldchang/jenkins,wangyikai/jenkins,amuniz/jenkins,Ykus/jenkins,ndeloof/jenkins,intelchen/jenkins,hemantojhaa/jenkins,amuniz/jenkins,tfennelly/jenkins,duzifang/my-jenkins,patbos/jenkins,KostyaSha/jenkins,bpzhang/jenkins,iqstack/jenkins,SenolOzer/jenkins,292388900/jenkins,shahharsh/jenkins,lindzh/jenkins,recena/jenkins,thomassuckow/jenkins,Jimilian/jenkins,DanielWeber/jenkins,mrooney/jenkins,jpederzolli/jenkins-1,ChrisA89/jenkins,varmenise/jenkins,sathiya-mit/jenkins,github-api-test-org/jenkins,albers/jenkins,azweb76/jenkins,jhoblitt/jenkins,Krasnyanskiy/jenkins,recena/jenkins,lindzh/jenkins,wuwen5/jenkins,gitaccountforprashant/gittest,rashmikanta-1984/jenkins,khmarbaise/jenkins,lvotypko/jenkins,liupugong/jenkins,olivergondza/jenkins,Krasnyanskiy/jenkins,1and1/jenkins,dennisjlee/jenkins,Wilfred/jenkins,github-api-test-org/jenkins,duzifang/my-jenkins,mcanthony/jenkins,AustinKwang/jenkins,Wilfred/jenkins,jenkinsci/jenkins,scoheb/jenkins,dariver/jenkins,tastatur/jenkins,ErikVerheul/jenkins | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
*
* 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 hudson.slaves;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.model.Computer;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.util.DescriptorList;
import org.kohsuke.stapler.DataBoundConstructor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Controls when to take {@link Computer} offline, bring it back online, or even to destroy it.
* <p/>
* <b>EXPERIMENTAL: SIGNATURE MAY CHANGE IN FUTURE RELEASES</b>
*
* @author Stephen Connolly
* @author Kohsuke Kawaguchi
*/
public abstract class RetentionStrategy<T extends Computer> implements Describable<RetentionStrategy<?>>, ExtensionPoint {
/**
* This method will be called periodically to allow this strategy to decide what to do with it's owning slave.
*
* @param c {@link Computer} for which this strategy is assigned. This computer may be online or offline.
* This object also exposes a bunch of properties that the callee can use to decide what action to take.
* @return The number of minutes after which the strategy would like to be checked again. The strategy may be
* rechecked earlier or later that this!
*/
public abstract long check(T c);
/**
* This method is called to determine whether manual launching of the slave is allowed at this point in time.
* @param c {@link Computer} for which this strategy is assigned. This computer may be online or offline.
* This object also exposes a bunch of properties that the callee can use to decide if manual launching is
* allowed at this time.
* @return {@code true} if manual launching of the slave is allowed at this point in time.
*/
public boolean isManualLaunchAllowed(T c) {
return true;
}
/**
* Called when a new {@link Computer} object is introduced (such as when Hudson started, or when
* a new slave is added.)
*
* <p>
* The default implementation of this method delegates to {@link #check(Computer)},
* but this allows {@link RetentionStrategy} to distinguish the first time invocation from the rest.
*
* @since 1.275
*/
public void start(T c) {
check(c);
}
/**
* All registered {@link RetentionStrategy} implementations.
*/
public static final DescriptorList<RetentionStrategy<?>> LIST = new DescriptorList<RetentionStrategy<?>>();
/**
* Dummy instance that doesn't do any attempt to retention.
*/
public static final RetentionStrategy<Computer> NOOP = new RetentionStrategy<Computer>() {
public long check(Computer c) {
return 1;
}
@Override
public void start(Computer c) {
c.connect(false);
}
public Descriptor<RetentionStrategy<?>> getDescriptor() {
return DESCRIPTOR;
}
private final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
class DescriptorImpl extends Descriptor<RetentionStrategy<?>> {
public String getDisplayName() {
return "";
}
}
};
/**
* Convenient singleton instance, since this {@link RetentionStrategy} is stateless.
*/
public static final Always INSTANCE = new Always();
/**
* {@link RetentionStrategy} that tries to keep the node online all the time.
*/
public static class Always extends RetentionStrategy<SlaveComputer> {
/**
* Constructs a new Always.
*/
@DataBoundConstructor
public Always() {
}
public long check(SlaveComputer c) {
if (c.isOffline() && c.isLaunchSupported())
c.tryReconnect();
return 1;
}
public DescriptorImpl getDescriptor() {
return DESCRIPTOR;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
private static class DescriptorImpl extends Descriptor<RetentionStrategy<?>> {
public String getDisplayName() {
return Messages.RetentionStrategy_Always_displayName();
}
}
static {
LIST.add(DESCRIPTOR);
}
}
/**
* {@link hudson.slaves.RetentionStrategy} that tries to keep the node offline when not in use.
*/
public static class Demand extends RetentionStrategy<SlaveComputer> {
private static final Logger logger = Logger.getLogger(Demand.class.getName());
/**
* The delay (in minutes) for which the slave must be in demand before tring to launch it.
*/
private final long inDemandDelay;
/**
* The delay (in minutes) for which the slave must be idle before taking it offline.
*/
private final long idleDelay;
@DataBoundConstructor
public Demand(long inDemandDelay, long idleDelay) {
this.inDemandDelay = Math.max(1, inDemandDelay);
this.idleDelay = Math.max(1, idleDelay);
}
/**
* Getter for property 'inDemandDelay'.
*
* @return Value for property 'inDemandDelay'.
*/
public long getInDemandDelay() {
return inDemandDelay;
}
/**
* Getter for property 'idleDelay'.
*
* @return Value for property 'idleDelay'.
*/
public long getIdleDelay() {
return idleDelay;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public synchronized long check(SlaveComputer c) {
if (c.isOffline()) {
final long demandMilliseconds = System.currentTimeMillis() - c.getDemandStartMilliseconds();
if (demandMilliseconds > inDemandDelay * 1000 * 60 /*MINS->MILLIS*/) {
// we've been in demand for long enough
logger.log(Level.INFO, "Launching computer {0} as it has been in demand for {1}",
new Object[]{c.getName(), Util.getTimeSpanString(demandMilliseconds)});
if (c.isLaunchSupported())
c.connect(true);
}
} else if (c.isIdle()) {
final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();
if (idleMilliseconds > idleDelay * 1000 * 60 /*MINS->MILLIS*/) {
// we've been idle for long enough
logger.log(Level.INFO, "Disconnecting computer {0} as it has been idle for {1}",
new Object[]{c.getName(), Util.getTimeSpanString(idleMilliseconds)});
c.disconnect();
}
}
return 1;
}
public Descriptor<RetentionStrategy<?>> getDescriptor() {
return DESCRIPTOR;
}
private static class DescriptorImpl extends Descriptor<RetentionStrategy<?>> {
public String getDisplayName() {
return Messages.RetentionStrategy_Demand_displayName();
}
}
static {
LIST.add(DESCRIPTOR);
}
}
static {
LIST.load(Demand.class);
if (Boolean.getBoolean("hudson.scheduledRetention"))
LIST.load(SimpleScheduledRetentionStrategy.class);
}
}
| core/src/main/java/hudson/slaves/RetentionStrategy.java | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
*
* 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 hudson.slaves;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.model.Computer;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.util.DescriptorList;
import org.kohsuke.stapler.DataBoundConstructor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Controls when to take {@link Computer} offline, bring it back online, or even to destroy it.
* <p/>
* <b>EXPERIMENTAL: SIGNATURE MAY CHANGE IN FUTURE RELEASES</b>
*
* @author Stephen Connolly
* @author Kohsuke Kawaguchi
*/
public abstract class RetentionStrategy<T extends Computer> implements Describable<RetentionStrategy<?>>, ExtensionPoint {
/**
* This method will be called periodically to allow this strategy to decide what to do with it's owning slave.
*
* @param c {@link Computer} for which this strategy is assigned. This computer may be online or offline.
* This object also exposes a bunch of properties that the callee can use to decide what action to take.
* @return The number of minutes after which the strategy would like to be checked again. The strategy may be
* rechecked earlier or later that this!
*/
public abstract long check(T c);
/**
* This method is called to determine whether manual launching of the slave is allowed at this point in time.
* @param c {@link Computer} for which this strategy is assigned. This computer may be online or offline.
* This object also exposes a bunch of properties that the callee can use to decide if manual launching is
* allowed at this time.
* @return {@code true} if manual launching of the slave is allowed at this point in time.
*/
public boolean isManualLaunchAllowed(T c) {
return true;
}
/**
* Called when a new {@link Computer} object is introduced (such as when Hudson started, or when
* a new slave is added.)
*
* <p>
* The default implementation of this method delegates to {@link #check(Computer)},
* but this allows {@link RetentionStrategy} to distinguish the first time invocation from the rest.
*
* @since 1.275
*/
public void start(T c) {
check(c);
}
/**
* All registered {@link RetentionStrategy} implementations.
*/
public static final DescriptorList<RetentionStrategy<?>> LIST = new DescriptorList<RetentionStrategy<?>>();
/**
* Dummy instance that doesn't do any attempt to retention.
*/
public static final RetentionStrategy<Computer> NOOP = new RetentionStrategy<Computer>() {
public long check(Computer c) {
return 1;
}
@Override
public void start(Computer c) {
c.connect(false);
}
public Descriptor<RetentionStrategy<?>> getDescriptor() {
throw new UnsupportedOperationException();
}
};
/**
* Convenient singleton instance, since this {@link RetentionStrategy} is stateless.
*/
public static final Always INSTANCE = new Always();
/**
* {@link RetentionStrategy} that tries to keep the node online all the time.
*/
public static class Always extends RetentionStrategy<SlaveComputer> {
/**
* Constructs a new Always.
*/
@DataBoundConstructor
public Always() {
}
public long check(SlaveComputer c) {
if (c.isOffline() && c.isLaunchSupported())
c.tryReconnect();
return 1;
}
public DescriptorImpl getDescriptor() {
return DESCRIPTOR;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
private static class DescriptorImpl extends Descriptor<RetentionStrategy<?>> {
public String getDisplayName() {
return Messages.RetentionStrategy_Always_displayName();
}
}
static {
LIST.add(DESCRIPTOR);
}
}
/**
* {@link hudson.slaves.RetentionStrategy} that tries to keep the node offline when not in use.
*/
public static class Demand extends RetentionStrategy<SlaveComputer> {
private static final Logger logger = Logger.getLogger(Demand.class.getName());
/**
* The delay (in minutes) for which the slave must be in demand before tring to launch it.
*/
private final long inDemandDelay;
/**
* The delay (in minutes) for which the slave must be idle before taking it offline.
*/
private final long idleDelay;
@DataBoundConstructor
public Demand(long inDemandDelay, long idleDelay) {
this.inDemandDelay = Math.max(1, inDemandDelay);
this.idleDelay = Math.max(1, idleDelay);
}
/**
* Getter for property 'inDemandDelay'.
*
* @return Value for property 'inDemandDelay'.
*/
public long getInDemandDelay() {
return inDemandDelay;
}
/**
* Getter for property 'idleDelay'.
*
* @return Value for property 'idleDelay'.
*/
public long getIdleDelay() {
return idleDelay;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public synchronized long check(SlaveComputer c) {
if (c.isOffline()) {
final long demandMilliseconds = System.currentTimeMillis() - c.getDemandStartMilliseconds();
if (demandMilliseconds > inDemandDelay * 1000 * 60 /*MINS->MILLIS*/) {
// we've been in demand for long enough
logger.log(Level.INFO, "Launching computer {0} as it has been in demand for {1}",
new Object[]{c.getName(), Util.getTimeSpanString(demandMilliseconds)});
if (c.isLaunchSupported())
c.connect(true);
}
} else if (c.isIdle()) {
final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();
if (idleMilliseconds > idleDelay * 1000 * 60 /*MINS->MILLIS*/) {
// we've been idle for long enough
logger.log(Level.INFO, "Disconnecting computer {0} as it has been idle for {1}",
new Object[]{c.getName(), Util.getTimeSpanString(idleMilliseconds)});
c.disconnect();
}
}
return 1;
}
public Descriptor<RetentionStrategy<?>> getDescriptor() {
return DESCRIPTOR;
}
private static class DescriptorImpl extends Descriptor<RetentionStrategy<?>> {
public String getDisplayName() {
return Messages.RetentionStrategy_Demand_displayName();
}
}
static {
LIST.add(DESCRIPTOR);
}
}
static {
LIST.load(Demand.class);
if (Boolean.getBoolean("hudson.scheduledRetention"))
LIST.load(SimpleScheduledRetentionStrategy.class);
}
}
| UnsupportedOperationException leaves ugly stack trace on the server side when NOOP shows up in the configuration page.
git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@15163 71c3de6d-444a-0410-be80-ed276b4c234a
| core/src/main/java/hudson/slaves/RetentionStrategy.java | UnsupportedOperationException leaves ugly stack trace on the server side when NOOP shows up in the configuration page. | <ide><path>ore/src/main/java/hudson/slaves/RetentionStrategy.java
<ide> }
<ide>
<ide> public Descriptor<RetentionStrategy<?>> getDescriptor() {
<del> throw new UnsupportedOperationException();
<add> return DESCRIPTOR;
<add> }
<add>
<add> private final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
<add>
<add> class DescriptorImpl extends Descriptor<RetentionStrategy<?>> {
<add> public String getDisplayName() {
<add> return "";
<add> }
<ide> }
<ide> };
<ide> |
|
Java | mit | 8cb2be3610e8ab681515757429c7943d07f6d865 | 0 | alternet/alternet.ml,alternet/alternet.ml | package ml.alternet.security.web;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import ml.alternet.facet.Unwrappable;
import ml.alternet.security.EmptyPassword;
import ml.alternet.security.Password;
import ml.alternet.security.PasswordState;
/**
* Represent a non empty sequence of passwords.
*
* <p>If no passwords are in this sequence, the current
* item is the empty password.</p>
*
* <p>NOTE : All the values are available at once in a
* <tt>PasswordParam</tt>. Actually, <tt>PasswordParam</tt>
* is iterable on all the passwords bound to the same name
* (if any) and already refer the first one in the sequence
* (if any, otherwise it refers to the empty password) ;
* therefore, it is irrelevant to specifically ask for a
* <tt>List<PasswordParam></tt>, a <tt>Set<PasswordParam></tt>
* or a <tt>SortedSet<PasswordParam></tt>.</p>
*
* @author Philippe Poulard
*/
public class PasswordParam implements Password, Iterable<Password>, Unwrappable<Password> {
private Iterator<Password> seq; // the sequence
private Password that; // the current pwd
/**
* Create a sequence of passwords.
*
* @param sequence An iterator on the sequence.
*/
public PasswordParam(Iterator<Password> sequence) {
this.seq = sequence;
if (sequence.hasNext()) {
this.that = sequence.next();
} else {
this.that = EmptyPassword.SINGLETON;
}
}
/**
* Convenient constructor for a sequence of a single password.
*
* @param password The single password of the sequence.
*/
public PasswordParam(Password password) {
that = password;
seq = Collections.emptyIterator();
}
/**
* Convenient constructor for a sequence representing the
* empty password.
*/
public PasswordParam() {
this(EmptyPassword.SINGLETON);
}
@Override
public void destroy() {
that.destroy();
}
@Override
public PasswordState state() {
return that.state();
}
@Override
public Clear getClearCopy() throws IllegalStateException {
return that.getClearCopy();
}
/**
* Indicates whether there is a next password in this sequence.
*
* @return <code>true</code> if a password is available, <code>false</code> otherwise.
*/
public boolean hasNext() {
return seq.hasNext();
}
/**
* Return the next password in this sequence.
*
* @return The next password in this sequence.
*/
public PasswordParam next() {
if (this.seq.hasNext()) {
this.that = this.seq.next();
} else if (this.that == EmptyPassword.SINGLETON) {
throw new NoSuchElementException();
} else {
this.that = EmptyPassword.SINGLETON;
}
return this;
}
@Override
public Iterator<Password> iterator() {
return new Iterator<Password>() {
@Override
public boolean hasNext() {
return PasswordParam.this.hasNext();
}
@Override
public Password next() {
return PasswordParam.this.next();
}
};
}
@Override
public String toString() {
return that.toString();
}
@Override
public Password unwrap() {
return that;
}
}
| security/src/main/java/ml/alternet/security/web/PasswordParam.java | package ml.alternet.security.web;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import ml.alternet.facet.Unwrappable;
import ml.alternet.security.EmptyPassword;
import ml.alternet.security.Password;
import ml.alternet.security.PasswordState;
/**
* Represent a non empty sequence of passwords.
*
* <p>If no passwords are in this sequence, the current
* item is the empty password.</p>
*
* <p>NOTE : All the values are available at once in a
* <tt>PasswordParam</tt>. Actually, <tt>PasswordParam</tt>
* is iterable on all the passwords bound to the same name
* (if any) and already refer the first one in the sequence
* (if any, otherwise it refers to the empty password) ;
* therefore, it is irrelevant to specifically ask for a
* <tt>List<PasswordParam></tt>, a <tt>Set<PasswordParam></tt>
* or a <tt>SortedSet<PasswordParam></tt>.</p>
*
* @author Philippe Poulard
*/
public class PasswordParam implements Password, Iterator<PasswordParam>, Iterable<Password>, Unwrappable<Password> {
private Iterator<Password> seq; // the sequence
private Password that; // the current pwd
/**
* Create a sequence of passwords.
*
* @param sequence An iterator on the sequence.
*/
public PasswordParam(Iterator<Password> sequence) {
this.seq = sequence;
if (sequence.hasNext()) {
this.that = sequence.next();
} else {
this.that = EmptyPassword.SINGLETON;
}
}
/**
* Convenient constructor for a sequence of a single password.
*
* @param password The single password of the sequence.
*/
public PasswordParam(Password password) {
that = password;
seq = Collections.emptyIterator();
}
/**
* Convenient constructor for a sequence representing the
* empty password.
*/
public PasswordParam() {
this(EmptyPassword.SINGLETON);
}
@Override
public void destroy() {
that.destroy();
}
@Override
public PasswordState state() {
return that.state();
}
@Override
public Clear getClearCopy() throws IllegalStateException {
return that.getClearCopy();
}
@Override
public boolean hasNext() {
return seq.hasNext();
}
@Override
public PasswordParam next() {
if (this.seq.hasNext()) {
this.that = this.seq.next();
} else if (this.that == EmptyPassword.SINGLETON) {
throw new NoSuchElementException();
} else {
this.that = EmptyPassword.SINGLETON;
}
return this;
}
@Override
public Iterator<Password> iterator() {
return new Iterator<Password>() {
@Override
public boolean hasNext() {
return PasswordParam.this.hasNext();
}
@Override
public Password next() {
return PasswordParam.this.next();
}
};
}
@Override
public String toString() {
return that.toString();
}
@Override
public Password unwrap() {
return that;
}
}
| Conflict on test for Iterator vs Iterable | security/src/main/java/ml/alternet/security/web/PasswordParam.java | Conflict on test for Iterator vs Iterable | <ide><path>ecurity/src/main/java/ml/alternet/security/web/PasswordParam.java
<ide> *
<ide> * @author Philippe Poulard
<ide> */
<del>public class PasswordParam implements Password, Iterator<PasswordParam>, Iterable<Password>, Unwrappable<Password> {
<add>public class PasswordParam implements Password, Iterable<Password>, Unwrappable<Password> {
<ide>
<ide> private Iterator<Password> seq; // the sequence
<ide> private Password that; // the current pwd
<ide> return that.getClearCopy();
<ide> }
<ide>
<del> @Override
<add> /**
<add> * Indicates whether there is a next password in this sequence.
<add> *
<add> * @return <code>true</code> if a password is available, <code>false</code> otherwise.
<add> */
<ide> public boolean hasNext() {
<ide> return seq.hasNext();
<ide> }
<ide>
<del> @Override
<add> /**
<add> * Return the next password in this sequence.
<add> *
<add> * @return The next password in this sequence.
<add> */
<ide> public PasswordParam next() {
<ide> if (this.seq.hasNext()) {
<ide> this.that = this.seq.next(); |
|
Java | apache-2.0 | 1f89a5ed408123a48ec0eb0145f0ec26685d44de | 0 | falbrech-hsdg/aludratest,AludraTest/aludratest,AludraTest/aludratest,falbrech-hsdg/aludratest,AludraTest/aludratest,falbrech-hsdg/aludratest | /*
* Copyright (C) 2010-2014 Hamburg Sud and the 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.aludratest.service.file;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;
import org.aludratest.exception.AutomationException;
import org.aludratest.exception.FunctionalFailure;
import org.aludratest.service.AttachParameter;
import org.aludratest.service.ElementType;
import org.aludratest.service.Interaction;
import org.aludratest.service.TechnicalArgument;
import org.aludratest.service.TechnicalLocator;
/**
* {@link Interaction} interface of the {@link FileService}.
* @author Volker Bergmann
*/
public interface FileInteraction extends Interaction {
/** Provides the root folder of the service instance.
* @return the root folder of the {@link FileService}. */
String getRootFolder();
/** Lists all child elements of the given folder.
* @param filePath the path of the file of which to get children
* @return a {@link List} of the child objects of the given file
*/
List<String> getChildren(@TechnicalLocator String filePath);
/** Lists all child elements of the given folder which match the given regular expression.
* @param filePath the path of the file of which to get the children
* @param filterRegex
* @return a {@link List} of the child objects of the given file
*/
List<String> getChildren(@TechnicalLocator String filePath, String filterRegex);
/** Lists all child elements of the given folder which match the filter.
* @param filePath the path of the file of which to get the children
* @param filter
* @return a {@link List} of the child objects of the given file
*/
List<String> getChildren(@TechnicalLocator String filePath, FileFilter filter);
/** Creates a directory.
* @param directoryPath the path of the directory to create
*/
void createDirectory(@TechnicalLocator String directoryPath);
/** Renames or moves a file or folder.
* @param fromPath the file/folder to rename/move
* @param toPath the new name/location of the file/folder
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean move(@TechnicalLocator String fromPath, String toPath, @TechnicalArgument boolean overwrite);
/** Copies a file or folder.
* @param fromPath the file/folder to copy
* @param toPath the name/location of the copy
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean copy(@TechnicalLocator String fromPath, String toPath, @TechnicalArgument boolean overwrite);
/** Deletes a file or folder.
* @param filePath the path of the file to delete
*/
void delete(@TechnicalLocator String filePath);
/** Creates a text file with the provided content.
* @param filePath the path of the file to save
* @param text the text to save as file content
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean writeTextFile(@TechnicalLocator String filePath, @AttachParameter("Text file contents") String text,
@TechnicalArgument boolean overwrite);
/** Creates a text file and writes to it all content provided by the source Reader.
* @param filePath the path of the file to save
* @param source a {@link Reader} which provides the file content
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean writeTextFile(@TechnicalLocator String filePath, Reader source, @TechnicalArgument boolean overwrite);
/** Creates a binary file with the provided content.
* @param filePath the path of the file to save
* @param bytes the file content to write
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean writeBinaryFile(@TechnicalLocator String filePath, @AttachParameter("Binary file contents") byte[] bytes,
@TechnicalArgument boolean overwrite);
/** Creates a binary file and writes to it all content provided by the source {@link InputStream}.
* @param filePath the path of the file to save
* @param source an {@link InputStream} which provides the content to write to the file
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean writeBinaryFile(@TechnicalLocator String filePath, InputStream source, @TechnicalArgument boolean overwrite);
/** Reads a text file and provides its content as String.
* @param filePath the path of the file to read
* @return the content of the file */
String readTextFile(@TechnicalLocator String filePath);
/** Creates a {@link Reader} for accessing the content of a text file.
* @param filePath the path of the file to read
* @return a reader for the text file */
BufferedReader getReaderForTextFile(@TechnicalLocator String filePath);
/** Reads a binary file and provides its content as an array of bytes.
* @param filePath the path of the file to read
* @return the file content as byte array */
byte[] readBinaryFile(@TechnicalLocator String filePath);
/** Creates an {@link InputStream} for accessing the content of a file.
* @param filePath the path of the file for which to get an input stream
* @return an {@link InputStream} for accessing the file */
InputStream getInputStreamForFile(@TechnicalLocator String filePath);
/** Polls the file system for a given file until it is found or a timeout is exceeded.
* Timeout and the maximum number of polls are retrieved from the
* {@link org.aludratest.service.file.impl.FileServiceConfiguration}.
* @param elementType
* @param filePath the path of the file for which to wait
* @throws AutomationException if the file was not found within the timeout */
void waitUntilExists(
@ElementType String elementType,
@TechnicalLocator String filePath);
/** Polls the file system for a given file until it has disappeared or a timeout is exceeded.
* Timeout and the maximum number of polls are retrieved from the
* {@link org.aludratest.service.file.impl.FileServiceConfiguration}.
* @param filePath the path of the file for which to wait until absence
* @throws AutomationException if the file was not found within the timeout */
void waitUntilNotExists(@TechnicalLocator String filePath);
/** Polls the given directory until the filter finds a match or a timeout is exceeded.
* Timeout and the maximum number of polls are retrieved from the
* {@link org.aludratest.service.file.impl.FileServiceConfiguration}.
* @param parentPath the path of the directory in which to search for the file
* @param filter a filter object that decides which file is to be accepted
* @return the file path of the first file that was accepted by the filter
* @throws AutomationException if the file was not found within the timeout */
String waitForFirstMatch(@TechnicalLocator String parentPath, FileFilter filter);
/** Polls the given directory until the filter finds a match or a timeout is exceeded. Timeout and the maximum number of polls
* are retrieved from the {@link org.aludratest.service.file.impl.FileServiceConfiguration}.
* @param dirPath the path of the directory in which to search for the file
* @param selector a {@link FileChooser} object that decides which file is to be accepted
* @return the file path of the file that was accepted by the filter, or null if none was accepted
* @throws AutomationException if the file was not found within the timeout */
String waitUntilChildExists(String dirPath, FileChooser selector);
}
| src/main/java/org/aludratest/service/file/FileInteraction.java | /*
* Copyright (C) 2010-2014 Hamburg Sud and the 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.aludratest.service.file;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;
import org.aludratest.exception.AutomationException;
import org.aludratest.exception.FunctionalFailure;
import org.aludratest.service.AttachParameter;
import org.aludratest.service.ElementType;
import org.aludratest.service.Interaction;
import org.aludratest.service.TechnicalLocator;
/**
* {@link Interaction} interface of the {@link FileService}.
* @author Volker Bergmann
*/
public interface FileInteraction extends Interaction {
/** Provides the root folder of the service instance.
* @return the root folder of the {@link FileService}. */
String getRootFolder();
/** Lists all child elements of the given folder.
* @param filePath the path of the file of which to get children
* @return a {@link List} of the child objects of the given file
*/
List<String> getChildren(@TechnicalLocator String filePath);
/** Lists all child elements of the given folder which match the given regular expression.
* @param filePath the path of the file of which to get the children
* @param filterRegex
* @return a {@link List} of the child objects of the given file
*/
List<String> getChildren(@TechnicalLocator String filePath, String filterRegex);
/** Lists all child elements of the given folder which match the filter.
* @param filePath the path of the file of which to get the children
* @param filter
* @return a {@link List} of the child objects of the given file
*/
List<String> getChildren(@TechnicalLocator String filePath, FileFilter filter);
/** Creates a directory.
* @param directoryPath the path of the directory to create
*/
void createDirectory(@TechnicalLocator String directoryPath);
/** Renames or moves a file or folder.
* @param fromPath the file/folder to rename/move
* @param toPath the new name/location of the file/folder
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean move(@TechnicalLocator String fromPath, String toPath, boolean overwrite);
/** Copies a file or folder.
* @param fromPath the file/folder to copy
* @param toPath the name/location of the copy
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean copy(@TechnicalLocator String fromPath, String toPath, boolean overwrite);
/** Deletes a file or folder.
* @param filePath the path of the file to delete
*/
void delete(@TechnicalLocator String filePath);
/** Creates a text file with the provided content.
* @param filePath the path of the file to save
* @param text the text to save as file content
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean writeTextFile(@TechnicalLocator String filePath, @AttachParameter("Text file contents") String text, boolean overwrite);
/** Creates a text file and writes to it all content provided by the source Reader.
* @param filePath the path of the file to save
* @param source a {@link Reader} which provides the file content
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean writeTextFile(@TechnicalLocator String filePath, Reader source, boolean overwrite);
/** Creates a binary file with the provided content.
* @param filePath the path of the file to save
* @param bytes the file content to write
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean writeBinaryFile(@TechnicalLocator String filePath, @AttachParameter("Binary file contents") byte[] bytes,
boolean overwrite);
/** Creates a binary file and writes to it all content provided by the source {@link InputStream}.
* @param filePath the path of the file to save
* @param source an {@link InputStream} which provides the content to write to the file
* @param overwrite flag which indicates if an existing file may be overwritten by the operation
* @return true if a formerly existing file was overwritten.
* @throws FunctionalFailure if a file was already present and overwriting was disabled. */
boolean writeBinaryFile(@TechnicalLocator String filePath, InputStream source, boolean overwrite);
/** Reads a text file and provides its content as String.
* @param filePath the path of the file to read
* @return the content of the file */
String readTextFile(@TechnicalLocator String filePath);
/** Creates a {@link Reader} for accessing the content of a text file.
* @param filePath the path of the file to read
* @return a reader for the text file */
BufferedReader getReaderForTextFile(@TechnicalLocator String filePath);
/** Reads a binary file and provides its content as an array of bytes.
* @param filePath the path of the file to read
* @return the file content as byte array */
byte[] readBinaryFile(@TechnicalLocator String filePath);
/** Creates an {@link InputStream} for accessing the content of a file.
* @param filePath the path of the file for which to get an input stream
* @return an {@link InputStream} for accessing the file */
InputStream getInputStreamForFile(@TechnicalLocator String filePath);
/** Polls the file system for a given file until it is found or a timeout is exceeded.
* Timeout and the maximum number of polls are retrieved from the
* {@link org.aludratest.service.file.impl.FileServiceConfiguration}.
* @param elementType
* @param filePath the path of the file for which to wait
* @throws AutomationException if the file was not found within the timeout */
void waitUntilExists(
@ElementType String elementType,
@TechnicalLocator String filePath);
/** Polls the file system for a given file until it has disappeared or a timeout is exceeded.
* Timeout and the maximum number of polls are retrieved from the
* {@link org.aludratest.service.file.impl.FileServiceConfiguration}.
* @param filePath the path of the file for which to wait until absence
* @throws AutomationException if the file was not found within the timeout */
void waitUntilNotExists(@TechnicalLocator String filePath);
/** Polls the given directory until the filter finds a match or a timeout is exceeded.
* Timeout and the maximum number of polls are retrieved from the
* {@link org.aludratest.service.file.impl.FileServiceConfiguration}.
* @param parentPath the path of the directory in which to search for the file
* @param filter a filter object that decides which file is to be accepted
* @return the file path of the first file that was accepted by the filter
* @throws AutomationException if the file was not found within the timeout */
String waitForFirstMatch(@TechnicalLocator String parentPath, FileFilter filter);
/** Polls the given directory until the filter finds a match or a timeout is exceeded. Timeout and the maximum number of polls
* are retrieved from the {@link org.aludratest.service.file.impl.FileServiceConfiguration}.
* @param dirPath the path of the directory in which to search for the file
* @param selector a {@link FileChooser} object that decides which file is to be accepted
* @return the file path of the file that was accepted by the filter, or null if none was accepted
* @throws AutomationException if the file was not found within the timeout */
String waitUntilChildExists(String dirPath, FileChooser selector);
}
| Log overwrite parameter as Technical Argument, not as data | src/main/java/org/aludratest/service/file/FileInteraction.java | Log overwrite parameter as Technical Argument, not as data | <ide><path>rc/main/java/org/aludratest/service/file/FileInteraction.java
<ide> import org.aludratest.service.AttachParameter;
<ide> import org.aludratest.service.ElementType;
<ide> import org.aludratest.service.Interaction;
<add>import org.aludratest.service.TechnicalArgument;
<ide> import org.aludratest.service.TechnicalLocator;
<ide>
<ide> /**
<ide> * @param overwrite flag which indicates if an existing file may be overwritten by the operation
<ide> * @return true if a formerly existing file was overwritten.
<ide> * @throws FunctionalFailure if a file was already present and overwriting was disabled. */
<del> boolean move(@TechnicalLocator String fromPath, String toPath, boolean overwrite);
<add> boolean move(@TechnicalLocator String fromPath, String toPath, @TechnicalArgument boolean overwrite);
<ide>
<ide> /** Copies a file or folder.
<ide> * @param fromPath the file/folder to copy
<ide> * @param overwrite flag which indicates if an existing file may be overwritten by the operation
<ide> * @return true if a formerly existing file was overwritten.
<ide> * @throws FunctionalFailure if a file was already present and overwriting was disabled. */
<del> boolean copy(@TechnicalLocator String fromPath, String toPath, boolean overwrite);
<add> boolean copy(@TechnicalLocator String fromPath, String toPath, @TechnicalArgument boolean overwrite);
<ide>
<ide> /** Deletes a file or folder.
<ide> * @param filePath the path of the file to delete
<ide> * @param overwrite flag which indicates if an existing file may be overwritten by the operation
<ide> * @return true if a formerly existing file was overwritten.
<ide> * @throws FunctionalFailure if a file was already present and overwriting was disabled. */
<del> boolean writeTextFile(@TechnicalLocator String filePath, @AttachParameter("Text file contents") String text, boolean overwrite);
<add> boolean writeTextFile(@TechnicalLocator String filePath, @AttachParameter("Text file contents") String text,
<add> @TechnicalArgument boolean overwrite);
<ide>
<ide> /** Creates a text file and writes to it all content provided by the source Reader.
<ide> * @param filePath the path of the file to save
<ide> * @param overwrite flag which indicates if an existing file may be overwritten by the operation
<ide> * @return true if a formerly existing file was overwritten.
<ide> * @throws FunctionalFailure if a file was already present and overwriting was disabled. */
<del> boolean writeTextFile(@TechnicalLocator String filePath, Reader source, boolean overwrite);
<add> boolean writeTextFile(@TechnicalLocator String filePath, Reader source, @TechnicalArgument boolean overwrite);
<ide>
<ide> /** Creates a binary file with the provided content.
<ide> * @param filePath the path of the file to save
<ide> * @return true if a formerly existing file was overwritten.
<ide> * @throws FunctionalFailure if a file was already present and overwriting was disabled. */
<ide> boolean writeBinaryFile(@TechnicalLocator String filePath, @AttachParameter("Binary file contents") byte[] bytes,
<del> boolean overwrite);
<add> @TechnicalArgument boolean overwrite);
<ide>
<ide> /** Creates a binary file and writes to it all content provided by the source {@link InputStream}.
<ide> * @param filePath the path of the file to save
<ide> * @param overwrite flag which indicates if an existing file may be overwritten by the operation
<ide> * @return true if a formerly existing file was overwritten.
<ide> * @throws FunctionalFailure if a file was already present and overwriting was disabled. */
<del> boolean writeBinaryFile(@TechnicalLocator String filePath, InputStream source, boolean overwrite);
<add> boolean writeBinaryFile(@TechnicalLocator String filePath, InputStream source, @TechnicalArgument boolean overwrite);
<ide>
<ide> /** Reads a text file and provides its content as String.
<ide> * @param filePath the path of the file to read |
|
Java | apache-2.0 | error: pathspec 'src/main/java/ui/GUIController.java' did not match any file(s) known to git
| e35aa13d4e21a3b63bca7bb3f222cc22dbcd359a | 1 | HyungJon/HubTurbo,Honoo/HubTurbo,saav/HubTurbo,HyungJon/HubTurbo,Sumei1009/HubTurbo,saav/HubTurbo,ianngiaw/HubTurbo,Sumei1009/HubTurbo,gaieepo/HubTurbo,Honoo/HubTurbo,gaieepo/HubTurbo,ianngiaw/HubTurbo | package ui;
import ui.issuecolumn.ColumnControl;
import ui.issuecolumn.IssueColumn;
import ui.issuecolumn.UIBrowserBridge;
import ui.issuepanel.IssuePanel;
import util.events.ModelUpdatedEventHandler;
/**
* This class manages the state of UI components and acts as a gateway between
* back-end components and GUI components. Any mutation of GUI components should be
* done here.
*/
public class GUIController {
private ColumnControl columnControl;
private UI ui;
public GUIController(UI ui, ColumnControl columnControl) {
this.ui = ui;
this.columnControl = columnControl;
// Set up the connection to the browser
new UIBrowserBridge(ui);
// Then register update events
registerEvents();
}
public void registerEvents() {
UI.events.registerEvent((ModelUpdatedEventHandler) e -> {
columnControl.updateModel(e.model);
columnControl.forEach(child -> {
if (child instanceof IssuePanel) {
((IssueColumn) child).setItems(e.model.getIssues(), e.hasMetadata);
}
});
});
}
}
| src/main/java/ui/GUIController.java | Created GUI Controller and placed columns update logic from ColumnControl in GUIController
| src/main/java/ui/GUIController.java | Created GUI Controller and placed columns update logic from ColumnControl in GUIController | <ide><path>rc/main/java/ui/GUIController.java
<add>package ui;
<add>
<add>import ui.issuecolumn.ColumnControl;
<add>import ui.issuecolumn.IssueColumn;
<add>import ui.issuecolumn.UIBrowserBridge;
<add>import ui.issuepanel.IssuePanel;
<add>import util.events.ModelUpdatedEventHandler;
<add>
<add>/**
<add> * This class manages the state of UI components and acts as a gateway between
<add> * back-end components and GUI components. Any mutation of GUI components should be
<add> * done here.
<add> */
<add>
<add>public class GUIController {
<add> private ColumnControl columnControl;
<add> private UI ui;
<add>
<add> public GUIController(UI ui, ColumnControl columnControl) {
<add> this.ui = ui;
<add> this.columnControl = columnControl;
<add>
<add> // Set up the connection to the browser
<add> new UIBrowserBridge(ui);
<add>
<add> // Then register update events
<add> registerEvents();
<add> }
<add>
<add> public void registerEvents() {
<add> UI.events.registerEvent((ModelUpdatedEventHandler) e -> {
<add> columnControl.updateModel(e.model);
<add> columnControl.forEach(child -> {
<add> if (child instanceof IssuePanel) {
<add> ((IssueColumn) child).setItems(e.model.getIssues(), e.hasMetadata);
<add> }
<add> });
<add> });
<add> }
<add>} |
|
Java | apache-2.0 | 1575782aedde7983314ef56ac8e93e41936e78e3 | 0 | DaveVoorhis/LDI,DaveVoorhis/LDI | /** Convenient runner for the Sil transpiler. */
public class Silt {
public static void main(String[] args) {
uk.ac.derby.ldi.silt.transpiler.Transpiler.main(args);
}
}
| Silt/src/Silt.java | /** Convenient runner for the Sili compiler. */
public class Silt {
public static void main(String[] args) {
uk.ac.derby.ldi.silt.transpiler.Transpiler.main(args);
}
}
| Fix comment | Silt/src/Silt.java | Fix comment | <ide><path>ilt/src/Silt.java
<del>/** Convenient runner for the Sili compiler. */
<add>/** Convenient runner for the Sil transpiler. */
<ide>
<ide> public class Silt {
<ide> public static void main(String[] args) { |
|
Java | mit | error: pathspec 'src/main/java/leetcode/Problem532.java' did not match any file(s) known to git
| eb5980525b6fd0ea27a043680b813be7b748cce5 | 1 | fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode | package leetcode;
/**
* https://leetcode.com/problems/k-diff-pairs-in-an-array/
*/
public class Problem532 {
public int findPairs(int[] nums, int k) {
// TODO
return 0;
}
public static void main(String[] args) {
Problem532 prob = new Problem532();
System.out.println(prob.findPairs(new int[]{3, 1, 4, 1, 5}, 2)); // 2
System.out.println(prob.findPairs(new int[]{1, 2, 3, 4, 5}, 1)); // 4
System.out.println(prob.findPairs(new int[]{1, 3, 1, 5, 4}, 0)); // 1
}
}
| src/main/java/leetcode/Problem532.java | Skeleton for problem 532
| src/main/java/leetcode/Problem532.java | Skeleton for problem 532 | <ide><path>rc/main/java/leetcode/Problem532.java
<add>package leetcode;
<add>
<add>/**
<add> * https://leetcode.com/problems/k-diff-pairs-in-an-array/
<add> */
<add>public class Problem532 {
<add> public int findPairs(int[] nums, int k) {
<add> // TODO
<add> return 0;
<add> }
<add>
<add> public static void main(String[] args) {
<add> Problem532 prob = new Problem532();
<add> System.out.println(prob.findPairs(new int[]{3, 1, 4, 1, 5}, 2)); // 2
<add> System.out.println(prob.findPairs(new int[]{1, 2, 3, 4, 5}, 1)); // 4
<add> System.out.println(prob.findPairs(new int[]{1, 3, 1, 5, 4}, 0)); // 1
<add> }
<add>} |
|
Java | bsd-3-clause | ae277a8d5b0954a7edcf22e11d461fc4a3c405c1 | 0 | CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers | package gov.nih.nci.cabig.caaers.dao;
import gov.nih.nci.cabig.caaers.DaoTestCase;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.domain.workflow.WorkflowConfig;
/**
*
* @author Biju Joseph
*
*/
public class StudySiteDaoTest extends DaoTestCase<StudySiteDao> {
protected void setUp() throws Exception {
super.setUp();
}
public void testMatchByStudyAndOrg() {
StudySite site = getDao().matchByStudyAndOrg("National Cancer Institute", "1138-43", "local");
assertNotNull(site);
}
public void testMatchByStudyAndOrgNciId() {
StudySite site = getDao().matchByStudyAndOrgNciId("NCI", "1138-43", "local");
assertNotNull(site);
}
public void testFindByStudyAndOrganization() {
StudySite site = getDao().findByStudyAndOrganization(-2, -1001);
assertNotNull(site);
}
public void testFindByStudyAndOrganizationInvalidStudy(){
StudySite site = getDao().findByStudyAndOrganization(-21, -1001);
assertNull(site);
}
public void testFindByStudyAndOrganizationInvalidOrganization(){
StudySite site = getDao().findByStudyAndOrganization(-2, -1002);
assertNull(site);
}
public void testGetById(){
StudySite site = getDao().getById(-1000);
assertNotNull(site);
assertNotNull(site.getWorkflowConfigs());
assertNotNull(site.getWorkflowConfigs().get("reportingPeriod"));
}
public void testSaveSiteWorkflowConfigAssociation(){
{
StudySite site = getDao().getById(-1000);
assertNotNull(site);
assertNotNull(site.getWorkflowConfigs());
assertNotNull(site.getWorkflowConfigs().get("reportingPeriod"));
assertNull(site.getWorkflowConfigs().get("mytest"));
}
interruptSession();
{
StudySite site = getDao().getById(-1000);
assertNotNull(site);
assertNotNull(site.getWorkflowConfigs());
assertNotNull(site.getWorkflowConfigs().get("reportingPeriod"));
WorkflowConfig wfconfig = new WorkflowConfig();
wfconfig.setId(-3000);
wfconfig.setVersion(0);
site.getWorkflowConfigs().put("mytest", wfconfig);
assertNotNull(site.getWorkflowConfigs().get("mytest"));
getDao().save(site);
}
interruptSession();
{
StudySite site = getDao().getById(-1000);
assertNotNull(site);
assertNotNull(site.getWorkflowConfigs());
assertNotNull(site.getWorkflowConfigs().get("reportingPeriod"));
assertNotNull(site.getWorkflowConfigs().get("mytest"));
assertEquals("MyTest", site.getWorkflowConfigs().get("mytest").getName());
}
}
}
| projects/core/src/test/java/gov/nih/nci/cabig/caaers/dao/StudySiteDaoTest.java | package gov.nih.nci.cabig.caaers.dao;
import gov.nih.nci.cabig.caaers.DaoTestCase;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.domain.workflow.WorkflowConfig;
/**
*
* @author Biju Joseph
*
*/
public class StudySiteDaoTest extends DaoTestCase<StudySiteDao> {
protected void setUp() throws Exception {
super.setUp();
}
public void testMatchByStudyAndOrg() {
StudySite site = getDao().matchByStudyAndOrg("National Cancer Institute", "1138-43", "local");
assertNotNull(site);
}
public void testFindByStudyAndOrganization() {
StudySite site = getDao().findByStudyAndOrganization(-2, -1001);
assertNotNull(site);
}
public void testFindByStudyAndOrganizationInvalidStudy(){
StudySite site = getDao().findByStudyAndOrganization(-21, -1001);
assertNull(site);
}
public void testFindByStudyAndOrganizationInvalidOrganization(){
StudySite site = getDao().findByStudyAndOrganization(-2, -1002);
assertNull(site);
}
public void testGetById(){
StudySite site = getDao().getById(-1000);
assertNotNull(site);
assertNotNull(site.getWorkflowConfigs());
assertNotNull(site.getWorkflowConfigs().get("reportingPeriod"));
}
public void testSaveSiteWorkflowConfigAssociation(){
{
StudySite site = getDao().getById(-1000);
assertNotNull(site);
assertNotNull(site.getWorkflowConfigs());
assertNotNull(site.getWorkflowConfigs().get("reportingPeriod"));
assertNull(site.getWorkflowConfigs().get("mytest"));
}
interruptSession();
{
StudySite site = getDao().getById(-1000);
assertNotNull(site);
assertNotNull(site.getWorkflowConfigs());
assertNotNull(site.getWorkflowConfigs().get("reportingPeriod"));
WorkflowConfig wfconfig = new WorkflowConfig();
wfconfig.setId(-3000);
wfconfig.setVersion(0);
site.getWorkflowConfigs().put("mytest", wfconfig);
assertNotNull(site.getWorkflowConfigs().get("mytest"));
getDao().save(site);
}
interruptSession();
{
StudySite site = getDao().getById(-1000);
assertNotNull(site);
assertNotNull(site.getWorkflowConfigs());
assertNotNull(site.getWorkflowConfigs().get("reportingPeriod"));
assertNotNull(site.getWorkflowConfigs().get("mytest"));
assertEquals("MyTest", site.getWorkflowConfigs().get("mytest").getName());
}
}
}
| added testMatchByStudyAndOrgNciId
SVN-Revision: 8679
| projects/core/src/test/java/gov/nih/nci/cabig/caaers/dao/StudySiteDaoTest.java | added testMatchByStudyAndOrgNciId | <ide><path>rojects/core/src/test/java/gov/nih/nci/cabig/caaers/dao/StudySiteDaoTest.java
<ide> assertNotNull(site);
<ide> }
<ide>
<del>
<add> public void testMatchByStudyAndOrgNciId() {
<add> StudySite site = getDao().matchByStudyAndOrgNciId("NCI", "1138-43", "local");
<add> assertNotNull(site);
<add> }
<add>
<ide> public void testFindByStudyAndOrganization() {
<ide> StudySite site = getDao().findByStudyAndOrganization(-2, -1001);
<ide> assertNotNull(site); |
|
Java | bsd-2-clause | error: pathspec 'lava-crms/src/edu/ucsf/lava/crms/protocol/controller/ProtocolInstrumentConfigOptionHandler.java' did not match any file(s) known to git
| b37123968d9461b9c144a4c49427b4c04267ec10 | 1 | UCSFMemoryAndAging/lava,UCSFMemoryAndAging/lava,UCSFMemoryAndAging/lava | package edu.ucsf.lava.crms.protocol.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.BindingResult;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import edu.ucsf.lava.core.controller.ComponentCommand;
import edu.ucsf.lava.core.model.EntityBase;
import edu.ucsf.lava.crms.controller.CrmsEntityComponentHandler;
import edu.ucsf.lava.crms.protocol.model.ProtocolInstrumentConfig;
import edu.ucsf.lava.crms.protocol.model.ProtocolInstrumentConfigOption;
import edu.ucsf.lava.crms.protocol.model.ProtocolVisitConfig;
public class ProtocolInstrumentConfigOptionHandler extends CrmsEntityComponentHandler {
public ProtocolInstrumentConfigOptionHandler() {
super();
setHandledEntity("protocolInstrumentConfigOption", ProtocolInstrumentConfigOption.class);
}
protected String[] defineRequiredFields(RequestContext context, Object command) {
setRequiredFields(new String[]{"label","instrType"});
return getRequiredFields();
}
protected Object initializeNewCommandInstance(RequestContext context, Object command){
HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest();
ProtocolInstrumentConfigOption instrumentOptionConfig = (ProtocolInstrumentConfigOption) command;
ProtocolInstrumentConfig instrumentConfig = (ProtocolInstrumentConfig) ProtocolInstrumentConfig.MANAGER.getOne(EntityBase.newFilterInstance().addIdDaoEqualityParam(Long.valueOf(context.getFlowScope().getString("param"))));
// the collection association between ProtocolInstrumentConfig and ProtocolInstrumentOptionConfig need only be unidirectional
// but was made bidirectional so that ProtocolInstrumentConfig does not have to be persisted in this handler (which
// would require doSaveAdd retrieving ProtocolInstrumentConfig again to persist it). ProtocolInstrumentConfig
// addOption manages both ends of the association, but only have to persist the collection end, ProtocolInstrumentOptionConfig
instrumentConfig.addOption(instrumentOptionConfig);
instrumentOptionConfig.setProjName(instrumentConfig.getProjName());
return command;
}
}
| lava-crms/src/edu/ucsf/lava/crms/protocol/controller/ProtocolInstrumentConfigOptionHandler.java | renamed from ProtocolInstrumentOptionConfigHandler
| lava-crms/src/edu/ucsf/lava/crms/protocol/controller/ProtocolInstrumentConfigOptionHandler.java | renamed from ProtocolInstrumentOptionConfigHandler | <ide><path>ava-crms/src/edu/ucsf/lava/crms/protocol/controller/ProtocolInstrumentConfigOptionHandler.java
<add>package edu.ucsf.lava.crms.protocol.controller;
<add>
<add>import java.util.Map;
<add>
<add>import javax.servlet.http.HttpServletRequest;
<add>
<add>import org.springframework.validation.BindingResult;
<add>import org.springframework.webflow.context.servlet.ServletExternalContext;
<add>import org.springframework.webflow.execution.Event;
<add>import org.springframework.webflow.execution.RequestContext;
<add>
<add>import edu.ucsf.lava.core.controller.ComponentCommand;
<add>import edu.ucsf.lava.core.model.EntityBase;
<add>import edu.ucsf.lava.crms.controller.CrmsEntityComponentHandler;
<add>import edu.ucsf.lava.crms.protocol.model.ProtocolInstrumentConfig;
<add>import edu.ucsf.lava.crms.protocol.model.ProtocolInstrumentConfigOption;
<add>import edu.ucsf.lava.crms.protocol.model.ProtocolVisitConfig;
<add>
<add>public class ProtocolInstrumentConfigOptionHandler extends CrmsEntityComponentHandler {
<add>
<add> public ProtocolInstrumentConfigOptionHandler() {
<add> super();
<add> setHandledEntity("protocolInstrumentConfigOption", ProtocolInstrumentConfigOption.class);
<add> }
<add>
<add> protected String[] defineRequiredFields(RequestContext context, Object command) {
<add> setRequiredFields(new String[]{"label","instrType"});
<add> return getRequiredFields();
<add> }
<add>
<add> protected Object initializeNewCommandInstance(RequestContext context, Object command){
<add> HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest();
<add>
<add> ProtocolInstrumentConfigOption instrumentOptionConfig = (ProtocolInstrumentConfigOption) command;
<add> ProtocolInstrumentConfig instrumentConfig = (ProtocolInstrumentConfig) ProtocolInstrumentConfig.MANAGER.getOne(EntityBase.newFilterInstance().addIdDaoEqualityParam(Long.valueOf(context.getFlowScope().getString("param"))));
<add> // the collection association between ProtocolInstrumentConfig and ProtocolInstrumentOptionConfig need only be unidirectional
<add> // but was made bidirectional so that ProtocolInstrumentConfig does not have to be persisted in this handler (which
<add> // would require doSaveAdd retrieving ProtocolInstrumentConfig again to persist it). ProtocolInstrumentConfig
<add> // addOption manages both ends of the association, but only have to persist the collection end, ProtocolInstrumentOptionConfig
<add> instrumentConfig.addOption(instrumentOptionConfig);
<add> instrumentOptionConfig.setProjName(instrumentConfig.getProjName());
<add> return command;
<add> }
<add>
<add>} |
|
Java | apache-2.0 | d5d5523edbddae6423cb40da3ef15e82e30cb1d3 | 0 | McLeodMoores/starling,McLeodMoores/starling,McLeodMoores/starling,McLeodMoores/starling | /**
* Copyright (C) 2017 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.mcleodmoores.analytics.math.statistics.descriptive;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.result.Function2;
/**
* Calculates the weighted mean of a series of values:
* $$
* \mu^* = \frac{\sum_{i=1}^n w_i x_i}{\sum_{i=1}^n w_i}
* $$
*/
public class WeightedMeanCalculator implements Function2<WeightFunction<Double>, double[], Double> {
@Override
public Double apply(final WeightFunction<Double> weights, final double[] values) {
ArgumentChecker.notNull(weights, "weights");
ArgumentChecker.notNull(values, "values");
final int n = values.length;
double sumW = 0;
double mean = 0;
for (int i = 0; i < n; i++) {
final double weight = weights.get();
sumW += weight;
mean = mean + weight * (values[i] - mean) / sumW;
}
return mean;
}
}
| projects/analytics/src/main/java/com/mcleodmoores/analytics/math/statistics/descriptive/WeightedMeanCalculator.java | /**
* Copyright (C) 2017 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.mcleodmoores.analytics.math.statistics.descriptive;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.result.Function2;
/**
* Calculates the weighted mean of a series of values:
* $$
* \mu^* = \frac{\sum_{i=1}^n w_i x_i}{\sum_{i=1}^n w_i}
* $$
*/
public class WeightedMeanCalculator implements Function2<WeightFunction<Double>, double[], Double> {
@Override
public Double apply(final WeightFunction<Double> weights, final double[] values) {
ArgumentChecker.notNull(weights, "weights");
ArgumentChecker.notNull(values, "values");
final int n = values.length;
double sumW = 0;
double mean = 0;
for (int i = 0; i < n; i++) {
final double weight = weights.get();
System.out.println(weight);
sumW += weight;
mean = mean + weight * (values[i] - mean) / sumW;
}
return mean;
}
}
| Removing a print statement
| projects/analytics/src/main/java/com/mcleodmoores/analytics/math/statistics/descriptive/WeightedMeanCalculator.java | Removing a print statement | <ide><path>rojects/analytics/src/main/java/com/mcleodmoores/analytics/math/statistics/descriptive/WeightedMeanCalculator.java
<ide> double mean = 0;
<ide> for (int i = 0; i < n; i++) {
<ide> final double weight = weights.get();
<del> System.out.println(weight);
<ide> sumW += weight;
<ide> mean = mean + weight * (values[i] - mean) / sumW;
<ide> } |
|
Java | lgpl-2.1 | 3f6251b14e951d8e0ebfba8929a359d3ee57c3f3 | 0 | kerner1000/jcamp-dx | package org.jcamp.parser;
/**
* {@code AFFNTokenizer} handles numeric data tables in AFFN format.
*
*
* @author Thomas Weber
* @author <a href="mailto:[email protected]">Alexander
* Kerner</a>
*/
public class AFFNTokenizer implements java.util.Enumeration<AFFNGroup> {
private final DataType type;
private String data;
private final String[] varSymbols;
private int pos;
private int length;
/**
* AFFNTokenizer constructor comment.
*/
public AFFNTokenizer(String[] symbols, String data) throws JCAMPException {
super();
this.type = checkSymbols(symbols);
if (this.type == null)
this.varSymbols = symbols;
else
this.varSymbols = this.type.getSymbols();
this.data = normalizeData(varSymbols.length, data);
this.length = this.data.length();
}
/**
* AFFNTokenizer constructor comment.
*/
public AFFNTokenizer(JCAMPDataRecord ldr) throws JCAMPException {
super();
DataVariableInfo varInfo = new DataVariableInfo(ldr);
this.type = checkSymbols(varInfo.getSymbols());
if (this.type == null)
this.varSymbols = varInfo.getSymbols();
else
this.varSymbols = this.type.getSymbols();
String ldrData = ldr.getContent();
LineTokenizer lt = new LineTokenizer(ldrData);
lt.nextLine(); // skip variable declaration
this.data = normalizeData(varSymbols.length,
ldrData.substring(lt.getPosition()));
this.length = this.data.length();
}
/**
* check for errornous symbols or standard symbols.
*
*/
private static DataType checkSymbols(String[] varSymbols)
throws JCAMPException {
if (varSymbols == null || varSymbols.length == 0)
throw new JCAMPException("bad variable declaration");
if (varSymbols.length == 2) {
if (varSymbols[0].equalsIgnoreCase("X")
&& varSymbols[1].equalsIgnoreCase("Y"))
return DataType.XY;
} else if (varSymbols.length == 3) {
if (varSymbols[0].equalsIgnoreCase("X")
&& varSymbols[1].equalsIgnoreCase("Y")
&& varSymbols[2].equalsIgnoreCase("W"))
return DataType.XYW;
}
return null;
}
/**
* get variable symbols.
*
* @return java.lang.String[]
*/
public final java.lang.String[] getSymbols() {
return varSymbols;
}
/**
* Insert the method's description here.
*
* @return com.creon.chem.jcamp.DataType
*/
public final DataType getType() {
return type;
}
/**
* returns <code>true</code> if more data is available.
*
* @return boolean
*/
@Override
public boolean hasMoreElements() {
return hasMoreGroups();
}
/**
* returns <code>true</code> if more data is available.
*
* @return boolean
*/
public boolean hasMoreGroups() {
if (pos < length - 1)
return true;
return false;
}
/**
* gets next data group.
*
* @return Object
*/
@Override
public AFFNGroup nextElement() {
try {
return nextGroup();
} catch (JCAMPException e) {
throw new java.util.NoSuchElementException(e.getMessage());
}
}
/**
* gets next data group.
*
* @return com.creon.chem.jcamp.AFFNGroup
*/
public AFFNGroup nextGroup() throws JCAMPException {
if (pos >= length)
throw new JCAMPException("parsed beyond end of AFFN block");
if (DataType.XY.equals(type))
return nextXYGroup();
if (DataType.XYW.equals(type))
return nextXYWGroup();
int n = varSymbols.length;
double[] values = new double[n];
for (int i = 0; i < n - 1; i++) {
int p = data.indexOf(",", pos);
if (p < 0)
throw new JCAMPException("missing data in AFFN block");
values[i] = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
}
int p = data.indexOf(";", pos);
if (p < 0)
throw new JCAMPException("extra data in AFFN block");
values[n - 1] = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
return new AFFNGroup(varSymbols, values);
}
/**
* gets next data group.
*
* @return com.creon.chem.jcamp.AFFNGroup
*/
private AFFNGroup nextXYGroup() throws JCAMPException {
double x;
double y;
int p = data.indexOf(',', pos);
if (p < 0) {
throw new JCAMPException("missing x data");
}
x = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
p = data.indexOf(';', pos);
if (p < 0)
throw new JCAMPException("missing y data");
y = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
return new AFFNGroup(x, y);
}
/**
* gets next data group.
*
* @return com.creon.chem.jcamp.AFFNGroup
*/
private AFFNGroup nextXYWGroup() throws JCAMPException {
double x;
double y;
double w;
int p = data.indexOf(',', pos);
if (p < 0)
throw new JCAMPException("missing x data");
x = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
p = data.indexOf(',', pos);
if (p < 0)
throw new JCAMPException("missing y data");
y = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
p = data.indexOf(';', pos);
if (p < 0)
throw new JCAMPException("missing w data");
w = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
return new AFFNGroup(x, y, w);
}
/**
* normalize data block in standard form: values are separated by ',',
* groups are separated by ';' whitespace is skipped
*
* @return java.lang.String
* @param orig
* java.lang.String
*/
private static String normalizeData(int groupLength, String orig)
throws JCAMPException {
StringBuilder normal = new StringBuilder();
boolean inNumber = false;
int j = 0;
for (int i = 0; i < orig.length(); i++) {
char c = orig.charAt(i);
if (Character.isWhitespace(c)) {
if (inNumber) {
inNumber = false;
j++;
if (j < groupLength)
normal.append(',');
else {
normal.append(';');
j = 0;
}
}
continue;
}
if (c == ';') {
if (inNumber) {
inNumber = false;
j++;
if (j < groupLength)
throw new JCAMPException("missing numbers in AFFN data");
if (j > groupLength)
throw new JCAMPException("extra numbers in AFFN data");
normal.append(';');
j = 0;
}
continue;
}
if (c == ',') {
if (inNumber) {
inNumber = false;
j++;
if (j >= groupLength)
throw new JCAMPException("extra commas in AFFN data");
normal.append(',');
}
continue;
}
if (Character.isDigit(c) || c == '.' || c == '+' || c == '-'
|| c == 'e' || c == 'E') {
normal.append(c);
inNumber = true;
} else {
throw new JCAMPException("unexpected character \'" + c
+ "\' in AFFN data");
}
}
normal.append(';');
return normal.toString();
}
}
| src/main/java/org/jcamp/parser/AFFNTokenizer.java | package org.jcamp.parser;
/**
* tokenizer (parser) that handles numeric data tables in AFFN format.
*
* @author Thomas Weber
*/
public class AFFNTokenizer
implements java.util.Enumeration {
private final DataType type;
private String data;
private final String[] varSymbols;
private int pos;
private int length;
/**
* AFFNTokenizer constructor comment.
*/
public AFFNTokenizer(String[] symbols, String data) throws JCAMPException {
super();
this.type = checkSymbols(symbols);
if (this.type == null)
this.varSymbols = symbols;
else
this.varSymbols = this.type.getSymbols();
this.data = normalizeData(varSymbols.length, data);
this.length = this.data.length();
}
/**
* AFFNTokenizer constructor comment.
*/
public AFFNTokenizer(JCAMPDataRecord ldr) throws JCAMPException {
super();
DataVariableInfo varInfo = new DataVariableInfo(ldr);
this.type = checkSymbols(varInfo.getSymbols());
if (this.type == null)
this.varSymbols = varInfo.getSymbols();
else
this.varSymbols = this.type.getSymbols();
String ldrData = ldr.getContent();
LineTokenizer lt = new LineTokenizer(ldrData);
lt.nextLine(); // skip variable declaration
this.data =
normalizeData(varSymbols.length, ldrData.substring(lt.getPosition()));
this.length = this.data.length();
}
/**
* check for errornous symbols or standard symbols.
*
*/
private static DataType checkSymbols(String[] varSymbols) throws JCAMPException {
if (varSymbols == null || varSymbols.length == 0)
throw new JCAMPException("bad variable declaration");
if (varSymbols.length == 2) {
if (varSymbols[0].equalsIgnoreCase("X") && varSymbols[1].equalsIgnoreCase("Y"))
return DataType.XY;
} else if (varSymbols.length == 3) {
if (varSymbols[0].equalsIgnoreCase("X")
&& varSymbols[1].equalsIgnoreCase("Y")
&& varSymbols[2].equalsIgnoreCase("W"))
return DataType.XYW;
}
return null;
}
/**
* get variable symbols.
*
* @return java.lang.String[]
*/
public final java.lang.String[] getSymbols() {
return varSymbols;
}
/**
* Insert the method's description here.
*
* @return com.creon.chem.jcamp.DataType
*/
public final DataType getType() {
return type;
}
/**
* returns <code>true</code> if more data is available.
*
* @return boolean
*/
public boolean hasMoreElements() {
return hasMoreGroups();
}
/**
* returns <code>true</code> if more data is available.
*
* @return boolean
*/
public boolean hasMoreGroups() {
if (pos < length-1)
return true;
return false;
}
/**
* gets next data group.
*
* @return Object
*/
public Object nextElement() {
try {
return nextGroup();
} catch (JCAMPException e) {
throw new java.util.NoSuchElementException(e.getMessage());
}
}
/**
* gets next data group.
*
* @return com.creon.chem.jcamp.AFFNGroup
*/
public AFFNGroup nextGroup() throws JCAMPException {
if (pos >= length)
throw new JCAMPException("parsed beyond end of AFFN block");
if (DataType.XY.equals(type))
return nextXYGroup();
if (DataType.XYW.equals(type))
return nextXYWGroup();
int n = varSymbols.length;
double[] values = new double[n];
for (int i = 0; i < n - 1; i++) {
int p = data.indexOf(",", pos);
if (p < 0)
throw new JCAMPException("missing data in AFFN block");
values[i] = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
}
int p = data.indexOf(";", pos);
if (p < 0)
throw new JCAMPException("extra data in AFFN block");
values[n - 1] = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
return new AFFNGroup(varSymbols, values);
}
/**
* gets next data group.
*
* @return com.creon.chem.jcamp.AFFNGroup
*/
private AFFNGroup nextXYGroup() throws JCAMPException {
double x;
double y;
int p = data.indexOf(',', pos);
if (p < 0) {
throw new JCAMPException("missing x data");
}
x = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
p = data.indexOf(';', pos);
if (p < 0)
throw new JCAMPException("missing y data");
y = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
return new AFFNGroup(x, y);
}
/**
* gets next data group.
*
* @return com.creon.chem.jcamp.AFFNGroup
*/
private AFFNGroup nextXYWGroup() throws JCAMPException {
double x;
double y;
double w;
int p = data.indexOf(',', pos);
if (p < 0)
throw new JCAMPException("missing x data");
x = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
p = data.indexOf(',', pos);
if (p < 0)
throw new JCAMPException("missing y data");
y = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
p = data.indexOf(';', pos);
if (p < 0)
throw new JCAMPException("missing w data");
w = Double.parseDouble(data.substring(pos, p));
pos = p + 1;
return new AFFNGroup(x, y, w);
}
/**
* normalize data block in standard form:
* values are separated by ',', groups are separated by ';'
* whitespace is skipped
*
* @return java.lang.String
* @param orig java.lang.String
*/
private static String normalizeData(int groupLength, String orig)
throws JCAMPException {
StringBuilder normal = new StringBuilder();
boolean inNumber = false;
int j = 0;
for (int i = 0; i < orig.length(); i++) {
char c = orig.charAt(i);
if (Character.isWhitespace(c)) {
if (inNumber) {
inNumber = false;
j++;
if (j<groupLength)
normal.append(',');
else {
normal.append(';');
j=0;
}
}
continue;
}
if (c == ';') {
if (inNumber) {
inNumber = false;
j++;
if (j<groupLength)
throw new JCAMPException("missing numbers in AFFN data");
if (j>groupLength)
throw new JCAMPException("extra numbers in AFFN data");
normal.append(';');
j=0;
}
continue;
}
if (c == ',') {
if (inNumber) {
inNumber = false;
j++;
if (j>=groupLength)
throw new JCAMPException("extra commas in AFFN data");
normal.append(',');
}
continue;
}
if (Character.isDigit(c)
|| c == '.'
|| c == '+'
|| c == '-'
|| c == 'e'
|| c == 'E') {
normal.append(c);
inNumber = true;
} else {
throw new JCAMPException("unexpected character \'" + c + "\' in AFFN data");
}
}
normal.append(';');
return normal.toString();
}
}
| Fix some generics. | src/main/java/org/jcamp/parser/AFFNTokenizer.java | Fix some generics. | <ide><path>rc/main/java/org/jcamp/parser/AFFNTokenizer.java
<ide> package org.jcamp.parser;
<ide>
<ide> /**
<del> * tokenizer (parser) that handles numeric data tables in AFFN format.
<add> * {@code AFFNTokenizer} handles numeric data tables in AFFN format.
<add> *
<ide> *
<ide> * @author Thomas Weber
<add> * @author <a href="mailto:[email protected]">Alexander
<add> * Kerner</a>
<ide> */
<del>public class AFFNTokenizer
<del> implements java.util.Enumeration {
<del>
<del> private final DataType type;
<del> private String data;
<del> private final String[] varSymbols;
<del> private int pos;
<del> private int length;
<del> /**
<del> * AFFNTokenizer constructor comment.
<del> */
<del> public AFFNTokenizer(String[] symbols, String data) throws JCAMPException {
<del> super();
<del> this.type = checkSymbols(symbols);
<del> if (this.type == null)
<del> this.varSymbols = symbols;
<del> else
<del> this.varSymbols = this.type.getSymbols();
<del> this.data = normalizeData(varSymbols.length, data);
<del> this.length = this.data.length();
<del> }
<del> /**
<del> * AFFNTokenizer constructor comment.
<del> */
<del> public AFFNTokenizer(JCAMPDataRecord ldr) throws JCAMPException {
<del> super();
<del> DataVariableInfo varInfo = new DataVariableInfo(ldr);
<del> this.type = checkSymbols(varInfo.getSymbols());
<del> if (this.type == null)
<del> this.varSymbols = varInfo.getSymbols();
<del> else
<del> this.varSymbols = this.type.getSymbols();
<del> String ldrData = ldr.getContent();
<del> LineTokenizer lt = new LineTokenizer(ldrData);
<del> lt.nextLine(); // skip variable declaration
<del> this.data =
<del> normalizeData(varSymbols.length, ldrData.substring(lt.getPosition()));
<del> this.length = this.data.length();
<del> }
<del> /**
<del> * check for errornous symbols or standard symbols.
<del> *
<del> */
<del> private static DataType checkSymbols(String[] varSymbols) throws JCAMPException {
<del> if (varSymbols == null || varSymbols.length == 0)
<del> throw new JCAMPException("bad variable declaration");
<del> if (varSymbols.length == 2) {
<del> if (varSymbols[0].equalsIgnoreCase("X") && varSymbols[1].equalsIgnoreCase("Y"))
<del> return DataType.XY;
<del> } else if (varSymbols.length == 3) {
<del> if (varSymbols[0].equalsIgnoreCase("X")
<del> && varSymbols[1].equalsIgnoreCase("Y")
<del> && varSymbols[2].equalsIgnoreCase("W"))
<del> return DataType.XYW;
<del> }
<del> return null;
<del> }
<del> /**
<del> * get variable symbols.
<del> *
<del> * @return java.lang.String[]
<del> */
<del> public final java.lang.String[] getSymbols() {
<del> return varSymbols;
<del> }
<del> /**
<del> * Insert the method's description here.
<del> *
<del> * @return com.creon.chem.jcamp.DataType
<del> */
<del> public final DataType getType() {
<del> return type;
<del> }
<del> /**
<del> * returns <code>true</code> if more data is available.
<del> *
<del> * @return boolean
<del> */
<del> public boolean hasMoreElements() {
<del> return hasMoreGroups();
<del> }
<del> /**
<del> * returns <code>true</code> if more data is available.
<del> *
<del> * @return boolean
<del> */
<del> public boolean hasMoreGroups() {
<del> if (pos < length-1)
<del> return true;
<del> return false;
<del> }
<del> /**
<del> * gets next data group.
<del> *
<del> * @return Object
<del> */
<del> public Object nextElement() {
<del> try {
<del> return nextGroup();
<del> } catch (JCAMPException e) {
<del> throw new java.util.NoSuchElementException(e.getMessage());
<del> }
<del> }
<del> /**
<del> * gets next data group.
<del> *
<del> * @return com.creon.chem.jcamp.AFFNGroup
<del> */
<del> public AFFNGroup nextGroup() throws JCAMPException {
<del> if (pos >= length)
<del> throw new JCAMPException("parsed beyond end of AFFN block");
<del> if (DataType.XY.equals(type))
<del> return nextXYGroup();
<del> if (DataType.XYW.equals(type))
<del> return nextXYWGroup();
<del> int n = varSymbols.length;
<del> double[] values = new double[n];
<del> for (int i = 0; i < n - 1; i++) {
<del> int p = data.indexOf(",", pos);
<del> if (p < 0)
<del> throw new JCAMPException("missing data in AFFN block");
<del> values[i] = Double.parseDouble(data.substring(pos, p));
<del> pos = p + 1;
<del> }
<del>
<del> int p = data.indexOf(";", pos);
<del> if (p < 0)
<del> throw new JCAMPException("extra data in AFFN block");
<del> values[n - 1] = Double.parseDouble(data.substring(pos, p));
<del> pos = p + 1;
<del> return new AFFNGroup(varSymbols, values);
<del>
<del> }
<del> /**
<del> * gets next data group.
<del> *
<del> * @return com.creon.chem.jcamp.AFFNGroup
<del> */
<del> private AFFNGroup nextXYGroup() throws JCAMPException {
<del> double x;
<del> double y;
<del> int p = data.indexOf(',', pos);
<del> if (p < 0) {
<del> throw new JCAMPException("missing x data");
<del> }
<del> x = Double.parseDouble(data.substring(pos, p));
<del> pos = p + 1;
<del> p = data.indexOf(';', pos);
<del> if (p < 0)
<del> throw new JCAMPException("missing y data");
<del> y = Double.parseDouble(data.substring(pos, p));
<del> pos = p + 1;
<del> return new AFFNGroup(x, y);
<del> }
<del> /**
<del> * gets next data group.
<del> *
<del> * @return com.creon.chem.jcamp.AFFNGroup
<del> */
<del> private AFFNGroup nextXYWGroup() throws JCAMPException {
<del> double x;
<del> double y;
<del> double w;
<del> int p = data.indexOf(',', pos);
<del> if (p < 0)
<del> throw new JCAMPException("missing x data");
<del> x = Double.parseDouble(data.substring(pos, p));
<del> pos = p + 1;
<del> p = data.indexOf(',', pos);
<del> if (p < 0)
<del> throw new JCAMPException("missing y data");
<del> y = Double.parseDouble(data.substring(pos, p));
<del> pos = p + 1;
<del> p = data.indexOf(';', pos);
<del> if (p < 0)
<del> throw new JCAMPException("missing w data");
<del> w = Double.parseDouble(data.substring(pos, p));
<del> pos = p + 1;
<del> return new AFFNGroup(x, y, w);
<del> }
<del> /**
<del> * normalize data block in standard form:
<del> * values are separated by ',', groups are separated by ';'
<del> * whitespace is skipped
<del> *
<del> * @return java.lang.String
<del> * @param orig java.lang.String
<del> */
<del> private static String normalizeData(int groupLength, String orig)
<del> throws JCAMPException {
<del> StringBuilder normal = new StringBuilder();
<del> boolean inNumber = false;
<del> int j = 0;
<del> for (int i = 0; i < orig.length(); i++) {
<del> char c = orig.charAt(i);
<del> if (Character.isWhitespace(c)) {
<del> if (inNumber) {
<del> inNumber = false;
<del> j++;
<del> if (j<groupLength)
<del> normal.append(',');
<del> else {
<del> normal.append(';');
<del> j=0;
<del> }
<del> }
<del> continue;
<del> }
<del> if (c == ';') {
<del> if (inNumber) {
<del> inNumber = false;
<del> j++;
<del> if (j<groupLength)
<del> throw new JCAMPException("missing numbers in AFFN data");
<del> if (j>groupLength)
<del> throw new JCAMPException("extra numbers in AFFN data");
<del> normal.append(';');
<del> j=0;
<del> }
<del> continue;
<del> }
<del> if (c == ',') {
<del> if (inNumber) {
<del> inNumber = false;
<del> j++;
<del> if (j>=groupLength)
<del> throw new JCAMPException("extra commas in AFFN data");
<del> normal.append(',');
<del> }
<del> continue;
<del> }
<del> if (Character.isDigit(c)
<del> || c == '.'
<del> || c == '+'
<del> || c == '-'
<del> || c == 'e'
<del> || c == 'E') {
<del> normal.append(c);
<del> inNumber = true;
<del> } else {
<del> throw new JCAMPException("unexpected character \'" + c + "\' in AFFN data");
<del> }
<del> }
<del> normal.append(';');
<del> return normal.toString();
<del> }
<add>public class AFFNTokenizer implements java.util.Enumeration<AFFNGroup> {
<add>
<add> private final DataType type;
<add> private String data;
<add> private final String[] varSymbols;
<add> private int pos;
<add> private int length;
<add>
<add> /**
<add> * AFFNTokenizer constructor comment.
<add> */
<add> public AFFNTokenizer(String[] symbols, String data) throws JCAMPException {
<add> super();
<add> this.type = checkSymbols(symbols);
<add> if (this.type == null)
<add> this.varSymbols = symbols;
<add> else
<add> this.varSymbols = this.type.getSymbols();
<add> this.data = normalizeData(varSymbols.length, data);
<add> this.length = this.data.length();
<add> }
<add>
<add> /**
<add> * AFFNTokenizer constructor comment.
<add> */
<add> public AFFNTokenizer(JCAMPDataRecord ldr) throws JCAMPException {
<add> super();
<add> DataVariableInfo varInfo = new DataVariableInfo(ldr);
<add> this.type = checkSymbols(varInfo.getSymbols());
<add> if (this.type == null)
<add> this.varSymbols = varInfo.getSymbols();
<add> else
<add> this.varSymbols = this.type.getSymbols();
<add> String ldrData = ldr.getContent();
<add> LineTokenizer lt = new LineTokenizer(ldrData);
<add> lt.nextLine(); // skip variable declaration
<add> this.data = normalizeData(varSymbols.length,
<add> ldrData.substring(lt.getPosition()));
<add> this.length = this.data.length();
<add> }
<add>
<add> /**
<add> * check for errornous symbols or standard symbols.
<add> *
<add> */
<add> private static DataType checkSymbols(String[] varSymbols)
<add> throws JCAMPException {
<add> if (varSymbols == null || varSymbols.length == 0)
<add> throw new JCAMPException("bad variable declaration");
<add> if (varSymbols.length == 2) {
<add> if (varSymbols[0].equalsIgnoreCase("X")
<add> && varSymbols[1].equalsIgnoreCase("Y"))
<add> return DataType.XY;
<add> } else if (varSymbols.length == 3) {
<add> if (varSymbols[0].equalsIgnoreCase("X")
<add> && varSymbols[1].equalsIgnoreCase("Y")
<add> && varSymbols[2].equalsIgnoreCase("W"))
<add> return DataType.XYW;
<add> }
<add> return null;
<add> }
<add>
<add> /**
<add> * get variable symbols.
<add> *
<add> * @return java.lang.String[]
<add> */
<add> public final java.lang.String[] getSymbols() {
<add> return varSymbols;
<add> }
<add>
<add> /**
<add> * Insert the method's description here.
<add> *
<add> * @return com.creon.chem.jcamp.DataType
<add> */
<add> public final DataType getType() {
<add> return type;
<add> }
<add>
<add> /**
<add> * returns <code>true</code> if more data is available.
<add> *
<add> * @return boolean
<add> */
<add> @Override
<add> public boolean hasMoreElements() {
<add> return hasMoreGroups();
<add> }
<add>
<add> /**
<add> * returns <code>true</code> if more data is available.
<add> *
<add> * @return boolean
<add> */
<add> public boolean hasMoreGroups() {
<add> if (pos < length - 1)
<add> return true;
<add> return false;
<add> }
<add>
<add> /**
<add> * gets next data group.
<add> *
<add> * @return Object
<add> */
<add> @Override
<add> public AFFNGroup nextElement() {
<add> try {
<add> return nextGroup();
<add> } catch (JCAMPException e) {
<add> throw new java.util.NoSuchElementException(e.getMessage());
<add> }
<add> }
<add>
<add> /**
<add> * gets next data group.
<add> *
<add> * @return com.creon.chem.jcamp.AFFNGroup
<add> */
<add> public AFFNGroup nextGroup() throws JCAMPException {
<add> if (pos >= length)
<add> throw new JCAMPException("parsed beyond end of AFFN block");
<add> if (DataType.XY.equals(type))
<add> return nextXYGroup();
<add> if (DataType.XYW.equals(type))
<add> return nextXYWGroup();
<add> int n = varSymbols.length;
<add> double[] values = new double[n];
<add> for (int i = 0; i < n - 1; i++) {
<add> int p = data.indexOf(",", pos);
<add> if (p < 0)
<add> throw new JCAMPException("missing data in AFFN block");
<add> values[i] = Double.parseDouble(data.substring(pos, p));
<add> pos = p + 1;
<add> }
<add>
<add> int p = data.indexOf(";", pos);
<add> if (p < 0)
<add> throw new JCAMPException("extra data in AFFN block");
<add> values[n - 1] = Double.parseDouble(data.substring(pos, p));
<add> pos = p + 1;
<add> return new AFFNGroup(varSymbols, values);
<add>
<add> }
<add>
<add> /**
<add> * gets next data group.
<add> *
<add> * @return com.creon.chem.jcamp.AFFNGroup
<add> */
<add> private AFFNGroup nextXYGroup() throws JCAMPException {
<add> double x;
<add> double y;
<add> int p = data.indexOf(',', pos);
<add> if (p < 0) {
<add> throw new JCAMPException("missing x data");
<add> }
<add> x = Double.parseDouble(data.substring(pos, p));
<add> pos = p + 1;
<add> p = data.indexOf(';', pos);
<add> if (p < 0)
<add> throw new JCAMPException("missing y data");
<add> y = Double.parseDouble(data.substring(pos, p));
<add> pos = p + 1;
<add> return new AFFNGroup(x, y);
<add> }
<add>
<add> /**
<add> * gets next data group.
<add> *
<add> * @return com.creon.chem.jcamp.AFFNGroup
<add> */
<add> private AFFNGroup nextXYWGroup() throws JCAMPException {
<add> double x;
<add> double y;
<add> double w;
<add> int p = data.indexOf(',', pos);
<add> if (p < 0)
<add> throw new JCAMPException("missing x data");
<add> x = Double.parseDouble(data.substring(pos, p));
<add> pos = p + 1;
<add> p = data.indexOf(',', pos);
<add> if (p < 0)
<add> throw new JCAMPException("missing y data");
<add> y = Double.parseDouble(data.substring(pos, p));
<add> pos = p + 1;
<add> p = data.indexOf(';', pos);
<add> if (p < 0)
<add> throw new JCAMPException("missing w data");
<add> w = Double.parseDouble(data.substring(pos, p));
<add> pos = p + 1;
<add> return new AFFNGroup(x, y, w);
<add> }
<add>
<add> /**
<add> * normalize data block in standard form: values are separated by ',',
<add> * groups are separated by ';' whitespace is skipped
<add> *
<add> * @return java.lang.String
<add> * @param orig
<add> * java.lang.String
<add> */
<add> private static String normalizeData(int groupLength, String orig)
<add> throws JCAMPException {
<add> StringBuilder normal = new StringBuilder();
<add> boolean inNumber = false;
<add> int j = 0;
<add> for (int i = 0; i < orig.length(); i++) {
<add> char c = orig.charAt(i);
<add> if (Character.isWhitespace(c)) {
<add> if (inNumber) {
<add> inNumber = false;
<add> j++;
<add> if (j < groupLength)
<add> normal.append(',');
<add> else {
<add> normal.append(';');
<add> j = 0;
<add> }
<add> }
<add> continue;
<add> }
<add> if (c == ';') {
<add> if (inNumber) {
<add> inNumber = false;
<add> j++;
<add> if (j < groupLength)
<add> throw new JCAMPException("missing numbers in AFFN data");
<add> if (j > groupLength)
<add> throw new JCAMPException("extra numbers in AFFN data");
<add> normal.append(';');
<add> j = 0;
<add> }
<add> continue;
<add> }
<add> if (c == ',') {
<add> if (inNumber) {
<add> inNumber = false;
<add> j++;
<add> if (j >= groupLength)
<add> throw new JCAMPException("extra commas in AFFN data");
<add> normal.append(',');
<add> }
<add> continue;
<add> }
<add> if (Character.isDigit(c) || c == '.' || c == '+' || c == '-'
<add> || c == 'e' || c == 'E') {
<add> normal.append(c);
<add> inNumber = true;
<add> } else {
<add> throw new JCAMPException("unexpected character \'" + c
<add> + "\' in AFFN data");
<add> }
<add> }
<add> normal.append(';');
<add> return normal.toString();
<add> }
<ide> } |
|
Java | epl-1.0 | 4d3c904a35a3296bd458731b1c02d1add481f628 | 0 | jcryptool/crypto,jcryptool/crypto,tassadarius/crypto,tassadarius/crypto | //-----BEGIN DISCLAIMER-----
/*******************************************************************************
* Copyright (c) 2013, 2020 JCrypTool Team and Contributors
*
* 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
*******************************************************************************/
//-----END DISCLAIMER-----
package org.jcryptool.analysis.substitution.views;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.jcryptool.analysis.substitution.Activator;
import org.jcryptool.analysis.substitution.calc.TextStatistic;
import org.jcryptool.analysis.substitution.ui.modules.SubstitutionAnalysisConfigPanel;
import org.jcryptool.analysis.substitution.ui.modules.SubstitutionAnalysisPanel;
import org.jcryptool.analysis.substitution.views.SubstitutionAnalysisView.State.Step;
import org.jcryptool.core.operations.alphabets.AbstractAlphabet;
import org.jcryptool.core.util.ui.auto.LayoutAdvisor;
import org.jcryptool.core.util.ui.auto.SmoothScroller;
/**
* This sample class demonstrates how to plug-in a new
* workbench view. The view shows data obtained from the
* model. The sample creates a dummy model on the fly,
* but a real implementation would connect to the model
* available either in this or another plug-in (e.g. the workspace).
* The view is connected to the model using a content provider.
* <p>
* The view uses a label provider to define how model
* objects should be presented in the view. Each
* view can present the same model objects using
* different labels and icons, if needed. Alternatively,
* a single label provider can be shared between views
* in order to ensure that objects of the same type are
* presented in the same way everywhere.
* <p>
*/
public class SubstitutionAnalysisView extends ViewPart {
private Composite mainComposite;
private State state;
private Composite mainPanel;
private SubstitutionAnalysisConfigPanel configPanel;
private ScrolledComposite scrolledComposite;
/*
* The content provider class is responsible for
* providing objects to the view. It can wrap
* existing objects in adapters or simply return
* objects as-is. These objects may be sensitive
* to the current input of the view, or ignore
* it and always show the same content
* (like Task List, for example).
*/
public static class State {
private Step step;
public enum Step {
CONFIG, ANALYSIS
}
public State(Step step) {
this.step = step;
}
public Step getStep() {
return step;
}
}
/**
* The constructor.
*/
public SubstitutionAnalysisView() {
super();
state = new State(State.Step.CONFIG);
}
private Composite getMainComposite() {
return mainComposite;
}
private ScrolledComposite getScrolledComposite() {
return scrolledComposite;
}
@Override
public void createPartControl(Composite parent) {
scrolledComposite = new ScrolledComposite(parent,SWT.H_SCROLL | SWT.V_SCROLL);
scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true));
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
//FIXME: TODO
mainComposite = new Composite(scrolledComposite, SWT.NONE);
mainComposite.setLayout(new GridLayout());
mainComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
scrolledComposite.setContent(mainComposite);
createAppropriatePanel(state);
// Set size of composite,
// because if not the composite will be fully extended
scrolledComposite.setMinSize(mainComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
LayoutAdvisor.addPreLayoutRootComposite(scrolledComposite);
// This makes the ScrolledComposite scrolling, when the mouse
// is on a Text with one or more of the following tags: SWT.READ_ONLY,
// SWT.V_SCROLL or SWT-H_SCROLL.
SmoothScroller.scrollSmooth(scrolledComposite);
// Register the context help
PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, Activator.PLUGIN_ID + ".substitutionHelpID"); //$NON-NLS-1$
}
private void createAppropriatePanel(State state) {
if(mainPanel != null && !mainPanel.isDisposed()) {
mainPanel.dispose();
}
if(state.getStep() == Step.CONFIG) {
SubstitutionAnalysisConfigPanel panel = createConfigPanel(mainComposite);
setMainPanel(panel);
this.configPanel = panel;
} else if(state.getStep() == Step.ANALYSIS) {
SubstitutionAnalysisConfigPanel.State data = this.configPanel.getState();
SubstitutionAnalysisPanel panel = createAnalysisPanel(mainComposite, data.getTextForAnalysis(), data.getAlphabet(), data.getStatistics());
setMainPanel(panel);
} else {
throw new RuntimeException("unsupported state in substitution analysis"); //$NON-NLS-1$
}
}
private SubstitutionAnalysisPanel createAnalysisPanel(Composite mainComposite, String textForAnalysis, AbstractAlphabet alphabet,
TextStatistic statistics) {
SubstitutionAnalysisPanel substitutionAnalysisPanel = new SubstitutionAnalysisPanel(mainComposite, SWT.NONE, textForAnalysis, alphabet, statistics, generateUpperLowerCaseMode(alphabet));
substitutionAnalysisPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
return substitutionAnalysisPanel;
}
private static boolean generateUpperLowerCaseMode(AbstractAlphabet alphabet) {
String ref = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$NON-NLS-1$
LinkedList<Character> refList = new LinkedList<Character>();
for(char c: ref.toCharArray()) refList.add(c);
Set<Character> compareAlphaSet = new HashSet<Character>();
for(char c: alphabet.getCharacterSet()) compareAlphaSet.add(c);
double compareValue = TextStatistic.compareTwoAlphabets(refList, compareAlphaSet);
if(compareValue > 0.9) return true;
return false;
}
private void setMainPanel(Composite panel) {
this.mainPanel = panel;
getMainComposite().layout(new Control[]{this.mainPanel});
}
private SubstitutionAnalysisConfigPanel createConfigPanel(Composite parent) {
final SubstitutionAnalysisConfigPanel panel = new SubstitutionAnalysisConfigPanel(parent, SWT.NONE);
panel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
panel.addObserver(new Observer() {
@Override
public void update(Observable o, Object arg) {
if(panel.getState().isReady()) {
state = new State(State.Step.ANALYSIS);
createAppropriatePanel(state);
}
}
});
return panel;
}
public void resetAnalysis() {
this.state = new State(Step.CONFIG);
createAppropriatePanel(state);
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
getMainComposite().setFocus();
}
} | org.jcryptool.analysis.substitution/src/org/jcryptool/analysis/substitution/views/SubstitutionAnalysisView.java | //-----BEGIN DISCLAIMER-----
/*******************************************************************************
* Copyright (c) 2013, 2020 JCrypTool Team and Contributors
*
* 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
*******************************************************************************/
//-----END DISCLAIMER-----
package org.jcryptool.analysis.substitution.views;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.jcryptool.analysis.substitution.Activator;
import org.jcryptool.analysis.substitution.calc.TextStatistic;
import org.jcryptool.analysis.substitution.ui.modules.SubstitutionAnalysisConfigPanel;
import org.jcryptool.analysis.substitution.ui.modules.SubstitutionAnalysisPanel;
import org.jcryptool.analysis.substitution.views.SubstitutionAnalysisView.State.Step;
import org.jcryptool.core.operations.alphabets.AbstractAlphabet;
import org.jcryptool.core.util.ui.auto.SmoothScroller;
/**
* This sample class demonstrates how to plug-in a new
* workbench view. The view shows data obtained from the
* model. The sample creates a dummy model on the fly,
* but a real implementation would connect to the model
* available either in this or another plug-in (e.g. the workspace).
* The view is connected to the model using a content provider.
* <p>
* The view uses a label provider to define how model
* objects should be presented in the view. Each
* view can present the same model objects using
* different labels and icons, if needed. Alternatively,
* a single label provider can be shared between views
* in order to ensure that objects of the same type are
* presented in the same way everywhere.
* <p>
*/
public class SubstitutionAnalysisView extends ViewPart {
private Composite mainComposite;
private State state;
private Composite mainPanel;
private SubstitutionAnalysisConfigPanel configPanel;
private ScrolledComposite scrolledComposite;
/*
* The content provider class is responsible for
* providing objects to the view. It can wrap
* existing objects in adapters or simply return
* objects as-is. These objects may be sensitive
* to the current input of the view, or ignore
* it and always show the same content
* (like Task List, for example).
*/
public static class State {
private Step step;
public enum Step {
CONFIG, ANALYSIS
}
public State(Step step) {
this.step = step;
}
public Step getStep() {
return step;
}
}
/**
* The constructor.
*/
public SubstitutionAnalysisView() {
super();
state = new State(State.Step.CONFIG);
}
private Composite getMainComposite() {
return mainComposite;
}
private ScrolledComposite getScrolledComposite() {
return scrolledComposite;
}
@Override
public void createPartControl(Composite parent) {
scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL);
//scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
scrolledComposite.setExpandHorizontal(false);
scrolledComposite.setExpandVertical(true);
// This makes the ScrolledComposite scrolling, when the mouse
// is on a Text with one or more of the following tags: SWT.READ_ONLY,
// SWT.V_SCROLL or SWT-H_SCROLL.
//FIXME: TODO
mainComposite = new Composite(scrolledComposite, SWT.NONE);
mainComposite.setLayout(new GridLayout());
mainComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
scrolledComposite.setContent(mainComposite);
createAppropriatePanel(state);
PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, Activator.PLUGIN_ID + ".substitutionHelpID"); //$NON-NLS-1$
SmoothScroller.scrollSmooth(scrolledComposite);
}
private void createAppropriatePanel(State state) {
if(mainPanel != null && !mainPanel.isDisposed()) {
mainPanel.dispose();
}
if(state.getStep() == Step.CONFIG) {
//scrolledComposite = new ScrolledComposite(mainComposite, SWT.H_SCROLL | SWT.V_SCROLL);
//scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
//scrolledComposite.setExpandHorizontal(true);
//scrolledComposite.setExpandVertical(true);
SubstitutionAnalysisConfigPanel panel = createConfigPanel(mainComposite);
setMainPanel(panel);
this.configPanel = panel;
//scrolledComposite.setContent(panel);
} else if(state.getStep() == Step.ANALYSIS) {
//scrolledComposite.dispose();
SubstitutionAnalysisConfigPanel.State data = this.configPanel.getState();
SubstitutionAnalysisPanel panel = createAnalysisPanel(mainComposite, data.getTextForAnalysis(), data.getAlphabet(), data.getStatistics());
setMainPanel(panel);
} else {
throw new RuntimeException("unsupported state in substitution analysis"); //$NON-NLS-1$
}
}
private SubstitutionAnalysisPanel createAnalysisPanel(Composite mainComposite, String textForAnalysis, AbstractAlphabet alphabet,
TextStatistic statistics) {
SubstitutionAnalysisPanel substitutionAnalysisPanel = new SubstitutionAnalysisPanel(mainComposite, SWT.NONE, textForAnalysis, alphabet, statistics, generateUpperLowerCaseMode(alphabet));
substitutionAnalysisPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
return substitutionAnalysisPanel;
}
private static boolean generateUpperLowerCaseMode(AbstractAlphabet alphabet) {
String ref = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$NON-NLS-1$
LinkedList<Character> refList = new LinkedList<Character>();
for(char c: ref.toCharArray()) refList.add(c);
Set<Character> compareAlphaSet = new HashSet<Character>();
for(char c: alphabet.getCharacterSet()) compareAlphaSet.add(c);
double compareValue = TextStatistic.compareTwoAlphabets(refList, compareAlphaSet);
if(compareValue > 0.9) return true;
return false;
}
private void setMainPanel(Composite panel) {
this.mainPanel = panel;
getMainComposite().layout(new Control[]{this.mainPanel});
}
private SubstitutionAnalysisConfigPanel createConfigPanel(Composite parent) {
final SubstitutionAnalysisConfigPanel panel = new SubstitutionAnalysisConfigPanel(parent, SWT.NONE);
panel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
panel.addObserver(new Observer() {
@Override
public void update(Observable o, Object arg) {
if(panel.getState().isReady()) {
state = new State(State.Step.ANALYSIS);
createAppropriatePanel(state);
}
}
});
return panel;
}
public void resetAnalysis() {
this.state = new State(Step.CONFIG);
createAppropriatePanel(state);
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
getMainComposite().setFocus();
}
} | Unfinished changes in substitution analysis scrollbar | org.jcryptool.analysis.substitution/src/org/jcryptool/analysis/substitution/views/SubstitutionAnalysisView.java | Unfinished changes in substitution analysis scrollbar | <ide><path>rg.jcryptool.analysis.substitution/src/org/jcryptool/analysis/substitution/views/SubstitutionAnalysisView.java
<ide> import org.jcryptool.analysis.substitution.ui.modules.SubstitutionAnalysisPanel;
<ide> import org.jcryptool.analysis.substitution.views.SubstitutionAnalysisView.State.Step;
<ide> import org.jcryptool.core.operations.alphabets.AbstractAlphabet;
<add>import org.jcryptool.core.util.ui.auto.LayoutAdvisor;
<ide> import org.jcryptool.core.util.ui.auto.SmoothScroller;
<ide>
<ide>
<ide> @Override
<ide> public void createPartControl(Composite parent) {
<ide>
<del> scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL);
<del> //scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
<del> scrolledComposite.setExpandHorizontal(false);
<add> scrolledComposite = new ScrolledComposite(parent,SWT.H_SCROLL | SWT.V_SCROLL);
<add> scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true));
<add> scrolledComposite.setExpandHorizontal(true);
<ide> scrolledComposite.setExpandVertical(true);
<add>
<add>
<add> //FIXME: TODO
<add>
<add> mainComposite = new Composite(scrolledComposite, SWT.NONE);
<add> mainComposite.setLayout(new GridLayout());
<add> mainComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
<add>
<add> scrolledComposite.setContent(mainComposite);
<add>
<add> createAppropriatePanel(state);
<add>
<add>
<add> // Set size of composite,
<add> // because if not the composite will be fully extended
<add> scrolledComposite.setMinSize(mainComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
<add> LayoutAdvisor.addPreLayoutRootComposite(scrolledComposite);
<add>
<ide>
<ide> // This makes the ScrolledComposite scrolling, when the mouse
<ide> // is on a Text with one or more of the following tags: SWT.READ_ONLY,
<ide> // SWT.V_SCROLL or SWT-H_SCROLL.
<del>
<del> //FIXME: TODO
<del>
<del> mainComposite = new Composite(scrolledComposite, SWT.NONE);
<del> mainComposite.setLayout(new GridLayout());
<del> mainComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
<del>
<del> scrolledComposite.setContent(mainComposite);
<del> createAppropriatePanel(state);
<del>
<add>
<add> SmoothScroller.scrollSmooth(scrolledComposite);
<add>
<add>
<add> // Register the context help
<ide> PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, Activator.PLUGIN_ID + ".substitutionHelpID"); //$NON-NLS-1$
<del> SmoothScroller.scrollSmooth(scrolledComposite);
<add>
<ide> }
<ide>
<ide> private void createAppropriatePanel(State state) {
<ide> mainPanel.dispose();
<ide> }
<ide> if(state.getStep() == Step.CONFIG) {
<del>
<del>
<del> //scrolledComposite = new ScrolledComposite(mainComposite, SWT.H_SCROLL | SWT.V_SCROLL);
<del> //scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
<del> //scrolledComposite.setExpandHorizontal(true);
<del> //scrolledComposite.setExpandVertical(true);
<del>
<del>
<ide> SubstitutionAnalysisConfigPanel panel = createConfigPanel(mainComposite);
<ide> setMainPanel(panel);
<ide> this.configPanel = panel;
<del> //scrolledComposite.setContent(panel);
<ide> } else if(state.getStep() == Step.ANALYSIS) {
<del> //scrolledComposite.dispose();
<ide> SubstitutionAnalysisConfigPanel.State data = this.configPanel.getState();
<ide> SubstitutionAnalysisPanel panel = createAnalysisPanel(mainComposite, data.getTextForAnalysis(), data.getAlphabet(), data.getStatistics());
<ide> setMainPanel(panel);
<ide>
<ide> private SubstitutionAnalysisConfigPanel createConfigPanel(Composite parent) {
<ide> final SubstitutionAnalysisConfigPanel panel = new SubstitutionAnalysisConfigPanel(parent, SWT.NONE);
<del> panel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
<add> panel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
<ide> panel.addObserver(new Observer() {
<ide>
<ide> @Override |
|
Java | apache-2.0 | 3b769a68a04fe40decbf027bf526cd142eaa5df2 | 0 | rinde/vanLon16-JAAMAS-code,rinde/vanLon17-JAAMAS-code,rinde/vanLon16-JAAMAS-code,rinde/vanLon17-JAAMAS-code,rinde/vanLon16-JAAMAS-code,rinde/vanLon16-AAMAS-code,rinde/vanLon16-AAMAS-code,rinde/vanLon17-JAAMAS-code | /*
* Copyright (C) 2015 Rinde van Lon, iMinds-DistriNet, KU Leuven
*
* 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.github.rinde.aamas16;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verifyNotNull;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
import com.github.rinde.logistics.pdptw.mas.TruckFactory.DefaultTruckFactory;
import com.github.rinde.logistics.pdptw.mas.comm.AuctionCommModel;
import com.github.rinde.logistics.pdptw.mas.comm.AuctionPanel;
import com.github.rinde.logistics.pdptw.mas.comm.AuctionStopConditions;
import com.github.rinde.logistics.pdptw.mas.comm.DoubleBid;
import com.github.rinde.logistics.pdptw.mas.comm.RtSolverBidder;
import com.github.rinde.logistics.pdptw.mas.route.RtSolverRoutePlanner;
import com.github.rinde.logistics.pdptw.solver.CheapestInsertionHeuristic;
import com.github.rinde.logistics.pdptw.solver.Opt2;
import com.github.rinde.rinsim.central.rt.RealtimeSolver;
import com.github.rinde.rinsim.central.rt.RtCentral;
import com.github.rinde.rinsim.central.rt.RtSolverModel;
import com.github.rinde.rinsim.central.rt.RtSolverPanel;
import com.github.rinde.rinsim.central.rt.SolverToRealtimeAdapter;
import com.github.rinde.rinsim.core.Simulator;
import com.github.rinde.rinsim.core.SimulatorAPI;
import com.github.rinde.rinsim.core.model.pdp.Parcel;
import com.github.rinde.rinsim.core.model.time.MeasuredDeviation;
import com.github.rinde.rinsim.core.model.time.RealtimeClockLogger;
import com.github.rinde.rinsim.core.model.time.RealtimeClockLogger.LogEntry;
import com.github.rinde.rinsim.core.model.time.TimeModel;
import com.github.rinde.rinsim.experiment.CommandLineProgress;
import com.github.rinde.rinsim.experiment.Experiment;
import com.github.rinde.rinsim.experiment.Experiment.Builder;
import com.github.rinde.rinsim.experiment.Experiment.SimArgs;
import com.github.rinde.rinsim.experiment.ExperimentResults;
import com.github.rinde.rinsim.experiment.MASConfiguration;
import com.github.rinde.rinsim.experiment.PostProcessor;
import com.github.rinde.rinsim.experiment.PostProcessors;
import com.github.rinde.rinsim.io.FileProvider;
import com.github.rinde.rinsim.pdptw.common.AddParcelEvent;
import com.github.rinde.rinsim.pdptw.common.AddVehicleEvent;
import com.github.rinde.rinsim.pdptw.common.RouteFollowingVehicle;
import com.github.rinde.rinsim.pdptw.common.RouteRenderer;
import com.github.rinde.rinsim.pdptw.common.StatisticsDTO;
import com.github.rinde.rinsim.pdptw.common.TimeLinePanel;
import com.github.rinde.rinsim.scenario.Scenario;
import com.github.rinde.rinsim.scenario.ScenarioIO;
import com.github.rinde.rinsim.scenario.StopConditions;
import com.github.rinde.rinsim.scenario.TimedEventHandler;
import com.github.rinde.rinsim.scenario.gendreau06.Gendreau06ObjectiveFunction;
import com.github.rinde.rinsim.scenario.gendreau06.Gendreau06Parser;
import com.github.rinde.rinsim.ui.View;
import com.github.rinde.rinsim.ui.renderers.PDPModelRenderer;
import com.github.rinde.rinsim.ui.renderers.PlaneRoadModelRenderer;
import com.github.rinde.rinsim.ui.renderers.RoadUserRenderer;
import com.github.rinde.rinsim.util.StochasticSupplier;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import net.openhft.affinity.AffinityLock;
/**
*
* @author Rinde van Lon
*/
public class PerformExperiment {
static final String VANLON_HOLVOET_DATASET = "files/vanLonHolvoet15/";
static final String RESULTS_MAIN_DIR = "files/results/";
enum ExperimentType {
GENDREAU(Gendreau06ObjectiveFunction.instance()) {
@Override
void apply(Builder bldr) {
bldr.addScenarios(
FileProvider.builder()
.add(Paths.get("files/gendreau2006/requests"))
.filter("glob:**req_rapide_**"))
.setScenarioReader(Functions.compose(ScenarioConverter.INSTANCE,
Gendreau06Parser.reader()))
.addResultListener(new GendreauResultWriter(experimentDir));;
}
},
/**
* Experiment on the Van Lon & Holvoet (2015) dataset.
*/
VAN_LON15(Gendreau06ObjectiveFunction.instance(50d)) {
@Override
void apply(Builder bldr) {
bldr.addScenarios(
FileProvider.builder()
.add(Paths.get(VANLON_HOLVOET_DATASET))
.filter("glob:**[0-9].scen"))
.setScenarioReader(
ScenarioIO.readerAdapter(ScenarioConverter.INSTANCE))
.addResultListener(new VanLonHolvoetResultWriter(experimentDir));
}
},
/**
* Investigate one setting of the Van Lon & Holvoet (2015) dataset with many
* repetitions.
*/
TIME_DEVIATION(Gendreau06ObjectiveFunction.instance(50d)) {
@Override
void apply(Builder bldr) {
bldr.addScenarios(FileProvider.builder()
.add(Paths.get(VANLON_HOLVOET_DATASET))
.filter("glob:**0.50-20-10.00-[0-9].scen"))
.setScenarioReader(
ScenarioIO.readerAdapter(ScenarioConverter.INSTANCE))
.repeat(10)
.addResultListener(new VanLonHolvoetResultWriter(experimentDir));
}
};
final File experimentDir = new File(RESULTS_MAIN_DIR + "/" + name());
private final Gendreau06ObjectiveFunction objectiveFunction;
ExperimentType(Gendreau06ObjectiveFunction objFunc) {
objectiveFunction = objFunc;
}
abstract void apply(Experiment.Builder b);
public Gendreau06ObjectiveFunction getObjectiveFunction() {
return objectiveFunction;
}
static ExperimentType find(String string) {
for (final ExperimentType type : ExperimentType.values()) {
final String name = type.name();
if (string.equalsIgnoreCase(name)
|| string.equalsIgnoreCase(name.replace("_", ""))) {
return type;
}
}
throw new IllegalArgumentException(
ExperimentType.class.getName() + " has no value called " + string);
}
}
public static void main(String[] args) throws IOException {
checkArgument(args.length > 2 && args[0].equals("-exp"),
"The type of experiment that should be run must be specified as follows: "
+ "\'-exp vanlon15|gendreau|timedeviation\', this option must be the "
+ "first in the list.");
final ExperimentType experimentType = ExperimentType.find(args[1]);
System.out.println(experimentType);
final String[] expArgs = new String[args.length - 2];
System.arraycopy(args, 2, expArgs, 0, args.length - 2);
final Gendreau06ObjectiveFunction objFunc =
experimentType.getObjectiveFunction();
final StochasticSupplier<RealtimeSolver> cih =
SolverToRealtimeAdapter
.create(CheapestInsertionHeuristic.supplier(objFunc));
final StochasticSupplier<RealtimeSolver> opt2 = Opt2.builder()
.withObjectiveFunction(objFunc)
.buildRealtimeSolverSupplier();
final long time = System.currentTimeMillis();
final Experiment.Builder experimentBuilder = Experiment
.build(objFunc)
.computeLocal()
.withRandomSeed(123)
.withThreads(11)
.repeat(1)
.addResultListener(new CommandLineProgress(System.out));
experimentType.apply(experimentBuilder);
experimentBuilder
.usePostProcessor(LogProcessor.INSTANCE)
.addConfiguration(MASConfiguration.pdptwBuilder()
.setName("ReAuction-2optRP-cihBID-BAL")
.addEventHandler(AddVehicleEvent.class,
DefaultTruckFactory.builder()
.setRoutePlanner(RtSolverRoutePlanner.supplier(opt2))
.setCommunicator(RtSolverBidder.supplier(objFunc, cih,
RtSolverBidder.BidFunctions.BALANCED))
.setLazyComputation(false)
.setRouteAdjuster(RouteFollowingVehicle.delayAdjuster())
.build())
.addModel(AuctionCommModel.builder(DoubleBid.class)
.withStopCondition(
AuctionStopConditions.and(
AuctionStopConditions.<DoubleBid>atLeastNumBids(2),
AuctionStopConditions.or(
AuctionStopConditions.<DoubleBid>allBidders(),
AuctionStopConditions
.<DoubleBid>maxAuctionDuration(5000)))))
.addModel(RtSolverModel.builder()
.withThreadPoolSize(3)
.withThreadGrouping(true))
.addModel(RealtimeClockLogger.builder())
.build())
.addConfiguration(MASConfiguration.pdptwBuilder()
.setName("ReAuction-2optRP-cihBID-BAL-HIGH")
.addEventHandler(AddVehicleEvent.class,
DefaultTruckFactory.builder()
.setRoutePlanner(RtSolverRoutePlanner.supplier(opt2))
.setCommunicator(RtSolverBidder.supplier(objFunc, cih,
RtSolverBidder.BidFunctions.BALANCED_HIGH))
.setLazyComputation(false)
.setRouteAdjuster(RouteFollowingVehicle.delayAdjuster())
.build())
.addModel(AuctionCommModel.builder(DoubleBid.class)
.withStopCondition(
AuctionStopConditions.and(
AuctionStopConditions.<DoubleBid>atLeastNumBids(2),
AuctionStopConditions.or(
AuctionStopConditions.<DoubleBid>allBidders(),
AuctionStopConditions
.<DoubleBid>maxAuctionDuration(5000)))))
.addModel(RtSolverModel.builder()
.withThreadPoolSize(3)
.withThreadGrouping(true))
.addModel(RealtimeClockLogger.builder())
.build())
.addConfiguration(MASConfiguration.pdptwBuilder()
.setName("ReAuction-2optRP-cihBID-BAL-LOW")
.addEventHandler(AddVehicleEvent.class,
DefaultTruckFactory.builder()
.setRoutePlanner(RtSolverRoutePlanner.supplier(opt2))
.setCommunicator(RtSolverBidder.supplier(objFunc, cih,
RtSolverBidder.BidFunctions.BALANCED_LOW))
.setLazyComputation(false)
.setRouteAdjuster(RouteFollowingVehicle.delayAdjuster())
.build())
.addModel(AuctionCommModel.builder(DoubleBid.class)
.withStopCondition(
AuctionStopConditions.and(
AuctionStopConditions.<DoubleBid>atLeastNumBids(2),
AuctionStopConditions.or(
AuctionStopConditions.<DoubleBid>allBidders(),
AuctionStopConditions
.<DoubleBid>maxAuctionDuration(5000)))))
.addModel(RtSolverModel.builder()
.withThreadPoolSize(3)
.withThreadGrouping(true))
.addModel(RealtimeClockLogger.builder())
.build())
// cheapest insertion
.addConfiguration(MASConfiguration.builder(
RtCentral.solverConfigurationAdapt(
CheapestInsertionHeuristic.supplier(objFunc), "", true))
.addModel(RealtimeClockLogger.builder())
.build())
// 2-opt cheapest insertion
.addConfiguration(MASConfiguration.builder(
RtCentral.solverConfiguration(
// Central.solverConfiguration(
Opt2.builder()
.withObjectiveFunction(objFunc)
.buildRealtimeSolverSupplier(),
""))
// , true))
.addModel(RealtimeClockLogger.builder())
.build())
.showGui(View.builder()
.withAutoPlay()
.withAutoClose()
.withSpeedUp(8)
// .withFullScreen()
.withTitleAppendix("AAMAS 2016 Experiment")
.with(RoadUserRenderer.builder()
.withToStringLabel())
.with(RouteRenderer.builder())
.with(PDPModelRenderer.builder())
.with(PlaneRoadModelRenderer.builder())
.with(AuctionPanel.builder())
.with(TimeLinePanel.builder())
.with(RtSolverPanel.builder())
.withResolution(1280, 1024));
final Optional<ExperimentResults> results =
experimentBuilder.perform(System.out, expArgs);
final long duration = System.currentTimeMillis() - time;
if (!results.isPresent()) {
return;
}
System.out.println("Done, computed " + results.get().getResults().size()
+ " simulations in " + duration / 1000d + "s");
}
enum ScenarioConverter implements Function<Scenario, Scenario> {
/**
* Changes ticksize to 250ms and adds stopcondition with maximum sim time of
* 10 hours.
*/
INSTANCE {
@Override
public Scenario apply(@Nullable Scenario input) {
final Scenario s = verifyNotNull(input);
return Scenario.builder(s)
.removeModelsOfType(TimeModel.AbstractBuilder.class)
.addModel(TimeModel.builder().withTickLength(250).withRealTime())
.setStopCondition(StopConditions.or(s.getStopCondition(),
StopConditions.limitedTime(10 * 60 * 60 * 1000)))
.build();
}
}
}
@AutoValue
abstract static class ExperimentInfo {
abstract List<LogEntry> getLog();
abstract long getRtCount();
abstract long getStCount();
abstract StatisticsDTO getStats();
abstract ImmutableList<MeasuredDeviation> getMeasuredDeviations();
static ExperimentInfo create(List<LogEntry> log, long rt, long st,
StatisticsDTO stats, ImmutableList<MeasuredDeviation> dev) {
return new AutoValue_PerformExperiment_ExperimentInfo(log, rt, st, stats,
dev);
}
}
enum LogProcessor implements PostProcessor<ExperimentInfo> {
INSTANCE {
@Override
public ExperimentInfo collectResults(Simulator sim, SimArgs args) {
final RealtimeClockLogger logger =
sim.getModelProvider().getModel(RealtimeClockLogger.class);
// logger.getDeviations()
final StatisticsDTO stats =
PostProcessors.statisticsPostProcessor().collectResults(sim, args);
System.out.println("success: " + args);
return ExperimentInfo.create(logger.getLog(), logger.getRtCount(),
logger.getStCount(), stats, logger.getDeviations());
}
@Override
public FailureStrategy handleFailure(Exception e, Simulator sim,
SimArgs args) {
System.out.println("Fail: " + args);
e.printStackTrace();
System.out.println(AffinityLock.dumpLocks());
// System.out.println(Joiner.on("\n").join(
// sim.getModelProvider().getModel(RealtimeClockLogger.class).getLog()));
// System.out.println("RETRY!");
return FailureStrategy.RETRY;
}
}
}
static class DebugParcelCreator
implements TimedEventHandler<AddParcelEvent>, Serializable {
private static final long serialVersionUID = -3604876394924095797L;
Map<SimulatorAPI, AtomicLong> map;
DebugParcelCreator() {
map = new ConcurrentHashMap<>();
}
@Override
public void handleTimedEvent(AddParcelEvent event, SimulatorAPI simulator) {
if (!map.containsKey(simulator)) {
map.put(simulator, new AtomicLong());
}
final String str =
"p" + Long.toString(map.get(simulator).getAndIncrement());
simulator.register(new Parcel(event.getParcelDTO()) {
@Override
public String toString() {
return str;
}
});
}
}
}
| src/main/java/com/github/rinde/aamas16/PerformExperiment.java | /*
* Copyright (C) 2015 Rinde van Lon, iMinds-DistriNet, KU Leuven
*
* 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.github.rinde.aamas16;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verifyNotNull;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
import com.github.rinde.logistics.pdptw.mas.TruckFactory.DefaultTruckFactory;
import com.github.rinde.logistics.pdptw.mas.comm.AuctionCommModel;
import com.github.rinde.logistics.pdptw.mas.comm.AuctionPanel;
import com.github.rinde.logistics.pdptw.mas.comm.AuctionStopConditions;
import com.github.rinde.logistics.pdptw.mas.comm.DoubleBid;
import com.github.rinde.logistics.pdptw.mas.comm.RtSolverBidder;
import com.github.rinde.logistics.pdptw.mas.route.RtSolverRoutePlanner;
import com.github.rinde.logistics.pdptw.solver.CheapestInsertionHeuristic;
import com.github.rinde.logistics.pdptw.solver.Opt2;
import com.github.rinde.rinsim.central.rt.RealtimeSolver;
import com.github.rinde.rinsim.central.rt.RtCentral;
import com.github.rinde.rinsim.central.rt.RtSolverModel;
import com.github.rinde.rinsim.central.rt.RtSolverPanel;
import com.github.rinde.rinsim.central.rt.SolverToRealtimeAdapter;
import com.github.rinde.rinsim.core.Simulator;
import com.github.rinde.rinsim.core.SimulatorAPI;
import com.github.rinde.rinsim.core.model.pdp.Parcel;
import com.github.rinde.rinsim.core.model.time.MeasuredDeviation;
import com.github.rinde.rinsim.core.model.time.RealtimeClockLogger;
import com.github.rinde.rinsim.core.model.time.RealtimeClockLogger.LogEntry;
import com.github.rinde.rinsim.core.model.time.TimeModel;
import com.github.rinde.rinsim.experiment.CommandLineProgress;
import com.github.rinde.rinsim.experiment.Experiment;
import com.github.rinde.rinsim.experiment.Experiment.Builder;
import com.github.rinde.rinsim.experiment.Experiment.SimArgs;
import com.github.rinde.rinsim.experiment.ExperimentResults;
import com.github.rinde.rinsim.experiment.MASConfiguration;
import com.github.rinde.rinsim.experiment.PostProcessor;
import com.github.rinde.rinsim.experiment.PostProcessors;
import com.github.rinde.rinsim.io.FileProvider;
import com.github.rinde.rinsim.pdptw.common.AddParcelEvent;
import com.github.rinde.rinsim.pdptw.common.AddVehicleEvent;
import com.github.rinde.rinsim.pdptw.common.RouteFollowingVehicle;
import com.github.rinde.rinsim.pdptw.common.RouteRenderer;
import com.github.rinde.rinsim.pdptw.common.StatisticsDTO;
import com.github.rinde.rinsim.pdptw.common.TimeLinePanel;
import com.github.rinde.rinsim.scenario.Scenario;
import com.github.rinde.rinsim.scenario.ScenarioIO;
import com.github.rinde.rinsim.scenario.StopConditions;
import com.github.rinde.rinsim.scenario.TimedEventHandler;
import com.github.rinde.rinsim.scenario.gendreau06.Gendreau06ObjectiveFunction;
import com.github.rinde.rinsim.scenario.gendreau06.Gendreau06Parser;
import com.github.rinde.rinsim.ui.View;
import com.github.rinde.rinsim.ui.renderers.PDPModelRenderer;
import com.github.rinde.rinsim.ui.renderers.PlaneRoadModelRenderer;
import com.github.rinde.rinsim.ui.renderers.RoadUserRenderer;
import com.github.rinde.rinsim.util.StochasticSupplier;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import net.openhft.affinity.AffinityLock;
/**
*
* @author Rinde van Lon
*/
public class PerformExperiment {
static final String VANLON_HOLVOET_DATASET = "files/vanLonHolvoet15/";
static final String RESULTS_MAIN_DIR = "files/results/";
enum ExperimentType {
GENDREAU(Gendreau06ObjectiveFunction.instance()) {
@Override
void apply(Builder bldr) {
bldr.addScenarios(
FileProvider.builder()
.add(Paths.get("files/gendreau2006/requests"))
.filter("glob:**req_rapide_**"))
.setScenarioReader(Functions.compose(ScenarioConverter.INSTANCE,
Gendreau06Parser.reader()))
.addResultListener(new GendreauResultWriter(experimentDir));;
}
},
/**
* Experiment on the Van Lon & Holvoet (2015) dataset.
*/
VAN_LON15(Gendreau06ObjectiveFunction.instance(50d)) {
@Override
void apply(Builder bldr) {
bldr.addScenarios(
FileProvider.builder()
.add(Paths.get(VANLON_HOLVOET_DATASET))
.filter("glob:**[0-9].scen"))
.setScenarioReader(
ScenarioIO.readerAdapter(ScenarioConverter.INSTANCE))
.addResultListener(new VanLonHolvoetResultWriter(experimentDir));
}
},
/**
* Investigate one setting of the Van Lon & Holvoet (2015) dataset with many
* repetitions.
*/
TIME_DEVIATION(Gendreau06ObjectiveFunction.instance(50d)) {
@Override
void apply(Builder bldr) {
bldr.addScenarios(FileProvider.builder()
.add(Paths.get(VANLON_HOLVOET_DATASET))
.filter("glob:**0.50-20-10.00-[0-9].scen"))
.setScenarioReader(
ScenarioIO.readerAdapter(ScenarioConverter.INSTANCE))
.repeat(10)
.addResultListener(new VanLonHolvoetResultWriter(experimentDir));
}
};
final File experimentDir = new File(RESULTS_MAIN_DIR + "/" + name());
private final Gendreau06ObjectiveFunction objectiveFunction;
ExperimentType(Gendreau06ObjectiveFunction objFunc) {
objectiveFunction = objFunc;
}
abstract void apply(Experiment.Builder b);
public Gendreau06ObjectiveFunction getObjectiveFunction() {
return objectiveFunction;
}
static ExperimentType find(String string) {
for (final ExperimentType type : ExperimentType.values()) {
final String name = type.name();
if (string.equalsIgnoreCase(name)
|| string.equalsIgnoreCase(name.replace("_", ""))) {
return type;
}
}
throw new IllegalArgumentException(
ExperimentType.class.getName() + " has no value called " + string);
}
}
public static void main(String[] args) throws IOException {
checkArgument(args.length > 2 && args[0].equals("-exp"),
"The type of experiment that should be run must be specified as follows: "
+ "\'-exp vanlon15|gendreau|timedeviation\', this option must be the "
+ "first in the list.");
final ExperimentType experimentType = ExperimentType.find(args[1]);
System.out.println(experimentType);
final String[] expArgs = new String[args.length - 2];
System.arraycopy(args, 2, expArgs, 0, args.length - 2);
final Gendreau06ObjectiveFunction objFunc =
experimentType.getObjectiveFunction();
final StochasticSupplier<RealtimeSolver> cih =
SolverToRealtimeAdapter
.create(CheapestInsertionHeuristic.supplier(objFunc));
final StochasticSupplier<RealtimeSolver> opt2 = Opt2.builder()
.withObjectiveFunction(objFunc)
.buildRealtimeSolverSupplier();
final long time = System.currentTimeMillis();
final Experiment.Builder experimentBuilder = Experiment
.build(objFunc)
.computeLocal()
.withRandomSeed(123)
.withThreads(11)
.repeat(1)
.addResultListener(new CommandLineProgress(System.out));
experimentType.apply(experimentBuilder);
experimentBuilder
.usePostProcessor(LogProcessor.INSTANCE)
.addConfiguration(MASConfiguration.pdptwBuilder()
.setName("ReAuction-2optRP-cihBID-BAL-HIGH")
.addEventHandler(AddVehicleEvent.class,
DefaultTruckFactory.builder()
.setRoutePlanner(RtSolverRoutePlanner.supplier(opt2))
.setCommunicator(RtSolverBidder.supplier(objFunc, cih,
RtSolverBidder.BidFunctions.BALANCED_HIGH))
.setLazyComputation(false)
.setRouteAdjuster(RouteFollowingVehicle.delayAdjuster())
.build())
.addModel(AuctionCommModel.builder(DoubleBid.class)
.withStopCondition(
AuctionStopConditions.and(
AuctionStopConditions.<DoubleBid>atLeastNumBids(2),
AuctionStopConditions.or(
AuctionStopConditions.<DoubleBid>allBidders(),
AuctionStopConditions
.<DoubleBid>maxAuctionDuration(5000)))))
.addModel(RtSolverModel.builder()
.withThreadPoolSize(3)
.withThreadGrouping(true))
.addModel(RealtimeClockLogger.builder())
.build())
.addConfiguration(MASConfiguration.pdptwBuilder()
.setName("ReAuction-2optRP-cihBID-BAL-LOW")
.addEventHandler(AddVehicleEvent.class,
DefaultTruckFactory.builder()
.setRoutePlanner(RtSolverRoutePlanner.supplier(opt2))
.setCommunicator(RtSolverBidder.supplier(objFunc, cih,
RtSolverBidder.BidFunctions.BALANCED_LOW))
.setLazyComputation(false)
.setRouteAdjuster(RouteFollowingVehicle.delayAdjuster())
.build())
.addModel(AuctionCommModel.builder(DoubleBid.class)
.withStopCondition(
AuctionStopConditions.and(
AuctionStopConditions.<DoubleBid>atLeastNumBids(2),
AuctionStopConditions.or(
AuctionStopConditions.<DoubleBid>allBidders(),
AuctionStopConditions
.<DoubleBid>maxAuctionDuration(5000)))))
.addModel(RtSolverModel.builder()
.withThreadPoolSize(3)
.withThreadGrouping(true))
.addModel(RealtimeClockLogger.builder())
.build())
// cheapest insertion
.addConfiguration(MASConfiguration.builder(
RtCentral.solverConfigurationAdapt(
CheapestInsertionHeuristic.supplier(objFunc), "", true))
.addModel(RealtimeClockLogger.builder())
.build())
// 2-opt cheapest insertion
.addConfiguration(MASConfiguration.builder(
RtCentral.solverConfiguration(
// Central.solverConfiguration(
Opt2.builder()
.withObjectiveFunction(objFunc)
.buildRealtimeSolverSupplier(),
""))
// , true))
.addModel(RealtimeClockLogger.builder())
.build())
.showGui(View.builder()
.withAutoPlay()
.withAutoClose()
.withSpeedUp(8)
// .withFullScreen()
.withTitleAppendix("AAMAS 2016 Experiment")
.with(RoadUserRenderer.builder()
.withToStringLabel())
.with(RouteRenderer.builder())
.with(PDPModelRenderer.builder())
.with(PlaneRoadModelRenderer.builder())
.with(AuctionPanel.builder())
.with(TimeLinePanel.builder())
.with(RtSolverPanel.builder())
.withResolution(1280, 1024));
final Optional<ExperimentResults> results =
experimentBuilder.perform(System.out, expArgs);
final long duration = System.currentTimeMillis() - time;
if (!results.isPresent()) {
return;
}
System.out.println("Done, computed " + results.get().getResults().size()
+ " simulations in " + duration / 1000d + "s");
}
enum ScenarioConverter implements Function<Scenario, Scenario> {
/**
* Changes ticksize to 250ms and adds stopcondition with maximum sim time of
* 10 hours.
*/
INSTANCE {
@Override
public Scenario apply(@Nullable Scenario input) {
final Scenario s = verifyNotNull(input);
return Scenario.builder(s)
.removeModelsOfType(TimeModel.AbstractBuilder.class)
.addModel(TimeModel.builder().withTickLength(250).withRealTime())
.setStopCondition(StopConditions.or(s.getStopCondition(),
StopConditions.limitedTime(10 * 60 * 60 * 1000)))
.build();
}
}
}
@AutoValue
abstract static class ExperimentInfo {
abstract List<LogEntry> getLog();
abstract long getRtCount();
abstract long getStCount();
abstract StatisticsDTO getStats();
abstract ImmutableList<MeasuredDeviation> getMeasuredDeviations();
static ExperimentInfo create(List<LogEntry> log, long rt, long st,
StatisticsDTO stats, ImmutableList<MeasuredDeviation> dev) {
return new AutoValue_PerformExperiment_ExperimentInfo(log, rt, st, stats,
dev);
}
}
enum LogProcessor implements PostProcessor<ExperimentInfo> {
INSTANCE {
@Override
public ExperimentInfo collectResults(Simulator sim, SimArgs args) {
final RealtimeClockLogger logger =
sim.getModelProvider().getModel(RealtimeClockLogger.class);
// logger.getDeviations()
final StatisticsDTO stats =
PostProcessors.statisticsPostProcessor().collectResults(sim, args);
System.out.println("success: " + args);
return ExperimentInfo.create(logger.getLog(), logger.getRtCount(),
logger.getStCount(), stats, logger.getDeviations());
}
@Override
public FailureStrategy handleFailure(Exception e, Simulator sim,
SimArgs args) {
System.out.println("Fail: " + args);
e.printStackTrace();
System.out.println(AffinityLock.dumpLocks());
// System.out.println(Joiner.on("\n").join(
// sim.getModelProvider().getModel(RealtimeClockLogger.class).getLog()));
// System.out.println("RETRY!");
return FailureStrategy.RETRY;
}
}
}
static class DebugParcelCreator
implements TimedEventHandler<AddParcelEvent>, Serializable {
private static final long serialVersionUID = -3604876394924095797L;
Map<SimulatorAPI, AtomicLong> map;
DebugParcelCreator() {
map = new ConcurrentHashMap<>();
}
@Override
public void handleTimedEvent(AddParcelEvent event, SimulatorAPI simulator) {
if (!map.containsKey(simulator)) {
map.put(simulator, new AtomicLong());
}
final String str =
"p" + Long.toString(map.get(simulator).getAndIncrement());
simulator.register(new Parcel(event.getParcelDTO()) {
@Override
public String toString() {
return str;
}
});
}
}
}
| more balance stuff
| src/main/java/com/github/rinde/aamas16/PerformExperiment.java | more balance stuff | <ide><path>rc/main/java/com/github/rinde/aamas16/PerformExperiment.java
<ide> experimentBuilder
<ide> .usePostProcessor(LogProcessor.INSTANCE)
<ide> .addConfiguration(MASConfiguration.pdptwBuilder()
<add> .setName("ReAuction-2optRP-cihBID-BAL")
<add> .addEventHandler(AddVehicleEvent.class,
<add> DefaultTruckFactory.builder()
<add> .setRoutePlanner(RtSolverRoutePlanner.supplier(opt2))
<add> .setCommunicator(RtSolverBidder.supplier(objFunc, cih,
<add> RtSolverBidder.BidFunctions.BALANCED))
<add> .setLazyComputation(false)
<add> .setRouteAdjuster(RouteFollowingVehicle.delayAdjuster())
<add> .build())
<add> .addModel(AuctionCommModel.builder(DoubleBid.class)
<add> .withStopCondition(
<add> AuctionStopConditions.and(
<add> AuctionStopConditions.<DoubleBid>atLeastNumBids(2),
<add> AuctionStopConditions.or(
<add> AuctionStopConditions.<DoubleBid>allBidders(),
<add> AuctionStopConditions
<add> .<DoubleBid>maxAuctionDuration(5000)))))
<add> .addModel(RtSolverModel.builder()
<add> .withThreadPoolSize(3)
<add> .withThreadGrouping(true))
<add> .addModel(RealtimeClockLogger.builder())
<add> .build())
<add> .addConfiguration(MASConfiguration.pdptwBuilder()
<ide> .setName("ReAuction-2optRP-cihBID-BAL-HIGH")
<ide> .addEventHandler(AddVehicleEvent.class,
<ide> DefaultTruckFactory.builder() |
|
Java | cc0-1.0 | 809701a123cfe351d2e4828e023206825b63054c | 0 | john494/SmartMirror,john494/SmartMirror,john494/SmartMirror,john494/SmartMirror,john494/SmartMirror,john494/SmartMirror,john494/SmartMirror | package com.example.smartmirror;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FacebookBackend extends AppCompatActivity {
private CallbackManager callbackManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_facebook);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("user_posts");
getLoginDetails(loginButton);
if(isLoggedIn()){
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/me/tagged", //me/tagged shows only posts user was tagged in. me/feed shows all posts published on profile
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
JSONObject jarray = response.getJSONObject();
List<NameValuePair> message = new ArrayList<NameValuePair>();
List<String> story = new ArrayList<String>();
List<NameValuePair> datetime = new ArrayList<NameValuePair>();
JSONArray array = null;
try {
array = jarray.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0 ; i < array.length() ; i++){
try {
message.add(new BasicNameValuePair("fmessage", array.getJSONObject(i).getString("message")));
} catch (JSONException e) {
e.printStackTrace();
}
try {
story.add(array.getJSONObject(i).getString("story"));
} catch (JSONException e) {
e.printStackTrace();
story.add(i,"");
}
try {
datetime.add(new BasicNameValuePair("fdate",array.getJSONObject(i).getString("created_time")));
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("logged", message.toString());
Log.i("logged", story.toString());
Log.i("logged", datetime.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://jarvis.cse.buffalo.edu/mine/facebook.php");
try {
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("fstring", "HI"));
//nameValuePairs.add(new BasicNameValuePair("fdate", "10/29/2016"));
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(message.size()*2);
for(int i = 0; i < message.size(); i++){
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(message.get(i));
nameValuePairs.add(new BasicNameValuePair("fpost", story.get(i)));
//Log.i("logged", message.get(i).toString());
nameValuePairs.add(datetime.get(i));
//Log.i("logged", datetime.get(i).toString());
}
Log.i("logged", nameValuePairs.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
//httppost.setEntity(new UrlEncodedFormEntity(story));
//httpclient.execute(httppost);
//httppost.setEntity(new UrlEncodedFormEntity(datetime));
//httpclient.execute(httppost);
//Log.i("logged", nameValuePairs.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
});
request.executeAsync();
}
else{
Log.i("logged", "out");
}
}
protected void getLoginDetails(LoginButton login_button){
login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>(){
@Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/me/tagged", //me/tagged shows only posts user was tagged in. me/feed shows all posts published on profile
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
Log.i("logged", "Success!");
}
});
request.executeAsync();
}
@Override
public void onCancel() {
Log.i("logged", "Cancelled");
}
@Override
public void onError(FacebookException e) {
Log.i("logged", "Error");
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
}
| phoneapp/SmartMirror/app/src/main/java/com/example/smartmirror/FacebookBackend.java | package com.example.smartmirror;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class FacebookBackend extends AppCompatActivity {
private CallbackManager callbackManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_facebook);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("user_posts");
getLoginDetails(loginButton);
if(isLoggedIn()){
Log.i("logged", "in");
//Log.i("logged", AccessToken.getCurrentAccessToken().getToken());
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/me/tagged", //me/tagged shows only posts user was tagged in. me/feed shows all posts published on profile
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
Log.i("logged", response.toString());
}
});
request.executeAsync();
}
else{
Log.i("logged", "out");
}
}
protected void getLoginDetails(LoginButton login_button){
login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>(){
@Override
public void onSuccess(LoginResult loginResult) {
//Log.i("logged", "Please");
//Log.i("logged", loginResult.getAccessToken().getToken());
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/me/tagged", //me/tagged shows only posts user was tagged in. me/feed shows all posts published on profile
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
Log.i("logged", response.toString());
}
});
request.executeAsync();
}
@Override
public void onCancel() {
Log.i("logged", "Please cancel");
}
@Override
public void onError(FacebookException e) {
Log.i("logged", "Please error");
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
}
| Feed is now pulled and being posted to server. #39
| phoneapp/SmartMirror/app/src/main/java/com/example/smartmirror/FacebookBackend.java | Feed is now pulled and being posted to server. #39 | <ide><path>honeapp/SmartMirror/app/src/main/java/com/example/smartmirror/FacebookBackend.java
<ide> import com.facebook.login.LoginResult;
<ide> import com.facebook.login.widget.LoginButton;
<ide>
<add>import org.apache.http.NameValuePair;
<add>import org.apache.http.client.ClientProtocolException;
<add>import org.apache.http.client.HttpClient;
<add>import org.apache.http.client.entity.UrlEncodedFormEntity;
<add>import org.apache.http.client.methods.HttpPost;
<add>import org.apache.http.impl.client.DefaultHttpClient;
<add>import org.apache.http.message.BasicNameValuePair;
<add>import org.json.JSONArray;
<add>import org.json.JSONException;
<add>import org.json.JSONObject;
<add>
<add>import java.io.IOException;
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<ide> public class FacebookBackend extends AppCompatActivity {
<ide>
<ide> private CallbackManager callbackManager;
<ide> getLoginDetails(loginButton);
<ide>
<ide> if(isLoggedIn()){
<del> Log.i("logged", "in");
<del> //Log.i("logged", AccessToken.getCurrentAccessToken().getToken());
<ide> GraphRequest request = GraphRequest.newGraphPathRequest(
<ide> AccessToken.getCurrentAccessToken(),
<ide> "/me/tagged", //me/tagged shows only posts user was tagged in. me/feed shows all posts published on profile
<ide> new GraphRequest.Callback() {
<ide> @Override
<ide> public void onCompleted(GraphResponse response) {
<del> Log.i("logged", response.toString());
<add> JSONObject jarray = response.getJSONObject();
<add> List<NameValuePair> message = new ArrayList<NameValuePair>();
<add> List<String> story = new ArrayList<String>();
<add> List<NameValuePair> datetime = new ArrayList<NameValuePair>();
<add> JSONArray array = null;
<add> try {
<add> array = jarray.getJSONArray("data");
<add> } catch (JSONException e) {
<add> e.printStackTrace();
<add> }
<add> for(int i = 0 ; i < array.length() ; i++){
<add> try {
<add> message.add(new BasicNameValuePair("fmessage", array.getJSONObject(i).getString("message")));
<add> } catch (JSONException e) {
<add> e.printStackTrace();
<add> }
<add> try {
<add> story.add(array.getJSONObject(i).getString("story"));
<add> } catch (JSONException e) {
<add> e.printStackTrace();
<add> story.add(i,"");
<add> }
<add> try {
<add> datetime.add(new BasicNameValuePair("fdate",array.getJSONObject(i).getString("created_time")));
<add> } catch (JSONException e) {
<add> e.printStackTrace();
<add> }
<add> }
<add> Log.i("logged", message.toString());
<add> Log.i("logged", story.toString());
<add> Log.i("logged", datetime.toString());
<add> HttpClient httpclient = new DefaultHttpClient();
<add> HttpPost httppost = new HttpPost("http://jarvis.cse.buffalo.edu/mine/facebook.php");
<add> try {
<add> //List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
<add>
<add> //nameValuePairs.add(new BasicNameValuePair("fstring", "HI"));
<add> //nameValuePairs.add(new BasicNameValuePair("fdate", "10/29/2016"));
<add> //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
<add> List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(message.size()*2);
<add> for(int i = 0; i < message.size(); i++){
<add> //List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
<add> nameValuePairs.add(message.get(i));
<add> nameValuePairs.add(new BasicNameValuePair("fpost", story.get(i)));
<add> //Log.i("logged", message.get(i).toString());
<add> nameValuePairs.add(datetime.get(i));
<add> //Log.i("logged", datetime.get(i).toString());
<add>
<add> }
<add> Log.i("logged", nameValuePairs.toString());
<add> httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
<add> httpclient.execute(httppost);
<add> //httppost.setEntity(new UrlEncodedFormEntity(story));
<add> //httpclient.execute(httppost);
<add> //httppost.setEntity(new UrlEncodedFormEntity(datetime));
<add> //httpclient.execute(httppost);
<add> //Log.i("logged", nameValuePairs.toString());
<add>
<add> } catch (ClientProtocolException e) {
<add> // TODO Auto-generated catch block
<add> } catch (IOException e) {
<add> // TODO Auto-generated catch block
<add> }
<ide> }
<ide> });
<ide>
<ide> login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>(){
<ide> @Override
<ide> public void onSuccess(LoginResult loginResult) {
<del> //Log.i("logged", "Please");
<del> //Log.i("logged", loginResult.getAccessToken().getToken());
<ide> GraphRequest request = GraphRequest.newGraphPathRequest(
<ide> AccessToken.getCurrentAccessToken(),
<ide> "/me/tagged", //me/tagged shows only posts user was tagged in. me/feed shows all posts published on profile
<ide> new GraphRequest.Callback() {
<ide> @Override
<ide> public void onCompleted(GraphResponse response) {
<del> Log.i("logged", response.toString());
<add> Log.i("logged", "Success!");
<ide> }
<ide> });
<ide>
<ide>
<ide> @Override
<ide> public void onCancel() {
<del> Log.i("logged", "Please cancel");
<add> Log.i("logged", "Cancelled");
<ide> }
<ide>
<ide> @Override
<ide> public void onError(FacebookException e) {
<del> Log.i("logged", "Please error");
<add> Log.i("logged", "Error");
<ide> }
<ide> });
<ide> |
|
Java | unlicense | d78869ae603502d4318f0676fdcd9f16525913ab | 0 | squeek502/SpiceOfLife | package squeek.spiceoflife.items;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.EnumAction;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IIcon;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.item.ItemTossEvent;
import squeek.applecore.api.food.FoodEvent;
import squeek.applecore.api.food.FoodValues;
import squeek.applecore.api.food.IEdible;
import squeek.spiceoflife.ModConfig;
import squeek.spiceoflife.ModInfo;
import squeek.spiceoflife.helpers.*;
import squeek.spiceoflife.helpers.MealPrioritizationHelper.InventoryFoodInfo;
import squeek.spiceoflife.inventory.ContainerFoodContainer;
import squeek.spiceoflife.inventory.FoodContainerInventory;
import squeek.spiceoflife.inventory.INBTInventoryHaver;
import squeek.spiceoflife.inventory.NBTInventory;
import squeek.spiceoflife.network.NetworkHelper;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemFoodContainer extends Item implements INBTInventoryHaver, IEdible
{
private IIcon iconOpenEmpty;
private IIcon iconOpenFull;
public int numSlots;
public String itemName;
public static final Random random = new Random();
public static final String TAG_KEY_INVENTORY = "Inventory";
public static final String TAG_KEY_OPEN = "Open";
public static final String TAG_KEY_UUID = "UUID";
public ItemFoodContainer(String itemName, int numSlots)
{
super();
this.itemName = itemName;
this.numSlots = numSlots;
setMaxStackSize(1);
setTextureName(ModInfo.MODID.toLowerCase() + ":" + itemName);
setUnlocalizedName(ModInfo.MODID.toLowerCase() + "." + itemName);
setCreativeTab(CreativeTabs.tabMisc);
// for ItemTossEvent
MinecraftForge.EVENT_BUS.register(this);
}
public boolean isEmpty(ItemStack itemStack)
{
return NBTInventory.isInventoryEmpty(getInventoryTag(itemStack));
}
public boolean isFull(ItemStack itemStack)
{
return getInventory(itemStack).isInventoryFull();
}
public boolean isOpen(ItemStack itemStack)
{
return itemStack.hasTagCompound() ? itemStack.getTagCompound().getBoolean(TAG_KEY_OPEN) : false;
}
public void setIsOpen(ItemStack itemStack, boolean isOpen)
{
NBTTagCompound baseTag = getOrInitBaseTag(itemStack);
baseTag.setBoolean(TAG_KEY_OPEN, isOpen);
}
public UUID getUUID(ItemStack itemStack)
{
return UUID.fromString(getOrInitBaseTag(itemStack).getString(TAG_KEY_UUID));
}
public NBTTagCompound getOrInitBaseTag(ItemStack itemStack)
{
if (!itemStack.hasTagCompound())
itemStack.setTagCompound(new NBTTagCompound());
NBTTagCompound baseTag = itemStack.getTagCompound();
if (!baseTag.hasKey(TAG_KEY_UUID))
baseTag.setString(TAG_KEY_UUID, UUID.randomUUID().toString());
return baseTag;
}
public NBTTagCompound getInventoryTag(ItemStack itemStack)
{
NBTTagCompound baseTag = getOrInitBaseTag(itemStack);
if (!baseTag.hasKey(TAG_KEY_INVENTORY))
baseTag.setTag(TAG_KEY_INVENTORY, new NBTTagCompound());
return baseTag.getCompoundTag(TAG_KEY_INVENTORY);
}
public FoodContainerInventory getInventory(ItemStack itemStack)
{
return new FoodContainerInventory(this, itemStack);
}
public void tryDumpFoodInto(ItemStack itemStack, IInventory inventory, EntityPlayer player)
{
FoodContainerInventory foodContainerInventory = getInventory(itemStack);
for (int slotNum = 0; slotNum < foodContainerInventory.getSizeInventory(); slotNum++)
{
ItemStack stackInSlot = foodContainerInventory.getStackInSlot(slotNum);
if (stackInSlot == null)
continue;
stackInSlot = InventoryHelper.insertStackIntoInventory(stackInSlot, inventory);
foodContainerInventory.setInventorySlotContents(slotNum, stackInSlot);
}
}
public void tryPullFoodFrom(ItemStack itemStack, IInventory inventory, EntityPlayer player)
{
List<InventoryFoodInfo> foodsToPull = MealPrioritizationHelper.findBestFoodsForPlayerAccountingForVariety(player, inventory);
if (foodsToPull.size() > 0)
{
FoodContainerInventory foodContainerInventory = getInventory(itemStack);
for (InventoryFoodInfo foodToPull : foodsToPull)
{
ItemStack stackInSlot = inventory.getStackInSlot(foodToPull.slotNum);
if (stackInSlot == null)
continue;
stackInSlot = InventoryHelper.insertStackIntoInventoryOnce(stackInSlot, foodContainerInventory);
inventory.setInventorySlotContents(foodToPull.slotNum, stackInSlot);
}
}
}
// necessary to catch tossing items while still in an inventory
@SubscribeEvent
public void onItemToss(ItemTossEvent event)
{
if (event.entityItem.getEntityItem().getItem() instanceof ItemFoodContainer)
{
onDroppedByPlayer(event.entityItem.getEntityItem(), event.player);
}
}
@Override
public boolean onDroppedByPlayer(ItemStack itemStack, EntityPlayer player)
{
if (!player.worldObj.isRemote && player.openContainer != null && player.openContainer instanceof ContainerFoodContainer)
{
ContainerFoodContainer openFoodContainer = (ContainerFoodContainer) player.openContainer;
UUID droppedUUID = getUUID(itemStack);
if (openFoodContainer.getUUID().equals(droppedUUID))
{
// if the cursor item is the open food container, then it will create an infinite loop
// due to the container dropping the cursor item when it is closed
ItemStack itemOnTheCursor = player.inventory.getItemStack();
if (itemOnTheCursor != null && itemOnTheCursor.getItem() instanceof ItemFoodContainer)
{
if (((ItemFoodContainer) itemOnTheCursor.getItem()).getUUID(itemOnTheCursor).equals(droppedUUID))
{
player.inventory.setItemStack(null);
}
}
player.closeScreen();
}
}
return super.onDroppedByPlayer(itemStack, player);
}
public boolean canBeEatenFrom(ItemStack stack)
{
return isOpen(stack) && !isEmpty(stack);
}
public boolean canPlayerEatFrom(EntityPlayer player, ItemStack stack)
{
return canBeEatenFrom(stack) && player.canEat(false);
}
@Override
public void onUpdate(ItemStack itemStack, World world, Entity ownerEntity, int par4, boolean par5)
{
if (!world.isRemote && ownerEntity instanceof EntityPlayer && isOpen(itemStack) && !isEmpty(itemStack))
{
EntityPlayer player = (EntityPlayer) ownerEntity;
if (!player.isSneaking() && MovementHelper.getDidJumpLastTick(player))
{
float chanceToDrop = ModConfig.FOOD_CONTAINERS_CHANCE_TO_DROP_FOOD;
if (player.isSprinting())
chanceToDrop *= 2f;
if (chanceToDrop > 0 && random.nextFloat() <= chanceToDrop)
{
ItemStack itemToDrop = InventoryHelper.removeRandomSingleItemFromInventory(getInventory(itemStack), random);
player.dropPlayerItemWithRandomChoice(itemToDrop, true);
}
}
}
super.onUpdate(itemStack, world, ownerEntity, par4, par5);
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void addInformation(ItemStack itemStack, EntityPlayer player, List toolTip, boolean isAdvanced)
{
super.addInformation(itemStack, player, toolTip, isAdvanced);
String openCloseLineColor = EnumChatFormatting.GRAY.toString();
if (isOpen(itemStack))
{
toolTip.add(openCloseLineColor + StatCollector.translateToLocalFormatted("spiceoflife.tooltip.to.close.food.container"));
if (ModConfig.FOOD_CONTAINERS_CHANCE_TO_DROP_FOOD > 0)
toolTip.add(EnumChatFormatting.GOLD.toString() + EnumChatFormatting.ITALIC + StatCollector.translateToLocal("spiceoflife.tooltip.can.spill.food"));
}
else
toolTip.add(openCloseLineColor + StatCollector.translateToLocalFormatted("spiceoflife.tooltip.to.open.food.container"));
}
@Override
public IIcon getIconIndex(ItemStack itemStack)
{
if (isOpen(itemStack))
{
return isEmpty(itemStack) ? iconOpenEmpty : iconOpenFull;
}
return super.getIconIndex(itemStack);
}
@Override
public IIcon getIcon(ItemStack itemStack, int renderPass)
{
return getIconIndex(itemStack);
}
@Override
public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ)
{
if (!world.isRemote && isOpen(itemStack))
{
IInventory inventoryHit = InventoryHelper.getInventoryAtLocation(world, x, y, z);
if (inventoryHit != null && inventoryHit.isUseableByPlayer(player))
{
tryDumpFoodInto(itemStack, inventoryHit, player);
tryPullFoodFrom(itemStack, inventoryHit, player);
return true;
}
}
return super.onItemUseFirst(itemStack, player, world, x, y, z, side, hitX, hitY, hitZ);
}
@Override
public EnumAction getItemUseAction(ItemStack itemStack)
{
if (canBeEatenFrom(itemStack))
return EnumAction.eat;
else
return EnumAction.none;
}
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player)
{
if (player.isSneaking())
{
setIsOpen(itemStack, !isOpen(itemStack));
}
else if (canPlayerEatFrom(player, itemStack))
{
player.setItemInUse(itemStack, getMaxItemUseDuration(itemStack));
}
else if (!isOpen(itemStack))
{
GuiHelper.openGuiOfItemStack(player, itemStack);
setIsOpen(itemStack, true);
}
return super.onItemRightClick(itemStack, world, player);
}
@Override
public int getMaxItemUseDuration(ItemStack itemStack)
{
return 32;
}
@Override
public ItemStack onEaten(ItemStack itemStack, World world, EntityPlayer player)
{
IInventory inventory = getInventory(itemStack);
int slotWithBestFood = MealPrioritizationHelper.findBestFoodForPlayerToEat(player, inventory);
ItemStack foodToEat = inventory.getStackInSlot(slotWithBestFood);
if (foodToEat != null)
{
foodToEat.onFoodEaten(world, player);
if (foodToEat.stackSize <= 0)
foodToEat = null;
inventory.setInventorySlotContents(slotWithBestFood, foodToEat);
}
return super.onEaten(itemStack, world, player);
}
public ItemStack getBestFoodForPlayerToEat(ItemStack itemStack, EntityPlayer player)
{
IInventory inventory = getInventory(itemStack);
int slotWithBestFood = MealPrioritizationHelper.findBestFoodForPlayerToEat(player, inventory);
ItemStack foodToEat = inventory.getStackInSlot(slotWithBestFood);
return foodToEat;
}
@SideOnly(Side.CLIENT)
@Override
public void registerIcons(IIconRegister iconRegister)
{
super.registerIcons(iconRegister);
iconOpenEmpty = iconRegister.registerIcon(getIconString() + "_open_empty");
iconOpenFull = iconRegister.registerIcon(getIconString() + "_open_full");
}
@Override
public int getSizeInventory()
{
return numSlots;
}
@Override
public String getInvName(NBTInventory inventory)
{
return this.getItemStackDisplayName(null);
}
@Override
public boolean isInvNameLocalized(NBTInventory inventory)
{
return false;
}
@Override
public int getInventoryStackLimit(NBTInventory inventory)
{
return ModConfig.FOOD_CONTAINERS_MAX_STACKSIZE;
}
@Override
public void onInventoryChanged(NBTInventory inventory)
{
}
@Override
public boolean isItemValidForSlot(NBTInventory inventory, int slotNum, ItemStack itemStack)
{
return FoodHelper.isFood(itemStack) && FoodHelper.isDirectlyEdible(itemStack);
}
/*
* IEdible implementation
*/
@Override
public FoodValues getFoodValues(ItemStack itemStack)
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
{
// the client uses the food values for tooltips/etc, so it should
// inherit them from the food that will be eaten
return FoodValues.get(getBestFoodForPlayerToEat(itemStack, NetworkHelper.getClientPlayer()));
}
else
{
// the server only needs to know that food values are non-null
// this is used for the isFood check
return new FoodValues(0, 0f);
}
}
// necessary to stop food containers themselves being modified
// for example, HO's modFoodDivider was being applied to the values
// shown in the tooltips/overlay
@SubscribeEvent(priority=EventPriority.LOWEST)
public void getFoodValues(FoodEvent.GetFoodValues event)
{
if (FoodHelper.isFoodContainer(event.food))
{
event.foodValues = event.unmodifiedFoodValues;
}
}
}
| java/squeek/spiceoflife/items/ItemFoodContainer.java | package squeek.spiceoflife.items;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.EnumAction;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IIcon;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.item.ItemTossEvent;
import squeek.applecore.api.food.FoodEvent;
import squeek.applecore.api.food.FoodValues;
import squeek.applecore.api.food.IEdible;
import squeek.spiceoflife.ModConfig;
import squeek.spiceoflife.ModInfo;
import squeek.spiceoflife.helpers.*;
import squeek.spiceoflife.helpers.MealPrioritizationHelper.InventoryFoodInfo;
import squeek.spiceoflife.inventory.ContainerFoodContainer;
import squeek.spiceoflife.inventory.FoodContainerInventory;
import squeek.spiceoflife.inventory.INBTInventoryHaver;
import squeek.spiceoflife.inventory.NBTInventory;
import squeek.spiceoflife.network.NetworkHelper;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemFoodContainer extends Item implements INBTInventoryHaver, IEdible
{
private IIcon iconOpenEmpty;
private IIcon iconOpenFull;
public int numSlots;
public String itemName;
public static final Random random = new Random();
public static final String TAG_KEY_INVENTORY = "Inventory";
public static final String TAG_KEY_OPEN = "Open";
public static final String TAG_KEY_UUID = "UUID";
public ItemFoodContainer(String itemName, int numSlots)
{
super();
this.itemName = itemName;
this.numSlots = numSlots;
setMaxStackSize(1);
setTextureName(ModInfo.MODID.toLowerCase() + ":" + itemName);
setUnlocalizedName(ModInfo.MODID.toLowerCase() + "." + itemName);
setCreativeTab(CreativeTabs.tabMisc);
// for ItemTossEvent
MinecraftForge.EVENT_BUS.register(this);
}
public boolean isEmpty(ItemStack itemStack)
{
return NBTInventory.isInventoryEmpty(getInventoryTag(itemStack));
}
public boolean isFull(ItemStack itemStack)
{
return getInventory(itemStack).isInventoryFull();
}
public boolean isOpen(ItemStack itemStack)
{
return itemStack.hasTagCompound() ? itemStack.getTagCompound().getBoolean(TAG_KEY_OPEN) : false;
}
public void setIsOpen(ItemStack itemStack, boolean isOpen)
{
NBTTagCompound baseTag = getOrInitBaseTag(itemStack);
baseTag.setBoolean(TAG_KEY_OPEN, isOpen);
}
public UUID getUUID(ItemStack itemStack)
{
return UUID.fromString(getOrInitBaseTag(itemStack).getString(TAG_KEY_UUID));
}
public NBTTagCompound getOrInitBaseTag(ItemStack itemStack)
{
if (!itemStack.hasTagCompound())
itemStack.setTagCompound(new NBTTagCompound());
NBTTagCompound baseTag = itemStack.getTagCompound();
if (!baseTag.hasKey(TAG_KEY_UUID))
baseTag.setString(TAG_KEY_UUID, UUID.randomUUID().toString());
return baseTag;
}
public NBTTagCompound getInventoryTag(ItemStack itemStack)
{
NBTTagCompound baseTag = getOrInitBaseTag(itemStack);
if (!baseTag.hasKey(TAG_KEY_INVENTORY))
baseTag.setTag(TAG_KEY_INVENTORY, new NBTTagCompound());
return baseTag.getCompoundTag(TAG_KEY_INVENTORY);
}
public FoodContainerInventory getInventory(ItemStack itemStack)
{
return new FoodContainerInventory(this, itemStack);
}
public void tryDumpFoodInto(ItemStack itemStack, IInventory inventory, EntityPlayer player)
{
FoodContainerInventory foodContainerInventory = getInventory(itemStack);
for (int slotNum = 0; slotNum < foodContainerInventory.getSizeInventory(); slotNum++)
{
ItemStack stackInSlot = foodContainerInventory.getStackInSlot(slotNum);
if (stackInSlot == null)
continue;
stackInSlot = InventoryHelper.insertStackIntoInventory(stackInSlot, inventory);
foodContainerInventory.setInventorySlotContents(slotNum, stackInSlot);
}
}
public void tryPullFoodFrom(ItemStack itemStack, IInventory inventory, EntityPlayer player)
{
List<InventoryFoodInfo> foodsToPull = MealPrioritizationHelper.findBestFoodsForPlayerAccountingForVariety(player, inventory);
if (foodsToPull.size() > 0)
{
FoodContainerInventory foodContainerInventory = getInventory(itemStack);
for (InventoryFoodInfo foodToPull : foodsToPull)
{
ItemStack stackInSlot = inventory.getStackInSlot(foodToPull.slotNum);
if (stackInSlot == null)
continue;
stackInSlot = InventoryHelper.insertStackIntoInventoryOnce(stackInSlot, foodContainerInventory);
inventory.setInventorySlotContents(foodToPull.slotNum, stackInSlot);
}
}
}
// necessary to catch tossing items while still in an inventory
@SubscribeEvent
public void onItemToss(ItemTossEvent event)
{
if (event.entityItem.getEntityItem().getItem() instanceof ItemFoodContainer)
{
onDroppedByPlayer(event.entityItem.getEntityItem(), event.player);
}
}
@Override
public boolean onDroppedByPlayer(ItemStack itemStack, EntityPlayer player)
{
if (!player.worldObj.isRemote && player.openContainer != null && player.openContainer instanceof ContainerFoodContainer)
{
ContainerFoodContainer openFoodContainer = (ContainerFoodContainer) player.openContainer;
UUID droppedUUID = getUUID(itemStack);
if (openFoodContainer.getUUID().equals(droppedUUID))
{
// if the cursor item is the open food container, then it will create an infinite loop
// due to the container dropping the cursor item when it is closed
ItemStack itemOnTheCursor = player.inventory.getItemStack();
if (itemOnTheCursor != null && itemOnTheCursor.getItem() instanceof ItemFoodContainer)
{
if (((ItemFoodContainer) itemOnTheCursor.getItem()).getUUID(itemOnTheCursor).equals(droppedUUID))
{
player.inventory.setItemStack(null);
}
}
player.closeScreen();
}
}
return super.onDroppedByPlayer(itemStack, player);
}
public boolean canBeEatenFrom(ItemStack stack)
{
return isOpen(stack) && !isEmpty(stack);
}
public boolean canPlayerEatFrom(EntityPlayer player, ItemStack stack)
{
return canBeEatenFrom(stack) && player.canEat(false);
}
@Override
public void onUpdate(ItemStack itemStack, World world, Entity ownerEntity, int par4, boolean par5)
{
if (!world.isRemote && ownerEntity instanceof EntityPlayer && isOpen(itemStack) && !isEmpty(itemStack))
{
EntityPlayer player = (EntityPlayer) ownerEntity;
if (!player.isSneaking() && MovementHelper.getDidJumpLastTick(player))
{
float chanceToDrop = ModConfig.FOOD_CONTAINERS_CHANCE_TO_DROP_FOOD;
if (player.isSprinting())
chanceToDrop *= 2f;
if (chanceToDrop > 0 && random.nextFloat() <= chanceToDrop)
{
ItemStack itemToDrop = InventoryHelper.removeRandomSingleItemFromInventory(getInventory(itemStack), random);
player.dropPlayerItemWithRandomChoice(itemToDrop, true);
}
}
}
super.onUpdate(itemStack, world, ownerEntity, par4, par5);
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void addInformation(ItemStack itemStack, EntityPlayer player, List toolTip, boolean isAdvanced)
{
super.addInformation(itemStack, player, toolTip, isAdvanced);
String openCloseLineColor = EnumChatFormatting.GRAY.toString();
if (isOpen(itemStack))
{
toolTip.add(openCloseLineColor + StatCollector.translateToLocalFormatted("spiceoflife.tooltip.to.close.food.container"));
if (ModConfig.FOOD_CONTAINERS_CHANCE_TO_DROP_FOOD > 0)
toolTip.add(EnumChatFormatting.GOLD.toString() + EnumChatFormatting.ITALIC + StatCollector.translateToLocal("spiceoflife.tooltip.can.spill.food"));
}
else
toolTip.add(openCloseLineColor + StatCollector.translateToLocalFormatted("spiceoflife.tooltip.to.open.food.container"));
}
@Override
public IIcon getIconIndex(ItemStack itemStack)
{
if (isOpen(itemStack))
{
return isEmpty(itemStack) ? iconOpenEmpty : iconOpenFull;
}
return super.getIconIndex(itemStack);
}
@Override
public IIcon getIcon(ItemStack itemStack, int renderPass)
{
return getIconIndex(itemStack);
}
@Override
public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ)
{
if (!world.isRemote && isOpen(itemStack))
{
IInventory inventoryHit = InventoryHelper.getInventoryAtLocation(world, x, y, z);
if (inventoryHit != null)
{
tryDumpFoodInto(itemStack, inventoryHit, player);
tryPullFoodFrom(itemStack, inventoryHit, player);
return true;
}
}
return super.onItemUseFirst(itemStack, player, world, x, y, z, side, hitX, hitY, hitZ);
}
@Override
public EnumAction getItemUseAction(ItemStack itemStack)
{
if (canBeEatenFrom(itemStack))
return EnumAction.eat;
else
return EnumAction.none;
}
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player)
{
if (player.isSneaking())
{
setIsOpen(itemStack, !isOpen(itemStack));
}
else if (canPlayerEatFrom(player, itemStack))
{
player.setItemInUse(itemStack, getMaxItemUseDuration(itemStack));
}
else if (!isOpen(itemStack))
{
GuiHelper.openGuiOfItemStack(player, itemStack);
setIsOpen(itemStack, true);
}
return super.onItemRightClick(itemStack, world, player);
}
@Override
public int getMaxItemUseDuration(ItemStack itemStack)
{
return 32;
}
@Override
public ItemStack onEaten(ItemStack itemStack, World world, EntityPlayer player)
{
IInventory inventory = getInventory(itemStack);
int slotWithBestFood = MealPrioritizationHelper.findBestFoodForPlayerToEat(player, inventory);
ItemStack foodToEat = inventory.getStackInSlot(slotWithBestFood);
if (foodToEat != null)
{
foodToEat.onFoodEaten(world, player);
if (foodToEat.stackSize <= 0)
foodToEat = null;
inventory.setInventorySlotContents(slotWithBestFood, foodToEat);
}
return super.onEaten(itemStack, world, player);
}
public ItemStack getBestFoodForPlayerToEat(ItemStack itemStack, EntityPlayer player)
{
IInventory inventory = getInventory(itemStack);
int slotWithBestFood = MealPrioritizationHelper.findBestFoodForPlayerToEat(player, inventory);
ItemStack foodToEat = inventory.getStackInSlot(slotWithBestFood);
return foodToEat;
}
@SideOnly(Side.CLIENT)
@Override
public void registerIcons(IIconRegister iconRegister)
{
super.registerIcons(iconRegister);
iconOpenEmpty = iconRegister.registerIcon(getIconString() + "_open_empty");
iconOpenFull = iconRegister.registerIcon(getIconString() + "_open_full");
}
@Override
public int getSizeInventory()
{
return numSlots;
}
@Override
public String getInvName(NBTInventory inventory)
{
return this.getItemStackDisplayName(null);
}
@Override
public boolean isInvNameLocalized(NBTInventory inventory)
{
return false;
}
@Override
public int getInventoryStackLimit(NBTInventory inventory)
{
return ModConfig.FOOD_CONTAINERS_MAX_STACKSIZE;
}
@Override
public void onInventoryChanged(NBTInventory inventory)
{
}
@Override
public boolean isItemValidForSlot(NBTInventory inventory, int slotNum, ItemStack itemStack)
{
return FoodHelper.isFood(itemStack) && FoodHelper.isDirectlyEdible(itemStack);
}
/*
* IEdible implementation
*/
@Override
public FoodValues getFoodValues(ItemStack itemStack)
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
{
// the client uses the food values for tooltips/etc, so it should
// inherit them from the food that will be eaten
return FoodValues.get(getBestFoodForPlayerToEat(itemStack, NetworkHelper.getClientPlayer()));
}
else
{
// the server only needs to know that food values are non-null
// this is used for the isFood check
return new FoodValues(0, 0f);
}
}
// necessary to stop food containers themselves being modified
// for example, HO's modFoodDivider was being applied to the values
// shown in the tooltips/overlay
@SubscribeEvent(priority=EventPriority.LOWEST)
public void getFoodValues(FoodEvent.GetFoodValues event)
{
if (FoodHelper.isFoodContainer(event.food))
{
event.foodValues = event.unmodifiedFoodValues;
}
}
}
| Fix food containers interacting with inventories that players can't interact with
* Closes #51
| java/squeek/spiceoflife/items/ItemFoodContainer.java | Fix food containers interacting with inventories that players can't interact with * Closes #51 | <ide><path>ava/squeek/spiceoflife/items/ItemFoodContainer.java
<ide> if (!world.isRemote && isOpen(itemStack))
<ide> {
<ide> IInventory inventoryHit = InventoryHelper.getInventoryAtLocation(world, x, y, z);
<del> if (inventoryHit != null)
<add> if (inventoryHit != null && inventoryHit.isUseableByPlayer(player))
<ide> {
<ide> tryDumpFoodInto(itemStack, inventoryHit, player);
<ide> tryPullFoodFrom(itemStack, inventoryHit, player); |
|
Java | epl-1.0 | 92cc74211ee328ac8328372d14032737f4d8961c | 0 | brunchboy/beat-link | package org.deepsymmetry.beatlink;
import org.deepsymmetry.beatlink.dbserver.BinaryField;
import org.deepsymmetry.beatlink.dbserver.Client;
import org.deepsymmetry.beatlink.dbserver.Message;
import org.deepsymmetry.beatlink.dbserver.NumberField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Watches for new tracks to be loaded on players, and queries the
* appropriate player for the metadata information when that happens.<p>
*
* @author James Elliott
*/
public class MetadataFinder {
private static final Logger logger = LoggerFactory.getLogger(MetadataFinder.class.getName());
/**
* The default value we will use for timeouts on opening and reading from sockets.
*/
public static final int DEFAULT_SOCKET_TIMEOUT = 10000;
/**
* The number of milliseconds after which an attempt to open or read from a socket will fail.
*/
private static int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
/**
* Set how long we will wait for a socket to connect or for a read operation to complete.
* Adjust this if your players or network require it.
*
* @param timeout after how many milliseconds will an attempt to open or read from a socket fail
*/
public static void setSocketTimeout(int timeout) {
socketTimeout = timeout;
}
/**
* Check how long we will wait for a socket to connect or for a read operation to complete.
* Adjust this if your players or network require it.
*
* @return the number of milliseconds after which an attempt to open or read from a socket will fail
*/
public static int getSocketTimeout() {
return socketTimeout;
}
/**
* Given a status update from a CDJ, find the metadata for the track that it has loaded, if any.
*
* @param status the CDJ status update that will be used to determine the loaded track and ask the appropriate
* player for metadata about it
* @return the metadata that was obtained, if any
*/
public static TrackMetadata requestMetadataFrom(CdjStatus status) {
if (status.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK || status.getRekordboxId() == 0) {
return null;
}
return requestMetadataFrom(status.getTrackSourcePlayer(), status.getTrackSourceSlot(), status.getRekordboxId());
}
/**
* Receive some bytes from the player we are requesting metadata from.
*
* @param is the input stream associated with the player metadata socket.
* @return the bytes read.
*
* @throws IOException if there is a problem reading the response
*/
private static byte[] receiveBytes(InputStream is) throws IOException {
byte[] buffer = new byte[8192];
int len = (is.read(buffer));
if (len < 1) {
throw new IOException("receiveBytes read " + len + " bytes.");
}
return Arrays.copyOf(buffer, len);
}
/**
* Receive an expected number of bytes from the player, logging a warning if we get a different number of them.
*
* @param is the input stream associated with the player metadata socket.
* @param size the number of bytes we expect to receive.
* @param description the type of response being processed, for use in the warning message.
* @return the bytes read.
*
* @throws IOException if there is a problem reading the response.
*/
private static byte[] readResponseWithExpectedSize(InputStream is, int size, String description) throws IOException {
byte[] result = receiveBytes(is);
if (result.length != size) {
logger.warn("Expected " + size + " bytes while reading " + description + " response, received " + result.length);
}
return result;
}
/**
* Finds a valid player number that is currently visible but which is different from the one specified, so it can
* be used as the source player for a query being sent to the specified one. If the virtual CDJ is running on an
* acceptable player number (which must be 1-4 to request metadata from an actual CDJ, but can be anything if we
* are talking to rekordbox), uses that, since it will always be safe. Otherwise, picks an existing player number,
* but this will cause the query to fail if that player has mounted media from the player we are querying.
*
* @param player the player to which a metadata query is being sent
* @param slot the media slot from which the track of interest was loaded
*
* @return some other currently active player number
*
* @throws IllegalStateException if there is no other player number available to use.
*/
private static int chooseAskingPlayerNumber(int player, CdjStatus.TrackSourceSlot slot) {
final int fakeDevice = VirtualCdj.getDeviceNumber();
if (slot == CdjStatus.TrackSourceSlot.COLLECTION || (fakeDevice >= 1 && fakeDevice <= 4)) {
return fakeDevice;
}
for (DeviceAnnouncement candidate : DeviceFinder.currentDevices()) {
final int realDevice = candidate.getNumber();
if (realDevice != player && realDevice >= 1 && realDevice <= 4) {
final DeviceUpdate lastUpdate = VirtualCdj.getLatestStatusFor(realDevice);
if (lastUpdate != null && lastUpdate instanceof CdjStatus &&
((CdjStatus)lastUpdate).getTrackSourcePlayer() != player) {
return candidate.getNumber();
}
}
}
throw new IllegalStateException("No player number available to query player " + player +
". If they are on the network, they must be using Link to play a track from that player, " +
"so we can't use their ID.");
}
/**
* Request metadata for a specific track ID, given a connection to a player that has already been set up.
* Separated into its own method so it could be used multiple times on the same connection when gathering
* all track metadata.
*
* @param rekordboxId the track of interest
* @param slot identifies the media slot we are querying
* @param client the dbserver client that is communicating with the appropriate player
*
* @return the retrieved metadata, or {@code null} if there is no such track
*
* @throws IOException if there is a communication problem
*/
private static TrackMetadata getTrackMetadata(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)
throws IOException {
// Send the metadata menu request
Message response = client.menuRequest(Message.KnownType.METADATA_REQ, Message.MenuIdentifier.MAIN_MENU, slot,
new NumberField(rekordboxId));
final long count = response.getMenuResultsCount();
if (count == Message.NO_MENU_RESULTS_AVAILABLE) {
return null;
}
// Gather all the metadata menu items
final List<Message> items = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, response);
TrackMetadata result = new TrackMetadata(rekordboxId, items);
if (result.getArtworkId() != 0) {
result = result.withArtwork(requestArtwork(result.getArtworkId(), slot, client));
}
return result;
}
/**
* Requests the beat grid for a specific track ID, given a connection to a player that has already been set up.
* @param rekordboxId the track of interest
* @param slot identifies the media slot we are querying
* @param client the dbserver client that is communicating with the appropriate player
*
* @return the retrieved beat grid, or {@code null} if there is no such track
*
* @throws IOException if there is a communication problem
*/
private static BeatGrid getBeatGrid(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)
throws IOException {
Message response = client.simpleRequest(Message.KnownType.BEAT_GRID_REQ, null,
client.buildRMS1(Message.MenuIdentifier.DATA, slot), new NumberField(rekordboxId));
if (response.knownType == Message.KnownType.BEAT_GRID) {
return new BeatGrid(response);
}
logger.error("Unexpected response type when requesting beat grid: {}", response);
return null;
}
/**
* Request the list of all tracks in the specified slot, given a connection to a player that has already been
* set up.
*
* @param slot identifies the media slot we are querying
* @param client the dbserver client that is communicating with the appropriate player
*
* @return the retrieved track list entry items
*
* @throws IOException if there is a communication problem
*/
private static List<Message> getFullTrackList(CdjStatus.TrackSourceSlot slot, Client client)
throws IOException {
// Send the metadata menu request
Message response = client.menuRequest(Message.KnownType.TRACK_LIST_REQ, Message.MenuIdentifier.MAIN_MENU, slot,
new NumberField(0));
final long count = response.getMenuResultsCount();
if (count == Message.NO_MENU_RESULTS_AVAILABLE) {
return Collections.emptyList();
}
// Gather all the metadata menu items
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, response);
}
/**
* Look up track metadata from a cache.
*
* @param cache the appropriate metadata cache file
* @param rekordboxId the track whose metadata is desired
*
* @return the cached metadata, including album art (if available), or {@code null}
*/
private static TrackMetadata getCachedMetadata(ZipFile cache, int rekordboxId) {
ZipEntry entry = cache.getEntry(getMetadataEntryName(rekordboxId));
if (entry != null) {
DataInputStream is = null;
try {
is = new DataInputStream(cache.getInputStream(entry));
List<Message> items = new LinkedList<Message>();
Message current = Message.read(is);
while (current.messageType.getValue() == Message.KnownType.MENU_ITEM.protocolValue) {
items.add(current);
current = Message.read(is);
}
TrackMetadata result = new TrackMetadata(rekordboxId, items);
try {
is.close();
} catch (Exception e) {
is = null;
logger.error("Problem closing Zip File input stream after reading metadata entry", e);
}
if (result.getArtworkId() != 0) {
entry = cache.getEntry(getArtworkEntryName(result));
if (entry != null) {
is = new DataInputStream(cache.getInputStream(entry));
try {
byte[] imageBytes = new byte[(int)entry.getSize()];
is.readFully(imageBytes);
result = result.withArtwork(ByteBuffer.wrap(imageBytes).asReadOnlyBuffer());
} catch (Exception e) {
logger.error("Problem reading artwork from metadata cache, leaving as null", e);
}
}
}
return result;
} catch (IOException e) {
if (is != null) {
try {
is.close();
} catch (Exception e2) {
logger.error("Problem closing ZipFile input stream after exception", e2);
}
}
logger.error("Problem reading metadata from cache file, returning null", e);
}
}
return null;
}
/**
* Look up a beat grid in a metadata cache.
*
* @param cache the appropriate metadata cache file
* @param rekordboxId the track whose beat grid is desired
*
* @return the cached beat grid (if available), or {@code null}
*/
private static BeatGrid getCachedBeatGrid(ZipFile cache, int rekordboxId) {
ZipEntry entry = cache.getEntry(getBeatGridEntryName(rekordboxId));
if (entry != null) {
DataInputStream is = null;
try {
is = new DataInputStream(cache.getInputStream(entry));
byte[] gridBytes = new byte[(int)entry.getSize()];
is.readFully(gridBytes);
try {
is.close();
} catch (Exception e) {
is = null;
logger.error("Problem closing Zip File input stream after reading beat grid entry", e);
}
return new BeatGrid(ByteBuffer.wrap(gridBytes).asReadOnlyBuffer());
} catch (IOException e) {
if (is != null) {
try {
is.close();
} catch (Exception e2) {
logger.error("Problem closing ZipFile input stream after exception", e2);
}
}
logger.error("Problem reading beat grid from cache file, returning null", e);
}
}
return null;
}
/**
* Ask the specified player for metadata about the track in the specified slot with the specified rekordbox ID.
*
* @param player the player number whose track is of interest
* @param slot the slot in which the track can be found
* @param rekordboxId the track of interest
*
* @return the metadata, if any
*
* @throws IllegalStateException if a metadata cache is being created amd we need to talk to the CDJs
*/
public static synchronized TrackMetadata requestMetadataFrom(int player, CdjStatus.TrackSourceSlot slot,
int rekordboxId) {
// First check if we are using cached data for this request
ZipFile cache = getMetadataCache(player, slot);
if (cache != null) {
return getCachedMetadata(cache, rekordboxId);
}
// TODO: Once we understand and track cue points, keep an in-memory cache of any loaded hot-cue tracks.
if (passive) {
return null; // We are not allowed to actively query for metadata
}
// We need to perform an actual query, so at this point we need to bail if a cache is being created
failIfCreatingCache();
final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getLatestAnnouncementFrom(player);
final int dbServerPort = getPlayerDBServerPort(player);
if (deviceAnnouncement == null || dbServerPort < 0) {
return null; // If the device isn't known, or did not provide a database server, we can't get metadata.
}
final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(player, slot);
Socket socket = null;
try {
InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort);
socket = new Socket();
socket.connect(address, socketTimeout);
socket.setSoTimeout(socketTimeout);
Client client = new Client(socket, player, posingAsPlayerNumber);
return getTrackMetadata(rekordboxId, slot, client);
} catch (Exception e) {
logger.warn("Problem requesting metadata", e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
logger.warn("Problem closing metadata request socket", e);
}
}
}
return null;
}
// TODO: Add method that enumerates a playlist or folder, then one that caches metadata from a playlist.
/**
* Ask the specified player for the beat grid pf the track in the specified slot with the specified rekordbox ID.
*
* @param player the player number whose track is of interest
* @param slot the slot in which the track can be found
* @param rekordboxId the track of interest
*
* @return the beat grid, if any
*
* @throws IllegalStateException if a metadata cache is being created and we need to talk to the CDJs
*/
public static synchronized BeatGrid requestBeatGridFrom(int player, CdjStatus.TrackSourceSlot slot, int rekordboxId) {
// First check if we are using cached data for this request
ZipFile cache = getMetadataCache(player, slot);
if (cache != null) {
return getCachedBeatGrid(cache, rekordboxId);
}
if (passive) {
return null; // We are not allowed to actively query for metadata
}
// We need to perform an actual query, so at this point we need to bail if a cache is being created
failIfCreatingCache();
final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getLatestAnnouncementFrom(player);
final int dbServerPort = getPlayerDBServerPort(player);
if (deviceAnnouncement == null || dbServerPort < 0) {
return null; // If the device isn't known, or did not provide a database server, we can't get metadata.
}
final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(player, slot);
Socket socket = null;
try {
InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort);
socket = new Socket();
socket.connect(address, socketTimeout);
Client client = new Client(socket, player, posingAsPlayerNumber);
return getBeatGrid(rekordboxId, slot, client);
} catch (Exception e) {
logger.warn("Problem requesting beat grid", e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
logger.warn("Problem closing metadata request socket", e);
}
}
}
return null;
}
/**
* Creates a metadata cache archive file of all tracks in the specified slot on the specified player. Any
* previous contents of the specified file will be replaced.
*
* @param player the player number whose media library is to have its metdata cached
* @param slot the slot in which the media to be cached can be found
* @param cache the file into which the metadata cache should be written
*
* @throws IOException if there is a problem communicating with the player or writing the cache file.
*/
public static void createMetadataCache(int player, CdjStatus.TrackSourceSlot slot, File cache)
throws IOException {
createMetadataCache(player, slot, cache, null);
}
/**
* The root under which all zip file entries will be created in our cache metadata files.
*/
private static final String CACHE_PREFIX = "BLTMetaCache/";
/**
* The file entry whose content will be the cache format identifier.
*/
private static final String CACHE_FORMAT_ENTRY = CACHE_PREFIX + "version";
/**
* The prefix for cache file entries that will store track metadata.
*/
private static final String CACHE_METADATA_ENTRY_PREFIX = CACHE_PREFIX + "metadata/";
/**
* The prefix for cache file entries that will store album art.
*/
private static final String CACHE_ART_ENTRY_PREFIX = CACHE_PREFIX + "artwork/";
/**
* The prefix for cache file entries that will store beat grids.
*/
private static final String CACHE_BEAT_GRID_ENTRY_PREFIX = CACHE_PREFIX + "beatgrid/";
/**
* The comment string used to identify a ZIP file as one of our metadata caches.
*/
public static final String CACHE_FORMAT_IDENTIFIER = "BeatLink Metadata Cache version 1";
/**
* Used to mark the end of the metadata items in each cache entry, just like when reading from the server.
*/
private static final Message MENU_FOOTER_MESSAGE = new Message(0, Message.KnownType.MENU_FOOTER);
/**
* Finish the process of copying a list of tracks to a metadata cache, once they have been listed. This code
* is shared between the implementations that work with the full track list and with playlists.
*
* @param trackListEntries the list of menu items identifying which tracks need to be copied to the metadata
* cache
* @param client the connection to the dbserver on the player whose metadata is being cached
* @param slot the slot in which the media to be cached can be found
* @param cache the file into which the metadata cache should be written
* @param listener will be informed after each track is added to the cache file being created and offered
* the opportunity to cancel the process
*
* @throws IOException if there is a problem communicating with the player or writing the cache file.
*/
private static void copyTracksToCache(List<Message> trackListEntries, Client client, CdjStatus.TrackSourceSlot slot,
File cache, MetadataCreationUpdateListener listener)
throws IOException {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
ZipOutputStream zos = null;
WritableByteChannel channel = null;
final Set<Integer> artworkAdded = new HashSet<Integer>();
try {
fos = new FileOutputStream(cache);
bos = new BufferedOutputStream(fos);
zos = new ZipOutputStream(bos);
zos.setMethod(ZipOutputStream.DEFLATED);
// Add a marker so we can recognize this as a metadata archive. I would use the ZipFile comment, but
// that is not available until Java 7, and Beat Link is supposed to be backwards compatible with Java 6.
ZipEntry zipEntry = new ZipEntry(CACHE_FORMAT_ENTRY);
zos.putNextEntry(zipEntry);
zos.write(CACHE_FORMAT_IDENTIFIER.getBytes("UTF-8"));
// Write the actual metadata entries
channel = Channels.newChannel(zos);
final int totalToCopy = trackListEntries.size();
int tracksCopied = 0;
for (Message entry : trackListEntries) {
if (entry.getMenuItemType() != Message.MenuItemType.TRACK_LIST_ENTRY) {
throw new IOException("Received unexpected item type. Needed TRACK_LIST_ENTRY, got: " + entry);
}
int rekordBoxId = (int)((NumberField)entry.arguments.get(1)).getValue();
TrackMetadata track = getTrackMetadata(rekordBoxId, slot, client);
logger.debug("Adding metadata with ID {}", rekordBoxId);
zipEntry = new ZipEntry(getMetadataEntryName(rekordBoxId));
zos.putNextEntry(zipEntry);
for (Message metadataItem : track.rawItems) {
client.writeMessage(metadataItem, channel);
}
client.writeMessage(MENU_FOOTER_MESSAGE, channel); // So we know to stop reading
// Now the album art, if any
if (track.getRawArtwork() != null && !artworkAdded.contains(track.getArtworkId())) {
logger.debug("Adding artwork with ID {}", track.getArtworkId());
zipEntry = new ZipEntry(getArtworkEntryName(track));
zos.putNextEntry(zipEntry);
Util.writeFully(track.getRawArtwork(), channel);
}
BeatGrid beatGrid = getBeatGrid(rekordBoxId, slot, client);
if (beatGrid != null) {
logger.debug("Adding beat grid with ID {}", rekordBoxId);
zipEntry = new ZipEntry(getBeatGridEntryName(rekordBoxId));
zos.putNextEntry(zipEntry);
Util.writeFully(beatGrid.getRawData(), channel);
}
// TODO: Include waveforms (once supported), etc.
if (listener != null) {
if (!listener.cacheUpdateContinuing(track, ++tracksCopied, totalToCopy)) {
logger.info("Track metadata cache creation canceled by listener");
cache.delete();
return;
}
}
}
} finally {
try {
if (channel != null) {
channel.close();
}
} catch (Exception e) {
logger.error("Problem closing byte channel for writing to metadata cache", e);
}
try {
if (zos != null) {
zos.close();
}
} catch (Exception e) {
logger.error("Problem closing Zip Output Stream of metadata cache", e);
}
try {
if (bos != null) {
bos.close();
}
} catch (Exception e) {
logger.error("Problem closing Buffered Output Stream of metadata cahce", e);
}
try {
if (fos != null) {
fos.close();
}
} catch (Exception e) {
logger.error("Problem closing File Output Stream of metadata cache", e);
}
}
}
/**
* Names the appropriate zip file entry for caching a track's metadata.
*
* @param rekordBoxId the id of the track being cached or looked up
*
* @return the name of the entry where that track's metadata should be stored
*/
private static String getMetadataEntryName(int rekordBoxId) {
return CACHE_METADATA_ENTRY_PREFIX + rekordBoxId;
}
/**
* Names the appropriate zip file entry for caching a track's album art.
*
* @param track the track being cached or looked up
*
* @return the name of entry where that track's artwork should be stored
*/
private static String getArtworkEntryName(TrackMetadata track) {
return CACHE_ART_ENTRY_PREFIX + track.getArtworkId() + ".jpg";
}
/**
* Names the appropriate zip file entry for caching a track's beat grid.
*
* @param rekordBoxId the id of the track being cached or looked up
*
* @return the name of the entry where that track's beat grid should be stored
*/
private static String getBeatGridEntryName(int rekordBoxId) {
return CACHE_BEAT_GRID_ENTRY_PREFIX + rekordBoxId;
}
/**
* Is set to {@code true} when a lengthy cache creation process is underway, to prevent other requests that might
* interfere with it.
*/
private static boolean creatingCache = false;
/**
* Record whether cache creation is taking place, so we can block other inquiries during that process.
*
* @param inProgress {@code true} if we are building a metadata cache file
*
* @throws IllegalStateException if a cache is already being created
*/
private static synchronized void setCreatingCache(boolean inProgress) {
if (creatingCache && inProgress) {
throw new IllegalStateException("Already creating a metadata cache");
}
creatingCache = inProgress;
}
/**
* Check whether cache creation is taking place, so we can block other inquiries during that process.
*
* @throws IllegalStateException if a cache is being created
*/
private static synchronized void failIfCreatingCache() {
if (creatingCache) {
throw new IllegalStateException("Cannot perform the requested operation while a metadata cache is being created");
}
}
/**
* Creates a metadata cache archive file of all tracks in the specified slot on the specified player. Any
* previous contents of the specified file will be replaced. If a non-{@code null} {@code listener} is
* supplied, its {@link MetadataCreationUpdateListener#cacheUpdateContinuing(TrackMetadata, int, int)} method
* will be called after each track is added to the cache, allowing it to display progress updates to the user,
* and to continue or cancel the process by returning {@code true} or {@code false}.
*
* Because this takes a huge amount of time relative to CDJ status updates, it can only be performed while
* the MetadataFinder is in passive mode.
*
* @param player the player number whose media library is to have its metdata cached
* @param slot the slot in which the media to be cached can be found
* @param cache the file into which the metadata cache should be written
* @param listener will be informed after each track is added to the cache file being created and offered
* the opportunity to cancel the process
*
* @throws IOException if there is a problem communicating with the player or writing the cache file
* @throws IllegalStateException if the MetadataFinder is not running or not in passive mode when this is called,
* or if another cache is already in the process of being created
*/
public static void createMetadataCache(int player, CdjStatus.TrackSourceSlot slot, File cache,
MetadataCreationUpdateListener listener)
throws IOException {
if (!running) {
throw new IllegalStateException("must be running to create a metadata cache");
}
if (!passive) {
throw new IllegalStateException("must be in passive mode to create a metadata cache");
}
final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getLatestAnnouncementFrom(player);
final int dbServerPort = getPlayerDBServerPort(player);
if (deviceAnnouncement == null || dbServerPort < 0) {
throw new IOException("Unable to find dbserver on player " + player);
}
final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(player, slot);
Socket socket = null;
Client client = null;
try {
setCreatingCache(true);
cache.delete();
InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort);
socket = new Socket();
socket.connect(address, socketTimeout);
client = new Client(socket, player, posingAsPlayerNumber);
copyTracksToCache(getFullTrackList(slot, client), client, slot, cache, listener);
} finally {
try {
if (client != null) {
client.close();
}
} catch (Exception e) {
logger.error("Problem closing dbserver client when building metadata cache", e);
}
try {
if (socket != null) {
socket.close();
}
} catch (Exception e) {
logger.error("Problem closing socket when building metadata cache", e);
}
setCreatingCache(false);
}
}
/**
* Request the artwork associated with a track whose metadata is being retrieved.
*
* @param artworkId identifies the album art to retrieve
* @param slot the slot identifier from which the track was loaded
* @param client the dbserver client that is communicating with the appropriate player
*
* @return the track's artwork, or null if none is available
*
* @throws IOException if there is a problem communicating with the player
*/
private static ByteBuffer requestArtwork(int artworkId, CdjStatus.TrackSourceSlot slot, Client client)
throws IOException {
// Send the artwork request
Message response = client.simpleRequest(Message.KnownType.ALBUM_ART_REQ, Message.KnownType.ALBUM_ART,
client.buildRMS1(Message.MenuIdentifier.DATA, slot), new NumberField((long)artworkId));
// Create an image from the response bytes
return ((BinaryField)response.arguments.get(3)).getValue();
}
/**
* Keeps track of the current metadata known for each player.
*/
private static final Map<Integer, TrackMetadata> metadata = new HashMap<Integer, TrackMetadata>();
/**
* Keeps track of the previous update from each player that we retrieved metadata about, to check whether a new
* track has been loaded.
*/
private static final Map<InetAddress, CdjStatus> lastUpdates = new HashMap<InetAddress, CdjStatus>();
/**
* A queue used to hold CDJ status updates we receive from the {@link VirtualCdj} so we can process them on a
* lower priority thread, and not hold up delivery to more time-sensitive listeners.
*/
private static LinkedBlockingDeque<CdjStatus> pendingUpdates = new LinkedBlockingDeque<CdjStatus>(100);
/**
* Our update listener just puts appropriate device updates on our queue, so we can process them on a lower
* priority thread, and not hold up delivery to more time-sensitive listeners.
*/
private static final DeviceUpdateListener updateListener = new DeviceUpdateListener() {
@Override
public void received(DeviceUpdate update) {
logger.debug("Received device update {}", update);
if (update instanceof CdjStatus) {
if (!pendingUpdates.offerLast((CdjStatus)update)) {
logger.warn("Discarding CDJ update because our queue is backed up.");
}
}
}
};
/**
* Keeps track of the database server ports of all the players we have seen on the network.
*/
private static final Map<Integer, Integer> dbServerPorts = new HashMap<Integer, Integer>();
/**
* Look up the database server port reported by a given player.
*
* @param player the player number of interest.
*
* @return the port number on which its database server is running, or -1 if unknown.
*/
public static synchronized int getPlayerDBServerPort(int player) {
Integer result = dbServerPorts.get(player);
if (result == null) {
return -1;
}
return result;
}
/**
* Record the database server port reported by a player.
*
* @param player the player number whose server port has been determined.
* @param port the port number on which the player's database server is running.
*/
private static synchronized void setPlayerDBServerPort(int player, int port) {
dbServerPorts.put(player, port);
}
/**
* The port on which we can request information about a player, including the port on which its database server
* is running.
*/
private static final int DB_SERVER_QUERY_PORT = 12523;
private static final byte[] DB_SERVER_QUERY_PACKET = {
0x00, 0x00, 0x00, 0x0f,
0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x44, 0x42, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, // RemoteDBServer
0x00
};
/**
* Query a player to determine the port on which its database server is running.
*
* @param announcement the device announcement with which we detected a new player on the network.
*/
private static void requestPlayerDBServerPort(DeviceAnnouncement announcement) {
Socket socket = null;
try {
InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT);
socket = new Socket();
socket.connect(address, socketTimeout);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
socket.setSoTimeout(socketTimeout);
os.write(DB_SERVER_QUERY_PACKET);
byte[] response = readResponseWithExpectedSize(is, 2, "database server port query packet");
if (response.length == 2) {
setPlayerDBServerPort(announcement.getNumber(), (int)Util.bytesToNumber(response, 0, 2));
}
} catch (java.net.ConnectException ce) {
logger.info("Player " + announcement.getNumber() +
" doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata.");
} catch (Exception e) {
logger.warn("Problem requesting database server port number", e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
logger.warn("Problem closing database server port request socket", e);
}
}
}
}
/**
* Our announcement listener watches for devices to appear on the network so we can ask them for their database
* server port, and when they disappear discards all information about them.
*/
private static final DeviceAnnouncementListener announcementListener = new DeviceAnnouncementListener() {
@Override
public void deviceFound(final DeviceAnnouncement announcement) {
new Thread(new Runnable() {
@Override
public void run() {
requestPlayerDBServerPort(announcement);
}
}).start();
}
@Override
public void deviceLost(DeviceAnnouncement announcement) {
setPlayerDBServerPort(announcement.getNumber(), -1);
clearMetadata(announcement);
detachMetadataCache(announcement.getNumber(), CdjStatus.TrackSourceSlot.SD_SLOT);
detachMetadataCache(announcement.getNumber(), CdjStatus.TrackSourceSlot.USB_SLOT);
}
};
/**
* Keep track of whether we are running
*/
private static boolean running = false;
/**
* Check whether we are currently running.
*
* @return true if track metadata is being sought for all active players
*/
public static synchronized boolean isRunning() {
return running;
}
/**
* Indicates whether we should use metdata only from caches, never actively requesting it from a player.
*/
private static boolean passive = false;
/**
* Check whether we are configured to use metadata only from caches, never actively requesting it from a player.
*
* @return {@code true} if only cached metadata will be used, or {@code false} if metadata will be requested from
* a player if a track is loaded from a media slot to which no cache has been assigned
*/
public static synchronized boolean isPassive() {
return passive;
}
/**
* Set whether we are configured to use metadata only from caches, never actively requesting it from a player.
*
* @param passive {@code true} if only cached metadata will be used, or {@code false} if metadata will be requested
* from a player if a track is loaded from a media slot to which no cache has been assigned
*
* @throws IllegalStateException if you try to turn off passive mode while a metadata cache is being created
*/
public static synchronized void setPassive(boolean passive) {
if (!passive) {
failIfCreatingCache();
}
MetadataFinder.passive = passive;
}
/**
* We process our updates on a separate thread so as not to slow down the high-priority update delivery thread;
* we perform potentially slow I/O.
*/
private static Thread queueHandler;
/**
* We have received an update that invalidates any previous metadata for that player, so clear it out, and alert
* any listeners.
*
* @param update the update which means we can have no metadata for the associated player
*/
private static synchronized void clearMetadata(CdjStatus update) {
metadata.remove(update.deviceNumber);
lastUpdates.remove(update.address);
deliverTrackMetadataUpdate(update.deviceNumber, null);
}
/**
* We have received notification that a device is no longer on the network, so clear out its metadata.
*
* @param announcement the packet which reported the device’s disappearance
*/
private static synchronized void clearMetadata(DeviceAnnouncement announcement) {
metadata.remove(announcement.getNumber());
lastUpdates.remove(announcement.getAddress());
}
/**
* We have obtained metadata for a device, so store it and alert any listeners.
*
* @param update the update which caused us to retrieve this metadata
* @param data the metadata which we received
*/
private static synchronized void updateMetadata(CdjStatus update, TrackMetadata data) {
metadata.put(update.deviceNumber, data);
lastUpdates.put(update.address, update);
deliverTrackMetadataUpdate(update.deviceNumber, data);
}
/**
* Get all currently known metadata.
*
* @return the track information reported by all current players
*/
public static synchronized Map<Integer, TrackMetadata> getLatestMetadata() {
return Collections.unmodifiableMap(new TreeMap<Integer, TrackMetadata>(metadata));
}
/**
* Look up the track metadata we have for a given player number.
*
* @param player the device number whose track metadata is desired
* @return information about the track loaded on that player, if available
*/
public static synchronized TrackMetadata getLatestMetadataFor(int player) {
return metadata.get(player);
}
/**
* Look up the track metadata we have for a given player, identified by a status update received from that player.
*
* @param update a status update from the player for which track metadata is desired
* @return information about the track loaded on that player, if available
*/
public static TrackMetadata getLatestMetadataFor(DeviceUpdate update) {
return getLatestMetadataFor(update.deviceNumber);
}
/**
* Keep track of the devices we are currently trying to get metadata from in response to status updates.
*/
private final static Set<Integer> activeRequests = new HashSet<Integer>();
/**
* Keeps track of any metadata caches that have been attached for the SD slots of players on the network,
* keyed by player number.
*/
private final static Map<Integer, ZipFile> sdMetadataCaches = new ConcurrentHashMap<Integer, ZipFile>();
/**
* Keeps track of any metadata caches that have been attached for the USB slots of players on the network,
* keyed by player number.
*/
private final static Map<Integer, ZipFile> usbMetadataCaches = new ConcurrentHashMap<Integer, ZipFile>();
/**
* Attach a metadata cache file to a particular player media slot, so the cache will be used instead of querying
* the player for metadata. This supports operation with metadata during shows where DJs are using all four player
* numbers and heavily cross-linking between them.
*
* If the media is ejected from that player slot, the cache will be detached.
*
* @param player the player number for which a metadata cache is to be attached
* @param slot the media slot to which a meta data cache is to be attached
* @param cache the metadata cache to be attached
*
* @throws IOException if there is a problem reading the cache file
* @throws IllegalArgumentException if an invalid player number or slot is supplied
* @throws IllegalStateException if the metadatafinder is not running
*/
public static void attachMetadataCache(int player, CdjStatus.TrackSourceSlot slot, File cache)
throws IOException {
if (!isRunning()) {
throw new IllegalStateException("attachMetadataCache() can't be used if MetadataFinder is not running");
}
if (player < 1 || player > 4 || DeviceFinder.getLatestAnnouncementFrom(player) == null) {
throw new IllegalArgumentException("unable to attach metadata cache for player " + player);
}
ZipFile oldCache = null;
// Open and validate the cache
ZipFile newCache = new ZipFile(cache, ZipFile.OPEN_READ);
ZipEntry zipEntry = newCache.getEntry(CACHE_FORMAT_ENTRY);
InputStream is = newCache.getInputStream(zipEntry);
Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
String tag = null;
if (s.hasNext()) tag = s.next();
if (!CACHE_FORMAT_IDENTIFIER.equals(tag)) {
try {
newCache.close();
} catch (Exception e) {
logger.error("Problem re-closing newly opened candidate metadata cache", e);
}
throw new IOException("File does not contain a Beat Link metadata cache: " + cache +
" (looking for format identifier \"" + CACHE_FORMAT_IDENTIFIER + "\", found: " + tag);
}
switch (slot) {
case USB_SLOT:
oldCache = usbMetadataCaches.put(player, newCache);
break;
case SD_SLOT:
oldCache = sdMetadataCaches.put(player, newCache);
break;
default:
try {
newCache.close();
} catch (Exception e) {
logger.error("Problem re-closing newly opened candidate metadata cache", e);
}
throw new IllegalArgumentException("Cannot cache media for slot " + slot);
}
if (oldCache != null) {
try {
oldCache.close();
} catch (IOException e) {
logger.error("Problem closing previous metadata cache", e);
}
}
deliverCacheUpdate();
}
/**
* Removes any metadata cache file that might have been assigned to a particular player media slot, so metadata
* will be looked up from the player itself.
*
* @param player the player number for which a metadata cache is to be attached
* @param slot the media slot to which a meta data cache is to be attached
*/
public static void detachMetadataCache(int player, CdjStatus.TrackSourceSlot slot) {
ZipFile oldCache = null;
switch (slot) {
case USB_SLOT:
oldCache = usbMetadataCaches.remove(player);
break;
case SD_SLOT:
oldCache = sdMetadataCaches.remove(player);
break;
default:
logger.warn("Ignoring request to remove metadata cache for slot {}", slot);
}
if (oldCache != null) {
try {
oldCache.close();
} catch (IOException e) {
logger.error("Problem closing metadata cache", e);
}
deliverCacheUpdate();
}
}
/**
* Finds the metadata cache file assigned to a particular player media slot, if any.
*
* @param player the player number for which a metadata cache is to be attached
* @param slot the media slot to which a meta data cache is to be attached
*
* @return the zip file being used as a metadata cache for that player and slot, or {@code null} if no cache
* has been attached
*/
public static ZipFile getMetadataCache(int player, CdjStatus.TrackSourceSlot slot) {
switch (slot) {
case USB_SLOT:
return usbMetadataCaches.get(player);
case SD_SLOT:
return sdMetadataCaches.get(player);
default:
return null;
}
}
/**
* Keeps track of any players with mounted SD media.
*/
private static Set<Integer> sdMounts = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());
/**
* Keeps track of any players with mounted USB media.
*/
private static Set<Integer> usbMounts = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());
/**
* Records that there is media mounted in a particular media player slot, updating listeners if this is a change.
*
* @param player the number of the player that has media in the specified slot
* @param slot the slot in which media is mounted
*/
private static void recordMount(int player, CdjStatus.TrackSourceSlot slot) {
switch (slot) {
case USB_SLOT:
if (usbMounts.add(player)) {
deliverCacheUpdate();
}
break;
case SD_SLOT:
if (sdMounts.add(player)) {
deliverCacheUpdate();
}
break;
default:
throw new IllegalArgumentException("Cannot record mounted media in slot " + slot);
}
}
/**
* Records that there is no media mounted in a particular media player slot, updating listeners if this is a change.
*
* @param player the number of the player that has no media in the specified slot
* @param slot the slot in which no media is mounted
*/
private static void removeMount(int player, CdjStatus.TrackSourceSlot slot) {
switch (slot) {
case USB_SLOT:
if (usbMounts.remove(player)) {
deliverCacheUpdate();
}
break;
case SD_SLOT:
if (sdMounts.remove(player)) {
deliverCacheUpdate();
}
break;
default:
logger.warn("Ignoring request to record unmounted media in slot {}", slot);
}
}
/**
* Returns the set of player numbers that currently have media mounted in the specified slot.
*
* @param slot the slot of interest, currently must be either {@code SD_SLOT} or {@code USB_SLOT}
*
* @return the player numbers with media currently mounted in the specified slot
*/
public static Set<Integer> getPlayersWithMediaIn(CdjStatus.TrackSourceSlot slot) {
switch (slot) {
case USB_SLOT:
return Collections.unmodifiableSet(usbMounts);
case SD_SLOT:
return Collections.unmodifiableSet(sdMounts);
default:
throw new IllegalArgumentException("Cannot report mounted media in slot " + slot);
}
}
/**
* Keeps track of the registered cache update listeners.
*/
private static final Set<MetadataCacheUpdateListener> cacheListeners = new HashSet<MetadataCacheUpdateListener>();
/**
* Adds the specified cache update listener to receive updates when a metadata cache is attached or detached.
* If {@code listener} is {@code null} or already present in the set of registered listeners, no exception is
* thrown and no action is performed.
*
* <p>To reduce latency, updates are delivered to listeners directly on the thread that is receiving packets
* from the network, so if you want to interact with user interface objects in listener methods, you need to use
* <code><a href="http://docs.oracle.com/javase/8/docs/api/javax/swing/SwingUtilities.html#invokeLater-java.lang.Runnable-">javax.swing.SwingUtilities.invokeLater(Runnable)</a></code>
* to do so on the Event Dispatch Thread.
*
* Even if you are not interacting with user interface objects, any code in the listener method
* <em>must</em> finish quickly, or it will add latency for other listeners, and updates will back up.
* If you want to perform lengthy processing of any sort, do so on another thread.</p>
*
* @param listener the cache update listener to add
*/
public static synchronized void addCacheUpdateListener(MetadataCacheUpdateListener listener) {
if (listener != null) {
cacheListeners.add(listener);
}
}
/**
* Removes the specified cache update listener so that it no longer receives updates when there
* are changes to the available set of metadata caches. If {@code listener} is {@code null} or not present
* in the set of registered listeners, no exception is thrown and no action is performed.
*
* @param listener the master listener to remove
*/
public static synchronized void removeCacheUpdateListener(MetadataCacheUpdateListener listener) {
if (listener != null) {
cacheListeners.remove(listener);
}
}
/**
* Get the set of currently-registered metadata cache update listeners.
*
* @return the listeners that are currently registered for metadata cache updates
*/
public static synchronized Set<MetadataCacheUpdateListener> getCacheUpdateListeners() {
return Collections.unmodifiableSet(new HashSet<MetadataCacheUpdateListener>(cacheListeners));
}
/**
* Send a metadata cache update announcement to all registered listeners.
*/
private static void deliverCacheUpdate() {
final Map<Integer, ZipFile> sdCaches = Collections.unmodifiableMap(sdMetadataCaches);
final Map<Integer, ZipFile> usbCaches = Collections.unmodifiableMap(usbMetadataCaches);
final Set<Integer> sdSet = Collections.unmodifiableSet(sdMounts);
final Set<Integer> usbSet = Collections.unmodifiableSet(usbMounts);
for (final MetadataCacheUpdateListener listener : getCacheUpdateListeners()) {
try {
listener.cacheStateChanged(sdCaches, usbCaches, sdSet, usbSet);
} catch (Exception e) {
logger.warn("Problem delivering metadata cache update to listener", e);
}
}
}
/**
* Keeps track of the registered track metadata update listeners.
*/
private static final Set<TrackMetadataUpdateListener> trackListeners = new HashSet<TrackMetadataUpdateListener>();
/**
* Adds the specified track metadata listener to receive updates when the track metadata for a player changes.
* If {@code listener} is {@code null} or already present in the set of registered listeners, no exception is
* thrown and no action is performed.
*
* <p>To reduce latency, updates are delivered to listeners directly on the thread that is receiving packets
* from the network, so if you want to interact with user interface objects in listener methods, you need to use
* <code><a href="http://docs.oracle.com/javase/8/docs/api/javax/swing/SwingUtilities.html#invokeLater-java.lang.Runnable-">javax.swing.SwingUtilities.invokeLater(Runnable)</a></code>
* to do so on the Event Dispatch Thread.
*
* Even if you are not interacting with user interface objects, any code in the listener method
* <em>must</em> finish quickly, or it will add latency for other listeners, and updates will back up.
* If you want to perform lengthy processing of any sort, do so on another thread.</p>
*
* @param listener the track metadata update listener to add
*/
public static synchronized void addTrackMetadataUpdateListener(TrackMetadataUpdateListener listener) {
if (listener != null) {
trackListeners.add(listener);
}
}
/**
* Get the set of currently-registered metadata cache update listeners.
*
* @return the listeners that are currently registered for metadata cache updates
*/
public static synchronized Set<TrackMetadataUpdateListener> getTrackMetadataUpdateListeners() {
return Collections.unmodifiableSet(new HashSet<TrackMetadataUpdateListener>(trackListeners));
}
/**
* Removes the specified track metadata update listener so that it no longer receives updates when track
* metadata for a player changes. If {@code listener} is {@code null} or not present
* in the set of registered listeners, no exception is thrown and no action is performed.
*
* @param listener the track metadata update listener to remove
*/
public static synchronized void removeTrackMetadataUpdateListener(TrackMetadataUpdateListener listener) {
if (listener != null) {
trackListeners.remove(listener);
}
}
/**
* Send a metadata cache update announcement to all registered listeners.
*/
private static void deliverTrackMetadataUpdate(int player, TrackMetadata metadata) {
for (final TrackMetadataUpdateListener listener : getTrackMetadataUpdateListeners()) {
try {
listener.metadataChanged(player, metadata);
} catch (Exception e) {
logger.warn("Problem delivering track metadata update to listener", e);
}
}
}
/**
* Process an update packet from one of the CDJs. See if it has a valid track loaded; if not, clear any
* metadata we had stored for that player. If so, see if it is the same track we already know about; if not,
* request the metadata associated with that track.
*
* Also clears out any metadata caches that were attached for slots that no longer have media mounted in them,
* and updates the sets of which players have media mounted in which slots.
*
* If any of these reflect a change in state, any registered listeners will be informed.
*
* @param update an update packet we received from a CDJ
*/
private static void handleUpdate(final CdjStatus update) {
// First see if any metadata caches need evicting or mount sets need updating.
if (update.isLocalUsbEmpty()) {
detachMetadataCache(update.deviceNumber, CdjStatus.TrackSourceSlot.USB_SLOT);
removeMount(update.deviceNumber, CdjStatus.TrackSourceSlot.USB_SLOT);
} else if (update.isLocalUsbLoaded()) {
recordMount(update.deviceNumber, CdjStatus.TrackSourceSlot.USB_SLOT);
}
if (update.isLocalSdEmpty()) {
detachMetadataCache(update.deviceNumber, CdjStatus.TrackSourceSlot.SD_SLOT);
removeMount(update.deviceNumber, CdjStatus.TrackSourceSlot.SD_SLOT);
} else if (update.isLocalSdLoaded()){
recordMount(update.deviceNumber, CdjStatus.TrackSourceSlot.SD_SLOT);
}
// Now see if a track has changed that needs new metadata.
if (update.getTrackType() != CdjStatus.TrackType.REKORDBOX ||
update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK ||
update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.UNKNOWN ||
update.getRekordboxId() == 0) { // We no longer have metadata for this device
clearMetadata(update);
} else { // We can gather metadata for this device; check if we already looked up this track
CdjStatus lastStatus = lastUpdates.get(update.address);
if (lastStatus == null || lastStatus.getTrackSourceSlot() != update.getTrackSourceSlot() ||
lastStatus.getTrackSourcePlayer() != update.getTrackSourcePlayer() ||
lastStatus.getRekordboxId() != update.getRekordboxId()) { // We have something new!
synchronized (activeRequests) {
// Make sure we are not already talking to the device before we try hitting it again.
if (!activeRequests.contains(update.getTrackSourcePlayer())) {
activeRequests.add(update.getTrackSourcePlayer());
new Thread(new Runnable() {
@Override
public void run() {
try {
TrackMetadata data = requestMetadataFrom(update);
if (data != null) {
updateMetadata(update, data);
}
} catch (Exception e) {
logger.warn("Problem requesting track metadata from update" + update, e);
} finally {
synchronized (activeRequests) {
activeRequests.remove(update.getTrackSourcePlayer());
}
}
}
}).start();
}
}
}
}
}
/**
* Start finding track metadata for all active players. Starts the {@link VirtualCdj} if it is not already
* running, because we need it to send us device status updates to notice when new tracks are loaded.
*
* @throws Exception if there is a problem starting the required components
*/
public static synchronized void start() throws Exception {
if (!running) {
DeviceFinder.start();
DeviceFinder.addDeviceAnnouncementListener(announcementListener);
for (DeviceAnnouncement device: DeviceFinder.currentDevices()) {
requestPlayerDBServerPort(device);
}
VirtualCdj.start();
VirtualCdj.addUpdateListener(updateListener);
queueHandler = new Thread(new Runnable() {
@Override
public void run() {
while (isRunning()) {
try {
handleUpdate(pendingUpdates.take());
} catch (InterruptedException e) {
// Interrupted due to MetadataFinder shutdown, presumably
}
}
}
});
running = true;
queueHandler.start();
}
}
/**
* Stop finding track metadata for all active players.
*/
public static synchronized void stop() {
if (running) {
VirtualCdj.removeUpdateListener(updateListener);
running = false;
pendingUpdates.clear();
queueHandler.interrupt();
queueHandler = null;
lastUpdates.clear();
metadata.clear();
}
}
}
| src/main/java/org/deepsymmetry/beatlink/MetadataFinder.java | package org.deepsymmetry.beatlink;
import org.deepsymmetry.beatlink.dbserver.BinaryField;
import org.deepsymmetry.beatlink.dbserver.Client;
import org.deepsymmetry.beatlink.dbserver.Message;
import org.deepsymmetry.beatlink.dbserver.NumberField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Watches for new tracks to be loaded on players, and queries the
* appropriate player for the metadata information when that happens.<p>
*
* @author James Elliott
*/
public class MetadataFinder {
private static final Logger logger = LoggerFactory.getLogger(MetadataFinder.class.getName());
/**
* The default value we will use for timeouts on opening and reading from sockets.
*/
public static final int DEFAULT_SOCKET_TIMEOUT = 10000;
/**
* The number of milliseconds after which an attempt to open or read from a socket will fail.
*/
private static int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
/**
* Set how long we will wait for a socket to connect or for a read operation to complete.
* Adjust this if your players or network require it.
*
* @param timeout after how many milliseconds will an attempt to open or read from a socket fail
*/
public static void setSocketTimeout(int timeout) {
socketTimeout = timeout;
}
/**
* Check how long we will wait for a socket to connect or for a read operation to complete.
* Adjust this if your players or network require it.
*
* @return the number of milliseconds after which an attempt to open or read from a socket will fail
*/
public static int getSocketTimeout() {
return socketTimeout;
}
/**
* Given a status update from a CDJ, find the metadata for the track that it has loaded, if any.
*
* @param status the CDJ status update that will be used to determine the loaded track and ask the appropriate
* player for metadata about it
* @return the metadata that was obtained, if any
*/
public static TrackMetadata requestMetadataFrom(CdjStatus status) {
if (status.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK || status.getRekordboxId() == 0) {
return null;
}
return requestMetadataFrom(status.getTrackSourcePlayer(), status.getTrackSourceSlot(), status.getRekordboxId());
}
/**
* Receive some bytes from the player we are requesting metadata from.
*
* @param is the input stream associated with the player metadata socket.
* @return the bytes read.
*
* @throws IOException if there is a problem reading the response
*/
private static byte[] receiveBytes(InputStream is) throws IOException {
byte[] buffer = new byte[8192];
int len = (is.read(buffer));
if (len < 1) {
throw new IOException("receiveBytes read " + len + " bytes.");
}
return Arrays.copyOf(buffer, len);
}
/**
* Receive an expected number of bytes from the player, logging a warning if we get a different number of them.
*
* @param is the input stream associated with the player metadata socket.
* @param size the number of bytes we expect to receive.
* @param description the type of response being processed, for use in the warning message.
* @return the bytes read.
*
* @throws IOException if there is a problem reading the response.
*/
private static byte[] readResponseWithExpectedSize(InputStream is, int size, String description) throws IOException {
byte[] result = receiveBytes(is);
if (result.length != size) {
logger.warn("Expected " + size + " bytes while reading " + description + " response, received " + result.length);
}
return result;
}
/**
* Finds a valid player number that is currently visible but which is different from the one specified, so it can
* be used as the source player for a query being sent to the specified one. If the virtual CDJ is running on an
* acceptable player number (which must be 1-4 to request metadata from an actual CDJ, but can be anything if we
* are talking to rekordbox), uses that, since it will always be safe. Otherwise, picks an existing player number,
* but this will cause the query to fail if that player has mounted media from the player we are querying.
*
* @param player the player to which a metadata query is being sent
* @param slot the media slot from which the track of interest was loaded
*
* @return some other currently active player number
*
* @throws IllegalStateException if there is no other player number available to use.
*/
private static int chooseAskingPlayerNumber(int player, CdjStatus.TrackSourceSlot slot) {
final int fakeDevice = VirtualCdj.getDeviceNumber();
if (slot == CdjStatus.TrackSourceSlot.COLLECTION || (fakeDevice >= 1 && fakeDevice <= 4)) {
return fakeDevice;
}
for (DeviceAnnouncement candidate : DeviceFinder.currentDevices()) {
final int realDevice = candidate.getNumber();
if (realDevice != player && realDevice >= 1 && realDevice <= 4) {
final DeviceUpdate lastUpdate = VirtualCdj.getLatestStatusFor(realDevice);
if (lastUpdate != null && lastUpdate instanceof CdjStatus &&
((CdjStatus)lastUpdate).getTrackSourcePlayer() != player) {
return candidate.getNumber();
}
}
}
throw new IllegalStateException("No player number available to query player " + player +
". If they are on the network, they must be using Link to play a track from that player, " +
"so we can't use their ID.");
}
/**
* Request metadata for a specific track ID, given a connection to a player that has already been set up.
* Separated into its own method so it could be used multiple times on the same connection when gathering
* all track metadata.
*
* @param rekordboxId the track of interest
* @param slot identifies the media slot we are querying
* @param client the dbserver client that is communicating with the appropriate player
*
* @return the retrieved metadata, or {@code null} if there is no such track
*
* @throws IOException if there is a communication problem
*/
private static TrackMetadata getTrackMetadata(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)
throws IOException {
// Send the metadata menu request
Message response = client.menuRequest(Message.KnownType.METADATA_REQ, Message.MenuIdentifier.MAIN_MENU, slot,
new NumberField(rekordboxId));
final long count = response.getMenuResultsCount();
if (count == Message.NO_MENU_RESULTS_AVAILABLE) {
return null;
}
// Gather all the metadata menu items
final List<Message> items = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, response);
TrackMetadata result = new TrackMetadata(rekordboxId, items);
if (result.getArtworkId() != 0) {
result = result.withArtwork(requestArtwork(result.getArtworkId(), slot, client));
}
return result;
}
/**
* Requests the beat grid for a specific track ID, given a connection to a player that has already been set up.
* @param rekordboxId the track of interest
* @param slot identifies the media slot we are querying
* @param client the dbserver client that is communicating with the appropriate player
*
* @return the retrieved beat grid, or {@code null} if there is no such track
*
* @throws IOException if there is a communication problem
*/
private static BeatGrid getBeatGrid(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)
throws IOException {
Message response = client.simpleRequest(Message.KnownType.BEAT_GRID_REQ, null,
client.buildRMS1(Message.MenuIdentifier.DATA, slot), new NumberField(rekordboxId));
if (response.knownType == Message.KnownType.BEAT_GRID) {
return new BeatGrid(response);
}
logger.error("Unexpected response type when requesting beat grid: {}", response);
return null;
}
/**
* Request the list of all tracks in the specified slot, given a connection to a player that has already been
* set up.
*
* @param slot identifies the media slot we are querying
* @param client the dbserver client that is communicating with the appropriate player
*
* @return the retrieved track list entry items
*
* @throws IOException if there is a communication problem
*/
private static List<Message> getFullTrackList(CdjStatus.TrackSourceSlot slot, Client client)
throws IOException {
// Send the metadata menu request
Message response = client.menuRequest(Message.KnownType.TRACK_LIST_REQ, Message.MenuIdentifier.MAIN_MENU, slot,
new NumberField(0));
final long count = response.getMenuResultsCount();
if (count == Message.NO_MENU_RESULTS_AVAILABLE) {
return Collections.emptyList();
}
// Gather all the metadata menu items
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, response);
}
/**
* Look up track metadata from a cache.
*
* @param cache the appropriate metadata cache file
* @param rekordboxId the track whose metadata is desired
*
* @return the cached metadata, including album art (if available), or {@code null}
*/
private static TrackMetadata getCachedMetadata(ZipFile cache, int rekordboxId) {
ZipEntry entry = cache.getEntry(getMetadataEntryName(rekordboxId));
if (entry != null) {
DataInputStream is = null;
try {
is = new DataInputStream(cache.getInputStream(entry));
List<Message> items = new LinkedList<Message>();
Message current = Message.read(is);
while (current.messageType.getValue() == Message.KnownType.MENU_ITEM.protocolValue) {
items.add(current);
current = Message.read(is);
}
TrackMetadata result = new TrackMetadata(rekordboxId, items);
try {
is.close();
} catch (Exception e) {
is = null;
logger.error("Problem closing Zip File input stream after reading metadata entry", e);
}
if (result.getArtworkId() != 0) {
entry = cache.getEntry(getArtworkEntryName(result));
if (entry != null) {
is = new DataInputStream(cache.getInputStream(entry));
try {
byte[] imageBytes = new byte[(int)entry.getSize()];
is.readFully(imageBytes);
result = result.withArtwork(ByteBuffer.wrap(imageBytes).asReadOnlyBuffer());
} catch (Exception e) {
logger.error("Problem reading artwork from metadata cache, leaving as null", e);
}
}
}
return result;
} catch (IOException e) {
if (is != null) {
try {
is.close();
} catch (Exception e2) {
logger.error("Problem closing ZipFile input stream after exception", e2);
}
}
logger.error("Problem reading metadata from cache file, returning null", e);
}
}
return null;
}
/**
* Look up a beat grid in a metadata cache.
*
* @param cache the appropriate metadata cache file
* @param rekordboxId the track whose beat grid is desired
*
* @return the cached beat grid (if available), or {@code null}
*/
private static BeatGrid getCachedBeatGrid(ZipFile cache, int rekordboxId) {
ZipEntry entry = cache.getEntry(getBeatGridEntryName(rekordboxId));
if (entry != null) {
DataInputStream is = null;
try {
is = new DataInputStream(cache.getInputStream(entry));
byte[] gridBytes = new byte[(int)entry.getSize()];
is.readFully(gridBytes);
try {
is.close();
} catch (Exception e) {
is = null;
logger.error("Problem closing Zip File input stream after reading beat grid entry", e);
}
return new BeatGrid(ByteBuffer.wrap(gridBytes).asReadOnlyBuffer());
} catch (IOException e) {
if (is != null) {
try {
is.close();
} catch (Exception e2) {
logger.error("Problem closing ZipFile input stream after exception", e2);
}
}
logger.error("Problem reading beat grid from cache file, returning null", e);
}
}
return null;
}
/**
* Ask the specified player for metadata about the track in the specified slot with the specified rekordbox ID.
*
* @param player the player number whose track is of interest
* @param slot the slot in which the track can be found
* @param rekordboxId the track of interest
*
* @return the metadata, if any
*
* @throws IllegalStateException if a metadata cache is being created amd we need to talk to the CDJs
*/
public static synchronized TrackMetadata requestMetadataFrom(int player, CdjStatus.TrackSourceSlot slot,
int rekordboxId) {
// First check if we are using cached data for this request
ZipFile cache = getMetadataCache(player, slot);
if (cache != null) {
return getCachedMetadata(cache, rekordboxId);
}
// TODO: Once we understand and track cue points, keep an in-memory cache of any loaded hot-cue tracks.
if (passive) {
return null; // We are not allowed to actively query for metadata
}
// We need to perform an actual query, so at this point we need to bail if a cache is being created
failIfCreatingCache();
final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getLatestAnnouncementFrom(player);
final int dbServerPort = getPlayerDBServerPort(player);
if (deviceAnnouncement == null || dbServerPort < 0) {
return null; // If the device isn't known, or did not provide a database server, we can't get metadata.
}
final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(player, slot);
Socket socket = null;
try {
InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort);
socket = new Socket();
socket.connect(address, socketTimeout);
socket.setSoTimeout(socketTimeout);
Client client = new Client(socket, player, posingAsPlayerNumber);
return getTrackMetadata(rekordboxId, slot, client);
} catch (Exception e) {
logger.warn("Problem requesting metadata", e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
logger.warn("Problem closing metadata request socket", e);
}
}
}
return null;
}
// TODO: Add method that enumerates a playlist or folder, then one that caches metadata from a playlist.
/**
* Ask the specified player for the beat grid pf the track in the specified slot with the specified rekordbox ID.
*
* @param player the player number whose track is of interest
* @param slot the slot in which the track can be found
* @param rekordboxId the track of interest
*
* @return the beat grid, if any
*
* @throws IllegalStateException if a metadata cache is being created and we need to talk to the CDJs
*/
public static synchronized BeatGrid requestBeatGridFrom(int player, CdjStatus.TrackSourceSlot slot, int rekordboxId) {
// First check if we are using cached data for this request
ZipFile cache = getMetadataCache(player, slot);
if (cache != null) {
return getCachedBeatGrid(cache, rekordboxId);
}
if (passive) {
return null; // We are not allowed to actively query for metadata
}
// We need to perform an actual query, so at this point we need to bail if a cache is being created
failIfCreatingCache();
final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getLatestAnnouncementFrom(player);
final int dbServerPort = getPlayerDBServerPort(player);
if (deviceAnnouncement == null || dbServerPort < 0) {
return null; // If the device isn't known, or did not provide a database server, we can't get metadata.
}
final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(player, slot);
Socket socket = null;
try {
InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort);
socket = new Socket();
socket.connect(address, socketTimeout);
Client client = new Client(socket, player, posingAsPlayerNumber);
return getBeatGrid(rekordboxId, slot, client);
} catch (Exception e) {
logger.warn("Problem requesting beat grid", e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
logger.warn("Problem closing metadata request socket", e);
}
}
}
return null;
}
/**
* Creates a metadata cache archive file of all tracks in the specified slot on the specified player. Any
* previous contents of the specified file will be replaced.
*
* @param player the player number whose media library is to have its metdata cached
* @param slot the slot in which the media to be cached can be found
* @param cache the file into which the metadata cache should be written
*
* @throws IOException if there is a problem communicating with the player or writing the cache file.
*/
public static void createMetadataCache(int player, CdjStatus.TrackSourceSlot slot, File cache)
throws IOException {
createMetadataCache(player, slot, cache, null);
}
/**
* The root under which all zip file entries will be created in our cache metadata files.
*/
private static final String CACHE_PREFIX = "BLTMetaCache/";
/**
* The file entry whose content will be the cache format identifier.
*/
private static final String CACHE_FORMAT_ENTRY = CACHE_PREFIX + "version";
/**
* The prefix for cache file entries that will store track metadata.
*/
private static final String CACHE_METADATA_ENTRY_PREFIX = CACHE_PREFIX + "metadata/";
/**
* The prefix for cache file entries that will store album art.
*/
private static final String CACHE_ART_ENTRY_PREFIX = CACHE_PREFIX + "artwork/";
/**
* The prefix for cache file entries that will store beat grids.
*/
private static final String CACHE_BEAT_GRID_ENTRY_PREFIX = CACHE_PREFIX + "beatgrid/";
/**
* The comment string used to identify a ZIP file as one of our metadata caches.
*/
public static final String CACHE_FORMAT_IDENTIFIER = "BeatLink Metadata Cache version 1";
/**
* Used to mark the end of the metadata items in each cache entry, just like when reading from the server.
*/
private static final Message MENU_FOOTER_MESSAGE = new Message(0, Message.KnownType.MENU_FOOTER);
/**
* Finish the process of copying a list of tracks to a metadata cache, once they have been listed. This code
* is shared between the implementations that work with the full track list and with playlists.
*
* @param trackListEntries the list of menu items identifying which tracks need to be copied to the metadata
* cache
* @param client the connection to the dbserver on the player whose metadata is being cached
* @param slot the slot in which the media to be cached can be found
* @param cache the file into which the metadata cache should be written
* @param listener will be informed after each track is added to the cache file being created and offered
* the opportunity to cancel the process
*
* @throws IOException if there is a problem communicating with the player or writing the cache file.
*/
private static void copyTracksToCache(List<Message> trackListEntries, Client client, CdjStatus.TrackSourceSlot slot,
File cache, MetadataCreationUpdateListener listener)
throws IOException {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
ZipOutputStream zos = null;
WritableByteChannel channel = null;
final Set<Integer> artworkAdded = new HashSet<Integer>();
try {
fos = new FileOutputStream(cache);
bos = new BufferedOutputStream(fos);
zos = new ZipOutputStream(bos);
zos.setMethod(ZipOutputStream.DEFLATED);
// Add a marker so we can recognize this as a metadata archive. I would use the ZipFile comment, but
// that is not available until Java 7, and Beat Link is supposed to be backwards compatible with Java 6.
ZipEntry zipEntry = new ZipEntry(CACHE_FORMAT_ENTRY);
zos.putNextEntry(zipEntry);
zos.write(CACHE_FORMAT_IDENTIFIER.getBytes("UTF-8"));
// Write the actual metadata entries
channel = Channels.newChannel(zos);
final int totalToCopy = trackListEntries.size();
int tracksCopied = 0;
for (Message entry : trackListEntries) {
if (entry.getMenuItemType() != Message.MenuItemType.TRACK_LIST_ENTRY) {
throw new IOException("Received unexpected item type. Needed TRACK_LIST_ENTRY, got: " + entry);
}
int rekordBoxId = (int)((NumberField)entry.arguments.get(1)).getValue();
TrackMetadata track = getTrackMetadata(rekordBoxId, slot, client);
logger.debug("Adding metadata with ID {}", rekordBoxId);
zipEntry = new ZipEntry(getMetadataEntryName(rekordBoxId));
zos.putNextEntry(zipEntry);
for (Message metadataItem : track.rawItems) {
client.writeMessage(metadataItem, channel);
}
client.writeMessage(MENU_FOOTER_MESSAGE, channel); // So we know to stop reading
// Now the album art, if any
if (track.getRawArtwork() != null && !artworkAdded.contains(track.getArtworkId())) {
logger.debug("Adding artwork with ID {}", track.getArtworkId());
zipEntry = new ZipEntry(getArtworkEntryName(track));
zos.putNextEntry(zipEntry);
Util.writeFully(track.getRawArtwork(), channel);
}
BeatGrid beatGrid = getBeatGrid(rekordBoxId, slot, client);
if (beatGrid != null) {
logger.debug("Adding beat grid with ID {}", rekordBoxId);
zipEntry = new ZipEntry(getBeatGridEntryName(rekordBoxId));
zos.putNextEntry(zipEntry);
Util.writeFully(beatGrid.getRawData(), channel);
}
// TODO: Include waveforms (once supported), etc.
if (listener != null) {
if (!listener.cacheUpdateContinuing(track, ++tracksCopied, totalToCopy)) {
logger.info("Track metadata cache creation canceled by listener");
cache.delete();
return;
}
}
}
} finally {
try {
if (channel != null) {
channel.close();
}
} catch (Exception e) {
logger.error("Problem closing byte channel for writing to metadata cache", e);
}
try {
if (zos != null) {
zos.close();
}
} catch (Exception e) {
logger.error("Problem closing Zip Output Stream of metadata cache", e);
}
try {
if (bos != null) {
bos.close();
}
} catch (Exception e) {
logger.error("Problem closing Buffered Output Stream of metadata cahce", e);
}
try {
if (fos != null) {
fos.close();
}
} catch (Exception e) {
logger.error("Problem closing File Output Stream of metadata cache", e);
}
}
}
/**
* Names the appropriate zip file entry for caching a track's metadata.
*
* @param rekordBoxId the id of the track being cached or looked up
*
* @return the name of the entry where that track's metadata should be stored
*/
private static String getMetadataEntryName(int rekordBoxId) {
return CACHE_METADATA_ENTRY_PREFIX + rekordBoxId;
}
/**
* Names the appropriate zip file entry for caching a track's album art.
*
* @param track the track being cached or looked up
*
* @return the name of entry where that track's artwork should be stored
*/
private static String getArtworkEntryName(TrackMetadata track) {
return CACHE_ART_ENTRY_PREFIX + track.getArtworkId() + ".jpg";
}
/**
* Names the appropriate zip file entry for caching a track's beat grid.
*
* @param rekordBoxId the id of the track being cached or looked up
*
* @return the name of the entry where that track's beat grid should be stored
*/
private static String getBeatGridEntryName(int rekordBoxId) {
return CACHE_BEAT_GRID_ENTRY_PREFIX + rekordBoxId;
}
/**
* Is set to {@code true} when a lengthy cache creation process is underway, to prevent other requests that might
* interfere with it.
*/
private static boolean creatingCache = false;
/**
* Record whether cache creation is taking place, so we can block other inquiries during that process.
*
* @param inProgress {@code true} if we are building a metadata cache file
*
* @throws IllegalStateException if a cache is already being created
*/
private static synchronized void setCreatingCache(boolean inProgress) {
if (creatingCache && inProgress) {
throw new IllegalStateException("Already creating a metadata cache");
}
creatingCache = inProgress;
}
/**
* Check whether cache creation is taking place, so we can block other inquiries during that process.
*
* @throws IllegalStateException if a cache is being created
*/
private static synchronized void failIfCreatingCache() {
if (creatingCache) {
throw new IllegalStateException("Cannot perform the requested operation while a metadata cache is being created");
}
}
/**
* Creates a metadata cache archive file of all tracks in the specified slot on the specified player. Any
* previous contents of the specified file will be replaced. If a non-{@code null} {@code listener} is
* supplied, its {@link MetadataCreationUpdateListener#cacheUpdateContinuing(TrackMetadata, int, int)} method
* will be called after each track is added to the cache, allowing it to display progress updates to the user,
* and to continue or cancel the process by returning {@code true} or {@code false}.
*
* Because this takes a huge amount of time relative to CDJ status updates, it can only be performed while
* the MetadataFinder is in passive mode.
*
* @param player the player number whose media library is to have its metdata cached
* @param slot the slot in which the media to be cached can be found
* @param cache the file into which the metadata cache should be written
* @param listener will be informed after each track is added to the cache file being created and offered
* the opportunity to cancel the process
*
* @throws IOException if there is a problem communicating with the player or writing the cache file
* @throws IllegalStateException if the MetadataFinder is not running or not in passive mode when this is called,
* or if another cache is already in the process of being created
*/
public static void createMetadataCache(int player, CdjStatus.TrackSourceSlot slot, File cache,
MetadataCreationUpdateListener listener)
throws IOException {
if (!running) {
throw new IllegalStateException("must be running to create a metadata cache");
}
if (!passive) {
throw new IllegalStateException("must be in passive mode to create a metadata cache");
}
final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getLatestAnnouncementFrom(player);
final int dbServerPort = getPlayerDBServerPort(player);
if (deviceAnnouncement == null || dbServerPort < 0) {
throw new IOException("Unable to find dbserver on player " + player);
}
final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(player, slot);
Socket socket = null;
Client client = null;
try {
setCreatingCache(true);
cache.delete();
InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort);
socket = new Socket();
socket.connect(address, socketTimeout);
client = new Client(socket, player, posingAsPlayerNumber);
copyTracksToCache(getFullTrackList(slot, client), client, slot, cache, listener);
} finally {
try {
if (client != null) {
client.close();
}
} catch (Exception e) {
logger.error("Problem closing dbserver client when building metadata cache", e);
}
try {
if (socket != null) {
socket.close();
}
} catch (Exception e) {
logger.error("Problem closing socket when building metadata cache", e);
}
setCreatingCache(false);
}
}
/**
* Request the artwork associated with a track whose metadata is being retrieved.
*
* @param artworkId identifies the album art to retrieve
* @param slot the slot identifier from which the track was loaded
* @param client the dbserver client that is communicating with the appropriate player
*
* @return the track's artwork, or null if none is available
*
* @throws IOException if there is a problem communicating with the player
*/
private static ByteBuffer requestArtwork(int artworkId, CdjStatus.TrackSourceSlot slot, Client client)
throws IOException {
// Send the artwork request
Message response = client.simpleRequest(Message.KnownType.ALBUM_ART_REQ, Message.KnownType.ALBUM_ART,
client.buildRMS1(Message.MenuIdentifier.DATA, slot), new NumberField((long)artworkId));
// Create an image from the response bytes
return ((BinaryField)response.arguments.get(3)).getValue();
}
/**
* Keeps track of the current metadata known for each player.
*/
private static final Map<Integer, TrackMetadata> metadata = new HashMap<Integer, TrackMetadata>();
/**
* Keeps track of the previous update from each player that we retrieved metadata about, to check whether a new
* track has been loaded.
*/
private static final Map<InetAddress, CdjStatus> lastUpdates = new HashMap<InetAddress, CdjStatus>();
/**
* A queue used to hold CDJ status updates we receive from the {@link VirtualCdj} so we can process them on a
* lower priority thread, and not hold up delivery to more time-sensitive listeners.
*/
private static LinkedBlockingDeque<CdjStatus> pendingUpdates = new LinkedBlockingDeque<CdjStatus>(100);
/**
* Our update listener just puts appropriate device updates on our queue, so we can process them on a lower
* priority thread, and not hold up delivery to more time-sensitive listeners.
*/
private static final DeviceUpdateListener updateListener = new DeviceUpdateListener() {
@Override
public void received(DeviceUpdate update) {
logger.debug("Received device update {}", update);
if (update instanceof CdjStatus) {
if (!pendingUpdates.offerLast((CdjStatus)update)) {
logger.warn("Discarding CDJ update because our queue is backed up.");
}
}
}
};
/**
* Keeps track of the database server ports of all the players we have seen on the network.
*/
private static final Map<Integer, Integer> dbServerPorts = new HashMap<Integer, Integer>();
/**
* Look up the database server port reported by a given player.
*
* @param player the player number of interest.
*
* @return the port number on which its database server is running, or -1 if unknown.
*/
public static synchronized int getPlayerDBServerPort(int player) {
Integer result = dbServerPorts.get(player);
if (result == null) {
return -1;
}
return result;
}
/**
* Record the database server port reported by a player.
*
* @param player the player number whose server port has been determined.
* @param port the port number on which the player's database server is running.
*/
private static synchronized void setPlayerDBServerPort(int player, int port) {
dbServerPorts.put(player, port);
}
/**
* The port on which we can request information about a player, including the port on which its database server
* is running.
*/
private static final int DB_SERVER_QUERY_PORT = 12523;
private static final byte[] DB_SERVER_QUERY_PACKET = {
0x00, 0x00, 0x00, 0x0f,
0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x44, 0x42, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, // RemoteDBServer
0x00
};
/**
* Query a player to determine the port on which its database server is running.
*
* @param announcement the device announcement with which we detected a new player on the network.
*/
private static void requestPlayerDBServerPort(DeviceAnnouncement announcement) {
Socket socket = null;
try {
socket = new Socket(announcement.getAddress(), DB_SERVER_QUERY_PORT);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
socket.setSoTimeout(3000);
os.write(DB_SERVER_QUERY_PACKET);
byte[] response = readResponseWithExpectedSize(is, 2, "database server port query packet");
if (response.length == 2) {
setPlayerDBServerPort(announcement.getNumber(), (int)Util.bytesToNumber(response, 0, 2));
}
} catch (java.net.ConnectException ce) {
logger.info("Player " + announcement.getNumber() +
" doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata.");
} catch (Exception e) {
logger.warn("Problem requesting database server port number", e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
logger.warn("Problem closing database server port request socket", e);
}
}
}
}
/**
* Our announcement listener watches for devices to appear on the network so we can ask them for their database
* server port, and when they disappear discards all information about them.
*/
private static final DeviceAnnouncementListener announcementListener = new DeviceAnnouncementListener() {
@Override
public void deviceFound(final DeviceAnnouncement announcement) {
new Thread(new Runnable() {
@Override
public void run() {
requestPlayerDBServerPort(announcement);
}
}).start();
}
@Override
public void deviceLost(DeviceAnnouncement announcement) {
setPlayerDBServerPort(announcement.getNumber(), -1);
clearMetadata(announcement);
detachMetadataCache(announcement.getNumber(), CdjStatus.TrackSourceSlot.SD_SLOT);
detachMetadataCache(announcement.getNumber(), CdjStatus.TrackSourceSlot.USB_SLOT);
}
};
/**
* Keep track of whether we are running
*/
private static boolean running = false;
/**
* Check whether we are currently running.
*
* @return true if track metadata is being sought for all active players
*/
public static synchronized boolean isRunning() {
return running;
}
/**
* Indicates whether we should use metdata only from caches, never actively requesting it from a player.
*/
private static boolean passive = false;
/**
* Check whether we are configured to use metadata only from caches, never actively requesting it from a player.
*
* @return {@code true} if only cached metadata will be used, or {@code false} if metadata will be requested from
* a player if a track is loaded from a media slot to which no cache has been assigned
*/
public static synchronized boolean isPassive() {
return passive;
}
/**
* Set whether we are configured to use metadata only from caches, never actively requesting it from a player.
*
* @param passive {@code true} if only cached metadata will be used, or {@code false} if metadata will be requested
* from a player if a track is loaded from a media slot to which no cache has been assigned
*
* @throws IllegalStateException if you try to turn off passive mode while a metadata cache is being created
*/
public static synchronized void setPassive(boolean passive) {
if (!passive) {
failIfCreatingCache();
}
MetadataFinder.passive = passive;
}
/**
* We process our updates on a separate thread so as not to slow down the high-priority update delivery thread;
* we perform potentially slow I/O.
*/
private static Thread queueHandler;
/**
* We have received an update that invalidates any previous metadata for that player, so clear it out, and alert
* any listeners.
*
* @param update the update which means we can have no metadata for the associated player
*/
private static synchronized void clearMetadata(CdjStatus update) {
metadata.remove(update.deviceNumber);
lastUpdates.remove(update.address);
deliverTrackMetadataUpdate(update.deviceNumber, null);
}
/**
* We have received notification that a device is no longer on the network, so clear out its metadata.
*
* @param announcement the packet which reported the device’s disappearance
*/
private static synchronized void clearMetadata(DeviceAnnouncement announcement) {
metadata.remove(announcement.getNumber());
lastUpdates.remove(announcement.getAddress());
}
/**
* We have obtained metadata for a device, so store it and alert any listeners.
*
* @param update the update which caused us to retrieve this metadata
* @param data the metadata which we received
*/
private static synchronized void updateMetadata(CdjStatus update, TrackMetadata data) {
metadata.put(update.deviceNumber, data);
lastUpdates.put(update.address, update);
deliverTrackMetadataUpdate(update.deviceNumber, data);
}
/**
* Get all currently known metadata.
*
* @return the track information reported by all current players
*/
public static synchronized Map<Integer, TrackMetadata> getLatestMetadata() {
return Collections.unmodifiableMap(new TreeMap<Integer, TrackMetadata>(metadata));
}
/**
* Look up the track metadata we have for a given player number.
*
* @param player the device number whose track metadata is desired
* @return information about the track loaded on that player, if available
*/
public static synchronized TrackMetadata getLatestMetadataFor(int player) {
return metadata.get(player);
}
/**
* Look up the track metadata we have for a given player, identified by a status update received from that player.
*
* @param update a status update from the player for which track metadata is desired
* @return information about the track loaded on that player, if available
*/
public static TrackMetadata getLatestMetadataFor(DeviceUpdate update) {
return getLatestMetadataFor(update.deviceNumber);
}
/**
* Keep track of the devices we are currently trying to get metadata from in response to status updates.
*/
private final static Set<Integer> activeRequests = new HashSet<Integer>();
/**
* Keeps track of any metadata caches that have been attached for the SD slots of players on the network,
* keyed by player number.
*/
private final static Map<Integer, ZipFile> sdMetadataCaches = new ConcurrentHashMap<Integer, ZipFile>();
/**
* Keeps track of any metadata caches that have been attached for the USB slots of players on the network,
* keyed by player number.
*/
private final static Map<Integer, ZipFile> usbMetadataCaches = new ConcurrentHashMap<Integer, ZipFile>();
/**
* Attach a metadata cache file to a particular player media slot, so the cache will be used instead of querying
* the player for metadata. This supports operation with metadata during shows where DJs are using all four player
* numbers and heavily cross-linking between them.
*
* If the media is ejected from that player slot, the cache will be detached.
*
* @param player the player number for which a metadata cache is to be attached
* @param slot the media slot to which a meta data cache is to be attached
* @param cache the metadata cache to be attached
*
* @throws IOException if there is a problem reading the cache file
* @throws IllegalArgumentException if an invalid player number or slot is supplied
* @throws IllegalStateException if the metadatafinder is not running
*/
public static void attachMetadataCache(int player, CdjStatus.TrackSourceSlot slot, File cache)
throws IOException {
if (!isRunning()) {
throw new IllegalStateException("attachMetadataCache() can't be used if MetadataFinder is not running");
}
if (player < 1 || player > 4 || DeviceFinder.getLatestAnnouncementFrom(player) == null) {
throw new IllegalArgumentException("unable to attach metadata cache for player " + player);
}
ZipFile oldCache = null;
// Open and validate the cache
ZipFile newCache = new ZipFile(cache, ZipFile.OPEN_READ);
ZipEntry zipEntry = newCache.getEntry(CACHE_FORMAT_ENTRY);
InputStream is = newCache.getInputStream(zipEntry);
Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
String tag = null;
if (s.hasNext()) tag = s.next();
if (!CACHE_FORMAT_IDENTIFIER.equals(tag)) {
try {
newCache.close();
} catch (Exception e) {
logger.error("Problem re-closing newly opened candidate metadata cache", e);
}
throw new IOException("File does not contain a Beat Link metadata cache: " + cache +
" (looking for format identifier \"" + CACHE_FORMAT_IDENTIFIER + "\", found: " + tag);
}
switch (slot) {
case USB_SLOT:
oldCache = usbMetadataCaches.put(player, newCache);
break;
case SD_SLOT:
oldCache = sdMetadataCaches.put(player, newCache);
break;
default:
try {
newCache.close();
} catch (Exception e) {
logger.error("Problem re-closing newly opened candidate metadata cache", e);
}
throw new IllegalArgumentException("Cannot cache media for slot " + slot);
}
if (oldCache != null) {
try {
oldCache.close();
} catch (IOException e) {
logger.error("Problem closing previous metadata cache", e);
}
}
deliverCacheUpdate();
}
/**
* Removes any metadata cache file that might have been assigned to a particular player media slot, so metadata
* will be looked up from the player itself.
*
* @param player the player number for which a metadata cache is to be attached
* @param slot the media slot to which a meta data cache is to be attached
*/
public static void detachMetadataCache(int player, CdjStatus.TrackSourceSlot slot) {
ZipFile oldCache = null;
switch (slot) {
case USB_SLOT:
oldCache = usbMetadataCaches.remove(player);
break;
case SD_SLOT:
oldCache = sdMetadataCaches.remove(player);
break;
default:
logger.warn("Ignoring request to remove metadata cache for slot {}", slot);
}
if (oldCache != null) {
try {
oldCache.close();
} catch (IOException e) {
logger.error("Problem closing metadata cache", e);
}
deliverCacheUpdate();
}
}
/**
* Finds the metadata cache file assigned to a particular player media slot, if any.
*
* @param player the player number for which a metadata cache is to be attached
* @param slot the media slot to which a meta data cache is to be attached
*
* @return the zip file being used as a metadata cache for that player and slot, or {@code null} if no cache
* has been attached
*/
public static ZipFile getMetadataCache(int player, CdjStatus.TrackSourceSlot slot) {
switch (slot) {
case USB_SLOT:
return usbMetadataCaches.get(player);
case SD_SLOT:
return sdMetadataCaches.get(player);
default:
return null;
}
}
/**
* Keeps track of any players with mounted SD media.
*/
private static Set<Integer> sdMounts = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());
/**
* Keeps track of any players with mounted USB media.
*/
private static Set<Integer> usbMounts = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());
/**
* Records that there is media mounted in a particular media player slot, updating listeners if this is a change.
*
* @param player the number of the player that has media in the specified slot
* @param slot the slot in which media is mounted
*/
private static void recordMount(int player, CdjStatus.TrackSourceSlot slot) {
switch (slot) {
case USB_SLOT:
if (usbMounts.add(player)) {
deliverCacheUpdate();
}
break;
case SD_SLOT:
if (sdMounts.add(player)) {
deliverCacheUpdate();
}
break;
default:
throw new IllegalArgumentException("Cannot record mounted media in slot " + slot);
}
}
/**
* Records that there is no media mounted in a particular media player slot, updating listeners if this is a change.
*
* @param player the number of the player that has no media in the specified slot
* @param slot the slot in which no media is mounted
*/
private static void removeMount(int player, CdjStatus.TrackSourceSlot slot) {
switch (slot) {
case USB_SLOT:
if (usbMounts.remove(player)) {
deliverCacheUpdate();
}
break;
case SD_SLOT:
if (sdMounts.remove(player)) {
deliverCacheUpdate();
}
break;
default:
logger.warn("Ignoring request to record unmounted media in slot {}", slot);
}
}
/**
* Returns the set of player numbers that currently have media mounted in the specified slot.
*
* @param slot the slot of interest, currently must be either {@code SD_SLOT} or {@code USB_SLOT}
*
* @return the player numbers with media currently mounted in the specified slot
*/
public static Set<Integer> getPlayersWithMediaIn(CdjStatus.TrackSourceSlot slot) {
switch (slot) {
case USB_SLOT:
return Collections.unmodifiableSet(usbMounts);
case SD_SLOT:
return Collections.unmodifiableSet(sdMounts);
default:
throw new IllegalArgumentException("Cannot report mounted media in slot " + slot);
}
}
/**
* Keeps track of the registered cache update listeners.
*/
private static final Set<MetadataCacheUpdateListener> cacheListeners = new HashSet<MetadataCacheUpdateListener>();
/**
* Adds the specified cache update listener to receive updates when a metadata cache is attached or detached.
* If {@code listener} is {@code null} or already present in the set of registered listeners, no exception is
* thrown and no action is performed.
*
* <p>To reduce latency, updates are delivered to listeners directly on the thread that is receiving packets
* from the network, so if you want to interact with user interface objects in listener methods, you need to use
* <code><a href="http://docs.oracle.com/javase/8/docs/api/javax/swing/SwingUtilities.html#invokeLater-java.lang.Runnable-">javax.swing.SwingUtilities.invokeLater(Runnable)</a></code>
* to do so on the Event Dispatch Thread.
*
* Even if you are not interacting with user interface objects, any code in the listener method
* <em>must</em> finish quickly, or it will add latency for other listeners, and updates will back up.
* If you want to perform lengthy processing of any sort, do so on another thread.</p>
*
* @param listener the cache update listener to add
*/
public static synchronized void addCacheUpdateListener(MetadataCacheUpdateListener listener) {
if (listener != null) {
cacheListeners.add(listener);
}
}
/**
* Removes the specified cache update listener so that it no longer receives updates when there
* are changes to the available set of metadata caches. If {@code listener} is {@code null} or not present
* in the set of registered listeners, no exception is thrown and no action is performed.
*
* @param listener the master listener to remove
*/
public static synchronized void removeCacheUpdateListener(MetadataCacheUpdateListener listener) {
if (listener != null) {
cacheListeners.remove(listener);
}
}
/**
* Get the set of currently-registered metadata cache update listeners.
*
* @return the listeners that are currently registered for metadata cache updates
*/
public static synchronized Set<MetadataCacheUpdateListener> getCacheUpdateListeners() {
return Collections.unmodifiableSet(new HashSet<MetadataCacheUpdateListener>(cacheListeners));
}
/**
* Send a metadata cache update announcement to all registered listeners.
*/
private static void deliverCacheUpdate() {
final Map<Integer, ZipFile> sdCaches = Collections.unmodifiableMap(sdMetadataCaches);
final Map<Integer, ZipFile> usbCaches = Collections.unmodifiableMap(usbMetadataCaches);
final Set<Integer> sdSet = Collections.unmodifiableSet(sdMounts);
final Set<Integer> usbSet = Collections.unmodifiableSet(usbMounts);
for (final MetadataCacheUpdateListener listener : getCacheUpdateListeners()) {
try {
listener.cacheStateChanged(sdCaches, usbCaches, sdSet, usbSet);
} catch (Exception e) {
logger.warn("Problem delivering metadata cache update to listener", e);
}
}
}
/**
* Keeps track of the registered track metadata update listeners.
*/
private static final Set<TrackMetadataUpdateListener> trackListeners = new HashSet<TrackMetadataUpdateListener>();
/**
* Adds the specified track metadata listener to receive updates when the track metadata for a player changes.
* If {@code listener} is {@code null} or already present in the set of registered listeners, no exception is
* thrown and no action is performed.
*
* <p>To reduce latency, updates are delivered to listeners directly on the thread that is receiving packets
* from the network, so if you want to interact with user interface objects in listener methods, you need to use
* <code><a href="http://docs.oracle.com/javase/8/docs/api/javax/swing/SwingUtilities.html#invokeLater-java.lang.Runnable-">javax.swing.SwingUtilities.invokeLater(Runnable)</a></code>
* to do so on the Event Dispatch Thread.
*
* Even if you are not interacting with user interface objects, any code in the listener method
* <em>must</em> finish quickly, or it will add latency for other listeners, and updates will back up.
* If you want to perform lengthy processing of any sort, do so on another thread.</p>
*
* @param listener the track metadata update listener to add
*/
public static synchronized void addTrackMetadataUpdateListener(TrackMetadataUpdateListener listener) {
if (listener != null) {
trackListeners.add(listener);
}
}
/**
* Get the set of currently-registered metadata cache update listeners.
*
* @return the listeners that are currently registered for metadata cache updates
*/
public static synchronized Set<TrackMetadataUpdateListener> getTrackMetadataUpdateListeners() {
return Collections.unmodifiableSet(new HashSet<TrackMetadataUpdateListener>(trackListeners));
}
/**
* Removes the specified track metadata update listener so that it no longer receives updates when track
* metadata for a player changes. If {@code listener} is {@code null} or not present
* in the set of registered listeners, no exception is thrown and no action is performed.
*
* @param listener the track metadata update listener to remove
*/
public static synchronized void removeTrackMetadataUpdateListener(TrackMetadataUpdateListener listener) {
if (listener != null) {
trackListeners.remove(listener);
}
}
/**
* Send a metadata cache update announcement to all registered listeners.
*/
private static void deliverTrackMetadataUpdate(int player, TrackMetadata metadata) {
for (final TrackMetadataUpdateListener listener : getTrackMetadataUpdateListeners()) {
try {
listener.metadataChanged(player, metadata);
} catch (Exception e) {
logger.warn("Problem delivering track metadata update to listener", e);
}
}
}
/**
* Process an update packet from one of the CDJs. See if it has a valid track loaded; if not, clear any
* metadata we had stored for that player. If so, see if it is the same track we already know about; if not,
* request the metadata associated with that track.
*
* Also clears out any metadata caches that were attached for slots that no longer have media mounted in them,
* and updates the sets of which players have media mounted in which slots.
*
* If any of these reflect a change in state, any registered listeners will be informed.
*
* @param update an update packet we received from a CDJ
*/
private static void handleUpdate(final CdjStatus update) {
// First see if any metadata caches need evicting or mount sets need updating.
if (update.isLocalUsbEmpty()) {
detachMetadataCache(update.deviceNumber, CdjStatus.TrackSourceSlot.USB_SLOT);
removeMount(update.deviceNumber, CdjStatus.TrackSourceSlot.USB_SLOT);
} else if (update.isLocalUsbLoaded()) {
recordMount(update.deviceNumber, CdjStatus.TrackSourceSlot.USB_SLOT);
}
if (update.isLocalSdEmpty()) {
detachMetadataCache(update.deviceNumber, CdjStatus.TrackSourceSlot.SD_SLOT);
removeMount(update.deviceNumber, CdjStatus.TrackSourceSlot.SD_SLOT);
} else if (update.isLocalSdLoaded()){
recordMount(update.deviceNumber, CdjStatus.TrackSourceSlot.SD_SLOT);
}
// Now see if a track has changed that needs new metadata.
if (update.getTrackType() != CdjStatus.TrackType.REKORDBOX ||
update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK ||
update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.UNKNOWN ||
update.getRekordboxId() == 0) { // We no longer have metadata for this device
clearMetadata(update);
} else { // We can gather metadata for this device; check if we already looked up this track
CdjStatus lastStatus = lastUpdates.get(update.address);
if (lastStatus == null || lastStatus.getTrackSourceSlot() != update.getTrackSourceSlot() ||
lastStatus.getTrackSourcePlayer() != update.getTrackSourcePlayer() ||
lastStatus.getRekordboxId() != update.getRekordboxId()) { // We have something new!
synchronized (activeRequests) {
// Make sure we are not already talking to the device before we try hitting it again.
if (!activeRequests.contains(update.getTrackSourcePlayer())) {
activeRequests.add(update.getTrackSourcePlayer());
new Thread(new Runnable() {
@Override
public void run() {
try {
TrackMetadata data = requestMetadataFrom(update);
if (data != null) {
updateMetadata(update, data);
}
} catch (Exception e) {
logger.warn("Problem requesting track metadata from update" + update, e);
} finally {
synchronized (activeRequests) {
activeRequests.remove(update.getTrackSourcePlayer());
}
}
}
}).start();
}
}
}
}
}
/**
* Start finding track metadata for all active players. Starts the {@link VirtualCdj} if it is not already
* running, because we need it to send us device status updates to notice when new tracks are loaded.
*
* @throws Exception if there is a problem starting the required components
*/
public static synchronized void start() throws Exception {
if (!running) {
DeviceFinder.start();
DeviceFinder.addDeviceAnnouncementListener(announcementListener);
for (DeviceAnnouncement device: DeviceFinder.currentDevices()) {
requestPlayerDBServerPort(device);
}
VirtualCdj.start();
VirtualCdj.addUpdateListener(updateListener);
queueHandler = new Thread(new Runnable() {
@Override
public void run() {
while (isRunning()) {
try {
handleUpdate(pendingUpdates.take());
} catch (InterruptedException e) {
// Interrupted due to MetadataFinder shutdown, presumably
}
}
}
});
running = true;
queueHandler.start();
}
}
/**
* Stop finding track metadata for all active players.
*/
public static synchronized void stop() {
if (running) {
VirtualCdj.removeUpdateListener(updateListener);
running = false;
pendingUpdates.clear();
queueHandler.interrupt();
queueHandler = null;
lastUpdates.clear();
metadata.clear();
}
}
}
| Use configured timeout for db server lookup too.
| src/main/java/org/deepsymmetry/beatlink/MetadataFinder.java | Use configured timeout for db server lookup too. | <ide><path>rc/main/java/org/deepsymmetry/beatlink/MetadataFinder.java
<ide> private static void requestPlayerDBServerPort(DeviceAnnouncement announcement) {
<ide> Socket socket = null;
<ide> try {
<del> socket = new Socket(announcement.getAddress(), DB_SERVER_QUERY_PORT);
<add> InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT);
<add> socket = new Socket();
<add> socket.connect(address, socketTimeout);
<ide> InputStream is = socket.getInputStream();
<ide> OutputStream os = socket.getOutputStream();
<del> socket.setSoTimeout(3000);
<add> socket.setSoTimeout(socketTimeout);
<ide> os.write(DB_SERVER_QUERY_PACKET);
<ide> byte[] response = readResponseWithExpectedSize(is, 2, "database server port query packet");
<ide> if (response.length == 2) { |
|
Java | apache-2.0 | 3ef380d3e23771b85c875eb6d1699f0d29120ade | 0 | ChinaQuants/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.masterdb.position;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.threeten.bp.Instant;
import org.threeten.bp.LocalDate;
import org.threeten.bp.LocalTime;
import org.threeten.bp.OffsetTime;
import org.threeten.bp.ZoneOffset;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.opengamma.DataNotFoundException;
import com.opengamma.elsql.ElSqlBundle;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.ExternalIdSearch;
import com.opengamma.id.IdUtils;
import com.opengamma.id.ObjectId;
import com.opengamma.id.ObjectIdentifiable;
import com.opengamma.id.UniqueId;
import com.opengamma.id.VersionCorrection;
import com.opengamma.master.AbstractHistoryRequest;
import com.opengamma.master.AbstractHistoryResult;
import com.opengamma.master.position.ManageablePosition;
import com.opengamma.master.position.ManageableTrade;
import com.opengamma.master.position.PositionDocument;
import com.opengamma.master.position.PositionHistoryRequest;
import com.opengamma.master.position.PositionHistoryResult;
import com.opengamma.master.position.PositionMaster;
import com.opengamma.master.position.PositionSearchRequest;
import com.opengamma.master.position.PositionSearchResult;
import com.opengamma.masterdb.AbstractDocumentDbMaster;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.db.DbConnector;
import com.opengamma.util.db.DbDateUtils;
import com.opengamma.util.db.DbMapSqlParameterSource;
import com.opengamma.util.money.Currency;
import com.opengamma.util.paging.Paging;
import com.opengamma.util.tuple.Pair;
import com.opengamma.util.tuple.Pairs;
/**
* A position master implementation using a database for persistence.
* <p>
* This is a full implementation of the position master using an SQL database. Full details of the API are in {@link PositionMaster}.
* <p>
* The SQL is stored externally in {@code DbPositionMaster.elsql}. Alternate databases or specific SQL requirements can be handled using database specific overrides, such as
* {@code DbPositionMaster-MySpecialDB.elsql}.
* <p>
* This class is mutable but must be treated as immutable after configuration.
*/
public class DbPositionMaster extends AbstractDocumentDbMaster<PositionDocument> implements PositionMaster {
/** Logger. */
private static final Logger s_logger = LoggerFactory.getLogger(DbPositionMaster.class);
/**
* The default scheme for unique identifiers.
*/
public static final String IDENTIFIER_SCHEME_DEFAULT = "DbPos";
// -----------------------------------------------------------------
// TIMERS FOR METRICS GATHERING
// By default these do nothing. Registration will replace them
// so that they actually do something.
// -----------------------------------------------------------------
private Timer _insertTimer = new Timer();
/**
* Creates an instance.
*
* @param dbConnector the database connector, not null
*/
public DbPositionMaster(final DbConnector dbConnector) {
super(dbConnector, IDENTIFIER_SCHEME_DEFAULT);
setElSqlBundle(ElSqlBundle.of(dbConnector.getDialect().getElSqlConfig(), DbPositionMaster.class));
}
@Override
public void registerMetrics(MetricRegistry summaryRegistry, MetricRegistry detailedRegistry, String namePrefix) {
super.registerMetrics(summaryRegistry, detailedRegistry, namePrefix);
_insertTimer = summaryRegistry.timer(namePrefix + ".insert");
}
//-------------------------------------------------------------------------
@Override
public PositionSearchResult search(final PositionSearchRequest request) {
ArgumentChecker.notNull(request, "request");
ArgumentChecker.notNull(request.getPagingRequest(), "request.pagingRequest");
ArgumentChecker.notNull(request.getVersionCorrection(), "request.versionCorrection");
s_logger.debug("search {}", request);
VersionCorrection vc = request.getVersionCorrection();
if (vc.containsLatest()) {
vc = vc.withLatestFixed(now());
}
final PositionSearchResult result = new PositionSearchResult(vc);
final ExternalIdSearch securityIdSearch = request.getSecurityIdSearch();
final Collection<ObjectId> positionObjectIds = request.getPositionObjectIds();
final Collection<ObjectId> tradeObjectIds = request.getTradeObjectIds();
if ((positionObjectIds != null && positionObjectIds.size() == 0) ||
(tradeObjectIds != null && tradeObjectIds.size() == 0) ||
(ExternalIdSearch.canMatch(securityIdSearch) == false)) {
result.setPaging(Paging.of(request.getPagingRequest(), 0));
return result;
}
final DbMapSqlParameterSource args = createParameterSource().addTimestamp("version_as_of_instant", vc.getVersionAsOf()).addTimestamp("corrected_to_instant", vc.getCorrectedTo())
.addValueNullIgnored("min_quantity", request.getMinQuantity()).addValueNullIgnored("max_quantity", request.getMaxQuantity())
.addValueNullIgnored("security_id_value", getDialect().sqlWildcardAdjustValue(request.getSecurityIdValue()));
if (request.getPositionProviderId() != null) {
args.addValue("pos_provider_scheme", request.getPositionProviderId().getScheme().getName());
args.addValue("pos_provider_value", request.getPositionProviderId().getValue());
}
if (request.getTradeProviderId() != null) {
args.addValue("trade_provider_scheme", request.getTradeProviderId().getScheme().getName());
args.addValue("trade_provider_value", request.getTradeProviderId().getValue());
}
if (securityIdSearch != null && securityIdSearch.alwaysMatches() == false) {
int i = 0;
for (final ExternalId id : securityIdSearch) {
args.addValue("key_scheme" + i, id.getScheme().getName());
args.addValue("key_value" + i, id.getValue());
i++;
}
args.addValue("sql_search_security_ids_type", securityIdSearch.getSearchType());
args.addValue("sql_search_security_ids", sqlSelectIdKeys(securityIdSearch));
args.addValue("security_id_search_size", securityIdSearch.getExternalIds().size());
}
if (positionObjectIds != null) {
final StringBuilder buf = new StringBuilder(positionObjectIds.size() * 10);
for (final ObjectId objectId : positionObjectIds) {
checkScheme(objectId);
buf.append(extractOid(objectId)).append(", ");
}
buf.setLength(buf.length() - 2);
args.addValue("sql_search_position_ids", buf.toString());
}
if (tradeObjectIds != null) {
final StringBuilder buf = new StringBuilder(tradeObjectIds.size() * 10);
for (final ObjectId objectId : tradeObjectIds) {
checkScheme(objectId);
buf.append(extractOid(objectId)).append(", ");
}
buf.setLength(buf.length() - 2);
args.addValue("sql_search_trade_ids", buf.toString());
}
args.addValue("paging_offset", request.getPagingRequest().getFirstItem());
args.addValue("paging_fetch", request.getPagingRequest().getPagingSize());
final String[] sql = {getElSqlBundle().getSql("Search", args), getElSqlBundle().getSql("SearchCount", args) };
doSearch(request.getPagingRequest(), sql, args, new PositionDocumentExtractor(), result);
return result;
}
/**
* Gets the SQL to find all the ids for a single bundle.
* <p>
* This is too complex for the elsql mechanism.
*
* @param idSearch the identifier search, not null
* @return the SQL, not null
*/
protected String sqlSelectIdKeys(final ExternalIdSearch idSearch) {
final List<String> list = new ArrayList<String>();
for (int i = 0; i < idSearch.size(); i++) {
list.add("(key_scheme = :key_scheme" + i + " AND key_value = :key_value" + i + ") ");
}
return StringUtils.join(list, "OR ");
}
//-------------------------------------------------------------------------
@Override
public PositionDocument get(final UniqueId uniqueId) {
return doGet(uniqueId, new PositionDocumentExtractor(), "Position");
}
//-------------------------------------------------------------------------
@Override
public PositionDocument get(final ObjectIdentifiable objectId, final VersionCorrection versionCorrection) {
return doGetByOidInstants(objectId, versionCorrection, new PositionDocumentExtractor(), "Position");
}
//-------------------------------------------------------------------------
@Override
public PositionHistoryResult history(final PositionHistoryRequest request) {
return doHistory(request, new PositionHistoryResult(), new PositionDocumentExtractor());
}
//-------------------------------------------------------------------------
/**
* Inserts a new document.
*
* @param document the document, not null
* @return the new document, not null
*/
@Override
protected PositionDocument insert(final PositionDocument document) {
ArgumentChecker.notNull(document.getPosition(), "document.position");
ArgumentChecker.notNull(document.getPosition().getQuantity(), "document.position.quantity");
for (final ManageableTrade trade : document.getPosition().getTrades()) {
ArgumentChecker.notNull(trade.getQuantity(), "position.trade.quantity");
ArgumentChecker.notNull(trade.getCounterpartyExternalId(), "position.trade.counterpartyexternalid");
ArgumentChecker.notNull(trade.getTradeDate(), "position.trade.tradedate");
}
try (Timer.Context context = _insertTimer.time()) {
final long positionId = nextId("pos_master_seq");
final long positionOid = (document.getUniqueId() != null ? extractOid(document.getUniqueId()) : positionId);
final UniqueId positionUid = createUniqueId(positionOid, positionId);
final ManageablePosition position = document.getPosition();
// the arguments for inserting into the position table
final DbMapSqlParameterSource docArgs = createParameterSource().addValue("position_id", positionId).addValue("position_oid", positionOid)
.addTimestamp("ver_from_instant", document.getVersionFromInstant()).addTimestampNullFuture("ver_to_instant", document.getVersionToInstant())
.addTimestamp("corr_from_instant", document.getCorrectionFromInstant())
.addTimestampNullFuture("corr_to_instant", document.getCorrectionToInstant())
.addValue("quantity", position.getQuantity(), Types.DECIMAL)
.addValue("provider_scheme",
position.getProviderId() != null ? position.getProviderId().getScheme().getName() : null, Types.VARCHAR)
.addValue("provider_value",
position.getProviderId() != null ? position.getProviderId().getValue() : null, Types.VARCHAR);
// the arguments for inserting into the pos_attribute table
final List<DbMapSqlParameterSource> posAttrList = Lists.newArrayList();
for (final Entry<String, String> entry : position.getAttributes().entrySet()) {
final long posAttrId = nextId("pos_trade_attr_seq");
final DbMapSqlParameterSource posAttrArgs = createParameterSource().addValue("attr_id", posAttrId)
.addValue("pos_id", positionId)
.addValue("pos_oid", positionOid)
.addValue("key", entry.getKey())
.addValue("value", entry.getValue());
posAttrList.add(posAttrArgs);
}
// the arguments for inserting into the idkey tables
final List<DbMapSqlParameterSource> posAssocList = new ArrayList<DbMapSqlParameterSource>();
final Set<Pair<String, String>> schemeValueSet = Sets.newHashSet();
for (final ExternalId id : position.getSecurityLink().getAllExternalIds()) {
final DbMapSqlParameterSource assocArgs = createParameterSource().addValue("position_id", positionId)
.addValue("key_scheme", id.getScheme().getName())
.addValue("key_value", id.getValue());
posAssocList.add(assocArgs);
schemeValueSet.add(Pairs.of(id.getScheme().getName(), id.getValue()));
}
// the arguments for inserting into the trade table
final List<DbMapSqlParameterSource> tradeList = Lists.newArrayList();
final List<DbMapSqlParameterSource> tradeAssocList = Lists.newArrayList();
final List<DbMapSqlParameterSource> tradeAttributeList = Lists.newArrayList();
for (final ManageableTrade trade : position.getTrades()) {
final long tradeId = nextId("pos_master_seq");
final long tradeOid = (trade.getUniqueId() != null ? extractOid(trade.getUniqueId()) : tradeId);
final ExternalId counterpartyId = trade.getCounterpartyExternalId();
final DbMapSqlParameterSource tradeArgs = createParameterSource().addValue("trade_id", tradeId)
.addValue("trade_oid", tradeOid)
.addValue("position_id", positionId)
.addValue("position_oid", positionOid)
.addValue("quantity", trade.getQuantity())
.addDate("trade_date", trade.getTradeDate())
.addTimeAllowNull("trade_time", trade.getTradeTime() != null ? trade.getTradeTime().toLocalTime() : null)
.addValue("zone_offset",
trade.getTradeTime() != null ? trade.getTradeTime().getOffset().getTotalSeconds() : null, Types.INTEGER)
.addValue("cparty_scheme", counterpartyId.getScheme().getName())
.addValue("cparty_value", counterpartyId.getValue())
.addValue("provider_scheme",
trade.getProviderId() != null ? trade.getProviderId().getScheme().getName() : null, Types.VARCHAR)
.addValue("provider_value",
trade.getProviderId() != null ? trade.getProviderId().getValue() : null, Types.VARCHAR)
.addValue("premium_value", trade.getPremium(), Types.DOUBLE)
.addValue("premium_currency",
trade.getPremiumCurrency() != null ? trade.getPremiumCurrency().getCode() : null, Types.VARCHAR)
.addDateAllowNull("premium_date", trade.getPremiumDate())
.addTimeAllowNull("premium_time", (trade.getPremiumTime() != null ? trade.getPremiumTime().toLocalTime() : null))
.addValue("premium_zone_offset",
trade.getPremiumTime() != null ? trade.getPremiumTime().getOffset().getTotalSeconds() : null, Types.INTEGER);
tradeList.add(tradeArgs);
// trade attributes
final Map<String, String> attributes = new HashMap<String, String>(trade.getAttributes());
for (final Entry<String, String> entry : attributes.entrySet()) {
final long tradeAttrId = nextId("pos_trade_attr_seq");
final DbMapSqlParameterSource tradeAttributeArgs = createParameterSource().addValue("attr_id", tradeAttrId)
.addValue("trade_id", tradeId)
.addValue("trade_oid", tradeOid)
.addValue("key", entry.getKey())
.addValue("value", entry.getValue());
tradeAttributeList.add(tradeAttributeArgs);
}
// set the trade uniqueId
final UniqueId tradeUid = createUniqueId(tradeOid, tradeId);
IdUtils.setInto(trade, tradeUid);
trade.setParentPositionId(positionUid);
for (final ExternalId id : trade.getSecurityLink().getAllExternalIds()) {
final DbMapSqlParameterSource assocArgs = createParameterSource().addValue("trade_id", tradeId)
.addValue("key_scheme", id.getScheme().getName())
.addValue("key_value", id.getValue());
tradeAssocList.add(assocArgs);
schemeValueSet.add(Pairs.of(id.getScheme().getName(), id.getValue()));
}
}
final List<DbMapSqlParameterSource> idKeyList = new ArrayList<DbMapSqlParameterSource>();
final String sqlSelectIdKey = getElSqlBundle().getSql("SelectIdKey");
for (final Pair<String, String> pair : schemeValueSet) {
final DbMapSqlParameterSource idkeyArgs = createParameterSource().addValue("key_scheme", pair.getFirst())
.addValue("key_value", pair.getSecond());
if (getJdbcTemplate().queryForList(sqlSelectIdKey, idkeyArgs).isEmpty()) {
// select avoids creating unecessary id, but id may still not be used
final long idKeyId = nextId("pos_idkey_seq");
idkeyArgs.addValue("idkey_id", idKeyId);
idKeyList.add(idkeyArgs);
}
}
final String sqlDoc = getElSqlBundle().getSql("Insert", docArgs);
final String sqlIdKey = getElSqlBundle().getSql("InsertIdKey");
final String sqlPosition2IdKey = getElSqlBundle().getSql("InsertPosition2IdKey");
final String sqlTrade = getElSqlBundle().getSql("InsertTrade");
final String sqlTrade2IdKey = getElSqlBundle().getSql("InsertTrade2IdKey");
final String sqlPositionAttributes = getElSqlBundle().getSql("InsertPositionAttributes");
final String sqlTradeAttributes = getElSqlBundle().getSql("InsertTradeAttributes");
getJdbcTemplate().update(sqlDoc, docArgs);
getJdbcTemplate().batchUpdate(sqlIdKey, idKeyList.toArray(new DbMapSqlParameterSource[idKeyList.size()]));
getJdbcTemplate().batchUpdate(sqlPosition2IdKey, posAssocList.toArray(new DbMapSqlParameterSource[posAssocList.size()]));
getJdbcTemplate().batchUpdate(sqlTrade, tradeList.toArray(new DbMapSqlParameterSource[tradeList.size()]));
getJdbcTemplate().batchUpdate(sqlTrade2IdKey, tradeAssocList.toArray(new DbMapSqlParameterSource[tradeAssocList.size()]));
getJdbcTemplate().batchUpdate(sqlPositionAttributes, posAttrList.toArray(new DbMapSqlParameterSource[posAttrList.size()]));
getJdbcTemplate().batchUpdate(sqlTradeAttributes, tradeAttributeList.toArray(new DbMapSqlParameterSource[tradeAttributeList.size()]));
// set the uniqueId
position.setUniqueId(positionUid);
document.setUniqueId(positionUid);
return document;
}
}
//-------------------------------------------------------------------------
@Override
public ManageableTrade getTrade(final UniqueId uniqueId) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
checkScheme(uniqueId);
if (uniqueId.isVersioned()) {
return getTradeById(uniqueId);
} else {
return getTradeByInstants(uniqueId, null, null);
}
}
/**
* Gets a trade by searching for the latest version of an object identifier.
*
* @param uniqueId the unique identifier, not null
* @param versionAsOf the instant to fetch, not null
* @param correctedTo the instant to fetch, not null
* @return the trade, null if not found
*/
protected ManageableTrade getTradeByInstants(final UniqueId uniqueId, final Instant versionAsOf, final Instant correctedTo) {
s_logger.debug("getTradeByLatest {}", uniqueId);
final Instant now = now();
final DbMapSqlParameterSource args = createParameterSource().addValue("trade_oid", extractOid(uniqueId))
.addTimestamp("version_as_of_instant", Objects.firstNonNull(versionAsOf, now))
.addTimestamp("corrected_to_instant", Objects.firstNonNull(correctedTo, now));
final PositionDocumentExtractor extractor = new PositionDocumentExtractor();
final NamedParameterJdbcOperations namedJdbc = getDbConnector().getJdbcTemplate();
final String sql = getElSqlBundle().getSql("GetTradeByOidInstants", args);
final List<PositionDocument> docs = namedJdbc.query(sql, args, extractor);
if (docs.isEmpty()) {
throw new DataNotFoundException("Trade not found: " + uniqueId);
}
return docs.get(0).getPosition().getTrades().get(0); // SQL loads desired trade as only trade
}
/**
* Gets a trade by identifier.
*
* @param uniqueId the unique identifier, not null
* @return the trade, null if not found
*/
protected ManageableTrade getTradeById(final UniqueId uniqueId) {
s_logger.debug("getTradeById {}", uniqueId);
final DbMapSqlParameterSource args = createParameterSource().addValue("trade_id", extractRowId(uniqueId));
final PositionDocumentExtractor extractor = new PositionDocumentExtractor();
final NamedParameterJdbcOperations namedJdbc = getDbConnector().getJdbcTemplate();
final String sql = getElSqlBundle().getSql("GetTradeById", args);
final List<PositionDocument> docs = namedJdbc.query(sql, args, extractor);
if (docs.isEmpty()) {
throw new DataNotFoundException("Trade not found: " + uniqueId);
}
return docs.get(0).getPosition().getTrades().get(0); // SQL loads desired trade as only trade
}
//-------------------------------------------------------------------------
@Override
protected AbstractHistoryResult<PositionDocument> historyByVersionsCorrections(final AbstractHistoryRequest request) {
final PositionHistoryRequest historyRequest = new PositionHistoryRequest();
historyRequest.setCorrectionsFromInstant(request.getCorrectionsFromInstant());
historyRequest.setCorrectionsToInstant(request.getCorrectionsToInstant());
historyRequest.setVersionsFromInstant(request.getVersionsFromInstant());
historyRequest.setVersionsToInstant(request.getVersionsToInstant());
historyRequest.setObjectId(request.getObjectId());
return history(historyRequest);
}
//-------------------------------------------------------------------------
/**
* Mapper from SQL rows to a PositionDocument.
*/
protected final class PositionDocumentExtractor implements ResultSetExtractor<List<PositionDocument>> {
private long _lastPositionId = -1;
private long _lastTradeId = -1;
private ManageablePosition _position;
private ManageableTrade _trade;
private final List<PositionDocument> _documents = new ArrayList<PositionDocument>();
@Override
public List<PositionDocument> extractData(final ResultSet rs) throws SQLException, DataAccessException {
while (rs.next()) {
final long positionId = rs.getLong("POSITION_ID");
if (_lastPositionId != positionId) {
_lastPositionId = positionId;
buildPosition(rs, positionId);
}
final String posIdScheme = rs.getString("POS_KEY_SCHEME");
final String posIdValue = rs.getString("POS_KEY_VALUE");
if (posIdScheme != null && posIdValue != null) {
if (posIdScheme.equals(ObjectId.EXTERNAL_SCHEME.getName())) {
final ObjectId oid = ObjectId.parse(posIdValue);
_position.getSecurityLink().setObjectId(oid);
} else {
final ExternalId id = ExternalId.of(posIdScheme, posIdValue);
_position.getSecurityLink().addExternalId(id);
}
}
final String posAttrKey = rs.getString("POS_ATTR_KEY");
final String posAttrValue = rs.getString("POS_ATTR_VALUE");
if (posAttrKey != null && posAttrValue != null) {
_position.addAttribute(posAttrKey, posAttrValue);
}
final long tradeId = rs.getLong("TRADE_ID");
if (_lastTradeId != tradeId && tradeId != 0) {
buildTrade(rs, tradeId);
}
final String tradeIdScheme = rs.getString("TRADE_KEY_SCHEME");
final String tradeIdValue = rs.getString("TRADE_KEY_VALUE");
if (tradeIdScheme != null && tradeIdValue != null) {
if (tradeIdScheme.equals(ObjectId.EXTERNAL_SCHEME.getName())) {
final ObjectId oid = ObjectId.parse(tradeIdValue);
_trade.getSecurityLink().setObjectId(oid);
} else {
final ExternalId id = ExternalId.of(tradeIdScheme, tradeIdValue);
_trade.getSecurityLink().addExternalId(id);
}
}
final String tradeAttrKey = rs.getString("TRADE_ATTR_KEY");
final String tradeAttrValue = rs.getString("TRADE_ATTR_VALUE");
if (tradeAttrKey != null && tradeAttrValue != null) {
_trade.addAttribute(tradeAttrKey, tradeAttrValue);
}
}
return _documents;
}
private void buildPosition(final ResultSet rs, final long positionId) throws SQLException {
final long positionOid = rs.getLong("POSITION_OID");
final BigDecimal quantity = extractBigDecimal(rs, "POS_QUANTITY");
final Timestamp versionFrom = rs.getTimestamp("VER_FROM_INSTANT");
final Timestamp versionTo = rs.getTimestamp("VER_TO_INSTANT");
final Timestamp correctionFrom = rs.getTimestamp("CORR_FROM_INSTANT");
final Timestamp correctionTo = rs.getTimestamp("CORR_TO_INSTANT");
final String providerScheme = rs.getString("POS_PROVIDER_SCHEME");
final String providerValue = rs.getString("POS_PROVIDER_VALUE");
_position = new ManageablePosition(quantity, ExternalIdBundle.EMPTY);
_position.setUniqueId(createUniqueId(positionOid, positionId));
if (providerScheme != null && providerValue != null) {
_position.setProviderId(ExternalId.of(providerScheme, providerValue));
}
final PositionDocument doc = new PositionDocument(_position);
doc.setVersionFromInstant(DbDateUtils.fromSqlTimestamp(versionFrom));
doc.setVersionToInstant(DbDateUtils.fromSqlTimestampNullFarFuture(versionTo));
doc.setCorrectionFromInstant(DbDateUtils.fromSqlTimestamp(correctionFrom));
doc.setCorrectionToInstant(DbDateUtils.fromSqlTimestampNullFarFuture(correctionTo));
doc.setUniqueId(createUniqueId(positionOid, positionId));
_documents.add(doc);
}
private void buildTrade(final ResultSet rs, final long tradeId) throws SQLException {
_lastTradeId = tradeId;
final long tradeOid = rs.getLong("TRADE_OID");
final BigDecimal tradeQuantity = extractBigDecimal(rs, "TRADE_QUANTITY");
final LocalDate tradeDate = DbDateUtils.fromSqlDate(rs.getDate("TRADE_DATE"));
final LocalTime tradeTime = rs.getTimestamp("TRADE_TIME") != null ? DbDateUtils.fromSqlTime(rs.getTimestamp("TRADE_TIME")) : null;
final int zoneOffset = rs.getInt("ZONE_OFFSET");
final String cpartyScheme = rs.getString("CPARTY_SCHEME");
final String cpartyValue = rs.getString("CPARTY_VALUE");
final String providerScheme = rs.getString("TRADE_PROVIDER_SCHEME");
final String providerValue = rs.getString("TRADE_PROVIDER_VALUE");
OffsetTime tradeOffsetTime = null;
if (tradeTime != null) {
tradeOffsetTime = OffsetTime.of(tradeTime, ZoneOffset.ofTotalSeconds(zoneOffset));
}
ExternalId counterpartyId = null;
if (cpartyScheme != null && cpartyValue != null) {
counterpartyId = ExternalId.of(cpartyScheme, cpartyValue);
}
_trade = new ManageableTrade(tradeQuantity, ExternalIdBundle.EMPTY, tradeDate, tradeOffsetTime, counterpartyId);
_trade.setUniqueId(createUniqueId(tradeOid, tradeId));
if (providerScheme != null && providerValue != null) {
_trade.setProviderId(ExternalId.of(providerScheme, providerValue));
}
// different databases return different types, notably BigDecimal and Double
// note that getObject(key, Double.class) does not seem to work
final Object premiumValue = rs.getObject("PREMIUM_VALUE");
if (premiumValue != null) {
_trade.setPremium(rs.getDouble("PREMIUM_VALUE"));
}
final String currencyCode = rs.getString("PREMIUM_CURRENCY");
if (currencyCode != null) {
_trade.setPremiumCurrency(Currency.of(currencyCode));
}
final Date premiumDate = rs.getDate("PREMIUM_DATE");
if (premiumDate != null) {
_trade.setPremiumDate(DbDateUtils.fromSqlDate(premiumDate));
}
_trade.setParentPositionId(_position.getUniqueId());
final LocalTime premiumTime = rs.getTimestamp("PREMIUM_TIME") != null ? DbDateUtils.fromSqlTime(rs.getTimestamp("PREMIUM_TIME")) : null;
final int premiumZoneOffset = rs.getInt("PREMIUM_ZONE_OFFSET");
if (premiumTime != null) {
_trade.setPremiumTime(OffsetTime.of(premiumTime, ZoneOffset.ofTotalSeconds(premiumZoneOffset)));
}
_position.getTrades().add(_trade);
}
}
}
| projects/OG-MasterDB/src/main/java/com/opengamma/masterdb/position/DbPositionMaster.java | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.masterdb.position;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.threeten.bp.Instant;
import org.threeten.bp.LocalDate;
import org.threeten.bp.LocalTime;
import org.threeten.bp.OffsetTime;
import org.threeten.bp.ZoneOffset;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.opengamma.DataNotFoundException;
import com.opengamma.elsql.ElSqlBundle;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.ExternalIdSearch;
import com.opengamma.id.IdUtils;
import com.opengamma.id.ObjectId;
import com.opengamma.id.ObjectIdentifiable;
import com.opengamma.id.UniqueId;
import com.opengamma.id.VersionCorrection;
import com.opengamma.master.AbstractHistoryRequest;
import com.opengamma.master.AbstractHistoryResult;
import com.opengamma.master.position.ManageablePosition;
import com.opengamma.master.position.ManageableTrade;
import com.opengamma.master.position.PositionDocument;
import com.opengamma.master.position.PositionHistoryRequest;
import com.opengamma.master.position.PositionHistoryResult;
import com.opengamma.master.position.PositionMaster;
import com.opengamma.master.position.PositionSearchRequest;
import com.opengamma.master.position.PositionSearchResult;
import com.opengamma.masterdb.AbstractDocumentDbMaster;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.db.DbConnector;
import com.opengamma.util.db.DbDateUtils;
import com.opengamma.util.db.DbMapSqlParameterSource;
import com.opengamma.util.money.Currency;
import com.opengamma.util.paging.Paging;
import com.opengamma.util.tuple.Pair;
import com.opengamma.util.tuple.Pairs;
/**
* A position master implementation using a database for persistence.
* <p>
* This is a full implementation of the position master using an SQL database. Full details of the API are in {@link PositionMaster}.
* <p>
* The SQL is stored externally in {@code DbPositionMaster.elsql}. Alternate databases or specific SQL requirements can be handled using database specific overrides, such as
* {@code DbPositionMaster-MySpecialDB.elsql}.
* <p>
* This class is mutable but must be treated as immutable after configuration.
*/
public class DbPositionMaster extends AbstractDocumentDbMaster<PositionDocument> implements PositionMaster {
/** Logger. */
private static final Logger s_logger = LoggerFactory.getLogger(DbPositionMaster.class);
/**
* The default scheme for unique identifiers.
*/
public static final String IDENTIFIER_SCHEME_DEFAULT = "DbPos";
// -----------------------------------------------------------------
// TIMERS FOR METRICS GATHERING
// By default these do nothing. Registration will replace them
// so that they actually do something.
// -----------------------------------------------------------------
private Timer _insertTimer = new Timer();
/**
* Creates an instance.
*
* @param dbConnector the database connector, not null
*/
public DbPositionMaster(final DbConnector dbConnector) {
super(dbConnector, IDENTIFIER_SCHEME_DEFAULT);
setElSqlBundle(ElSqlBundle.of(dbConnector.getDialect().getElSqlConfig(), DbPositionMaster.class));
}
@Override
public void registerMetrics(MetricRegistry summaryRegistry, MetricRegistry detailedRegistry, String namePrefix) {
super.registerMetrics(summaryRegistry, detailedRegistry, namePrefix);
_insertTimer = summaryRegistry.timer(namePrefix + ".insert");
}
//-------------------------------------------------------------------------
@Override
public PositionSearchResult search(final PositionSearchRequest request) {
ArgumentChecker.notNull(request, "request");
ArgumentChecker.notNull(request.getPagingRequest(), "request.pagingRequest");
ArgumentChecker.notNull(request.getVersionCorrection(), "request.versionCorrection");
s_logger.debug("search {}", request);
VersionCorrection vc = request.getVersionCorrection();
if (vc.containsLatest()) {
vc = vc.withLatestFixed(now());
}
final PositionSearchResult result = new PositionSearchResult(vc);
final ExternalIdSearch securityIdSearch = request.getSecurityIdSearch();
final Collection<ObjectId> positionObjectIds = request.getPositionObjectIds();
final Collection<ObjectId> tradeObjectIds = request.getTradeObjectIds();
if ((positionObjectIds != null && positionObjectIds.size() == 0) ||
(tradeObjectIds != null && tradeObjectIds.size() == 0) ||
(ExternalIdSearch.canMatch(securityIdSearch) == false)) {
result.setPaging(Paging.of(request.getPagingRequest(), 0));
return result;
}
final DbMapSqlParameterSource args = createParameterSource().addTimestamp("version_as_of_instant", vc.getVersionAsOf()).addTimestamp("corrected_to_instant", vc.getCorrectedTo())
.addValueNullIgnored("min_quantity", request.getMinQuantity()).addValueNullIgnored("max_quantity", request.getMaxQuantity())
.addValueNullIgnored("security_id_value", getDialect().sqlWildcardAdjustValue(request.getSecurityIdValue()));
if (request.getPositionProviderId() != null) {
args.addValue("pos_provider_scheme", request.getPositionProviderId().getScheme().getName());
args.addValue("pos_provider_value", request.getPositionProviderId().getValue());
}
if (request.getTradeProviderId() != null) {
args.addValue("trade_provider_scheme", request.getTradeProviderId().getScheme().getName());
args.addValue("trade_provider_value", request.getTradeProviderId().getValue());
}
if (securityIdSearch != null && securityIdSearch.alwaysMatches() == false) {
int i = 0;
for (final ExternalId id : securityIdSearch) {
args.addValue("key_scheme" + i, id.getScheme().getName());
args.addValue("key_value" + i, id.getValue());
i++;
}
args.addValue("sql_search_security_ids_type", securityIdSearch.getSearchType());
args.addValue("sql_search_security_ids", sqlSelectIdKeys(securityIdSearch));
args.addValue("security_id_search_size", securityIdSearch.getExternalIds().size());
}
if (positionObjectIds != null) {
final StringBuilder buf = new StringBuilder(positionObjectIds.size() * 10);
for (final ObjectId objectId : positionObjectIds) {
checkScheme(objectId);
buf.append(extractOid(objectId)).append(", ");
}
buf.setLength(buf.length() - 2);
args.addValue("sql_search_position_ids", buf.toString());
}
if (tradeObjectIds != null) {
final StringBuilder buf = new StringBuilder(tradeObjectIds.size() * 10);
for (final ObjectId objectId : tradeObjectIds) {
checkScheme(objectId);
buf.append(extractOid(objectId)).append(", ");
}
buf.setLength(buf.length() - 2);
args.addValue("sql_search_trade_ids", buf.toString());
}
args.addValue("paging_offset", request.getPagingRequest().getFirstItem());
args.addValue("paging_fetch", request.getPagingRequest().getPagingSize());
final String[] sql = {getElSqlBundle().getSql("Search", args), getElSqlBundle().getSql("SearchCount", args) };
doSearch(request.getPagingRequest(), sql, args, new PositionDocumentExtractor(), result);
return result;
}
/**
* Gets the SQL to find all the ids for a single bundle.
* <p>
* This is too complex for the elsql mechanism.
*
* @param idSearch the identifier search, not null
* @return the SQL, not null
*/
protected String sqlSelectIdKeys(final ExternalIdSearch idSearch) {
final List<String> list = new ArrayList<String>();
for (int i = 0; i < idSearch.size(); i++) {
list.add("(key_scheme = :key_scheme" + i + " AND key_value = :key_value" + i + ") ");
}
return StringUtils.join(list, "OR ");
}
//-------------------------------------------------------------------------
@Override
public PositionDocument get(final UniqueId uniqueId) {
return doGet(uniqueId, new PositionDocumentExtractor(), "Position");
}
//-------------------------------------------------------------------------
@Override
public PositionDocument get(final ObjectIdentifiable objectId, final VersionCorrection versionCorrection) {
return doGetByOidInstants(objectId, versionCorrection, new PositionDocumentExtractor(), "Position");
}
//-------------------------------------------------------------------------
@Override
public PositionHistoryResult history(final PositionHistoryRequest request) {
return doHistory(request, new PositionHistoryResult(), new PositionDocumentExtractor());
}
//-------------------------------------------------------------------------
/**
* Inserts a new document.
*
* @param document the document, not null
* @return the new document, not null
*/
@Override
protected PositionDocument insert(final PositionDocument document) {
ArgumentChecker.notNull(document.getPosition(), "document.position");
ArgumentChecker.notNull(document.getPosition().getQuantity(), "document.position.quantity");
for (final ManageableTrade trade : document.getPosition().getTrades()) {
ArgumentChecker.notNull(trade.getQuantity(), "position.trade.quantity");
ArgumentChecker.notNull(trade.getCounterpartyExternalId(), "position.trade.counterpartyexternalid");
ArgumentChecker.notNull(trade.getTradeDate(), "position.trade.tradedate");
}
try (Timer.Context context = _insertTimer.time()) {
final long positionId = nextId("pos_master_seq");
final long positionOid = (document.getUniqueId() != null ? extractOid(document.getUniqueId()) : positionId);
final UniqueId positionUid = createUniqueId(positionOid, positionId);
final ManageablePosition position = document.getPosition();
// the arguments for inserting into the position table
final DbMapSqlParameterSource docArgs = createParameterSource().addValue("position_id", positionId).addValue("position_oid", positionOid)
.addTimestamp("ver_from_instant", document.getVersionFromInstant()).addTimestampNullFuture("ver_to_instant", document.getVersionToInstant())
.addTimestamp("corr_from_instant", document.getCorrectionFromInstant())
.addTimestampNullFuture("corr_to_instant", document.getCorrectionToInstant())
.addValue("quantity", position.getQuantity(), Types.DECIMAL)
.addValue("provider_scheme",
position.getProviderId() != null ? position.getProviderId().getScheme().getName() : null, Types.VARCHAR)
.addValue("provider_value",
position.getProviderId() != null ? position.getProviderId().getValue() : null, Types.VARCHAR);
// the arguments for inserting into the pos_attribute table
final List<DbMapSqlParameterSource> posAttrList = Lists.newArrayList();
for (final Entry<String, String> entry : position.getAttributes().entrySet()) {
final long posAttrId = nextId("pos_trade_attr_seq");
final DbMapSqlParameterSource posAttrArgs = createParameterSource().addValue("attr_id", posAttrId)
.addValue("pos_id", positionId)
.addValue("pos_oid", positionOid)
.addValue("key", entry.getKey())
.addValue("value", entry.getValue());
posAttrList.add(posAttrArgs);
}
// the arguments for inserting into the idkey tables
final List<DbMapSqlParameterSource> posAssocList = new ArrayList<DbMapSqlParameterSource>();
final Set<Pair<String, String>> schemeValueSet = Sets.newHashSet();
for (final ExternalId id : position.getSecurityLink().getAllExternalIds()) {
final DbMapSqlParameterSource assocArgs = createParameterSource().addValue("position_id", positionId)
.addValue("key_scheme", id.getScheme().getName())
.addValue("key_value", id.getValue());
posAssocList.add(assocArgs);
schemeValueSet.add(Pairs.of(id.getScheme().getName(), id.getValue()));
}
// the arguments for inserting into the trade table
final List<DbMapSqlParameterSource> tradeList = Lists.newArrayList();
final List<DbMapSqlParameterSource> tradeAssocList = Lists.newArrayList();
final List<DbMapSqlParameterSource> tradeAttributeList = Lists.newArrayList();
for (final ManageableTrade trade : position.getTrades()) {
final long tradeId = nextId("pos_master_seq");
final long tradeOid = (trade.getUniqueId() != null ? extractOid(trade.getUniqueId()) : tradeId);
final ExternalId counterpartyId = trade.getCounterpartyExternalId();
final DbMapSqlParameterSource tradeArgs = createParameterSource().addValue("trade_id", tradeId)
.addValue("trade_oid", tradeOid)
.addValue("position_id", positionId)
.addValue("position_oid", positionOid)
.addValue("quantity", trade.getQuantity())
.addDate("trade_date", trade.getTradeDate())
.addTimeAllowNull("trade_time", trade.getTradeTime() != null ? trade.getTradeTime().toLocalTime() : null)
.addValue("zone_offset",
trade.getTradeTime() != null ? trade.getTradeTime().getOffset().getTotalSeconds() : null, Types.INTEGER)
.addValue("cparty_scheme", counterpartyId.getScheme().getName())
.addValue("cparty_value", counterpartyId.getValue())
.addValue("provider_scheme",
trade.getProviderId() != null ? trade.getProviderId().getScheme().getName() : null, Types.VARCHAR)
.addValue("provider_value",
trade.getProviderId() != null ? trade.getProviderId().getValue() : null, Types.VARCHAR)
.addValue("premium_value", trade.getPremium(), Types.DOUBLE)
.addValue("premium_currency",
trade.getPremiumCurrency() != null ? trade.getPremiumCurrency().getCode() : null, Types.VARCHAR)
.addDateAllowNull("premium_date", trade.getPremiumDate())
.addTimeAllowNull("premium_time", (trade.getPremiumTime() != null ? trade.getPremiumTime().toLocalTime() : null))
.addValue("premium_zone_offset",
trade.getPremiumTime() != null ? trade.getPremiumTime().getOffset().getTotalSeconds() : null, Types.INTEGER);
tradeList.add(tradeArgs);
// trade attributes
final Map<String, String> attributes = new HashMap<String, String>(trade.getAttributes());
for (final Entry<String, String> entry : attributes.entrySet()) {
final long tradeAttrId = nextId("pos_trade_attr_seq");
final DbMapSqlParameterSource tradeAttributeArgs = createParameterSource().addValue("attr_id", tradeAttrId)
.addValue("trade_id", tradeId)
.addValue("trade_oid", tradeOid)
.addValue("key", entry.getKey())
.addValue("value", entry.getValue());
tradeAttributeList.add(tradeAttributeArgs);
}
// set the trade uniqueId
final UniqueId tradeUid = createUniqueId(tradeOid, tradeId);
IdUtils.setInto(trade, tradeUid);
trade.setParentPositionId(positionUid);
for (final ExternalId id : trade.getSecurityLink().getAllExternalIds()) {
final DbMapSqlParameterSource assocArgs = createParameterSource().addValue("trade_id", tradeId)
.addValue("key_scheme", id.getScheme().getName())
.addValue("key_value", id.getValue());
tradeAssocList.add(assocArgs);
schemeValueSet.add(Pairs.of(id.getScheme().getName(), id.getValue()));
}
}
final List<DbMapSqlParameterSource> idKeyList = new ArrayList<DbMapSqlParameterSource>();
final String sqlSelectIdKey = getElSqlBundle().getSql("SelectIdKey");
for (final Pair<String, String> pair : schemeValueSet) {
final DbMapSqlParameterSource idkeyArgs = createParameterSource().addValue("key_scheme", pair.getFirst())
.addValue("key_value", pair.getSecond());
if (getJdbcTemplate().queryForList(sqlSelectIdKey, idkeyArgs).isEmpty()) {
// select avoids creating unecessary id, but id may still not be used
final long idKeyId = nextId("pos_idkey_seq");
idkeyArgs.addValue("idkey_id", idKeyId);
idKeyList.add(idkeyArgs);
}
}
final String sqlDoc = getElSqlBundle().getSql("Insert", docArgs);
final String sqlIdKey = getElSqlBundle().getSql("InsertIdKey");
final String sqlPosition2IdKey = getElSqlBundle().getSql("InsertPosition2IdKey");
final String sqlTrade = getElSqlBundle().getSql("InsertTrade");
final String sqlTrade2IdKey = getElSqlBundle().getSql("InsertTrade2IdKey");
final String sqlPositionAttributes = getElSqlBundle().getSql("InsertPositionAttributes");
final String sqlTradeAttributes = getElSqlBundle().getSql("InsertTradeAttributes");
getJdbcTemplate().update(sqlDoc, docArgs);
getJdbcTemplate().batchUpdate(sqlIdKey, idKeyList.toArray(new DbMapSqlParameterSource[idKeyList.size()]));
getJdbcTemplate().batchUpdate(sqlPosition2IdKey, posAssocList.toArray(new DbMapSqlParameterSource[posAssocList.size()]));
getJdbcTemplate().batchUpdate(sqlTrade, tradeList.toArray(new DbMapSqlParameterSource[tradeList.size()]));
getJdbcTemplate().batchUpdate(sqlTrade2IdKey, tradeAssocList.toArray(new DbMapSqlParameterSource[tradeAssocList.size()]));
getJdbcTemplate().batchUpdate(sqlPositionAttributes, posAttrList.toArray(new DbMapSqlParameterSource[posAttrList.size()]));
getJdbcTemplate().batchUpdate(sqlTradeAttributes, tradeAttributeList.toArray(new DbMapSqlParameterSource[tradeAttributeList.size()]));
// set the uniqueId
position.setUniqueId(positionUid);
document.setUniqueId(positionUid);
return document;
}
}
//-------------------------------------------------------------------------
@Override
public ManageableTrade getTrade(final UniqueId uniqueId) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
checkScheme(uniqueId);
if (uniqueId.isVersioned()) {
return getTradeById(uniqueId);
} else {
return getTradeByInstants(uniqueId, null, null);
}
}
/**
* Gets a trade by searching for the latest version of an object identifier.
*
* @param uniqueId the unique identifier, not null
* @param versionAsOf the instant to fetch, not null
* @param correctedTo the instant to fetch, not null
* @return the trade, null if not found
*/
protected ManageableTrade getTradeByInstants(final UniqueId uniqueId, final Instant versionAsOf, final Instant correctedTo) {
s_logger.debug("getTradeByLatest {}", uniqueId);
final Instant now = now();
final DbMapSqlParameterSource args = createParameterSource().addValue("trade_oid", extractOid(uniqueId))
.addTimestamp("version_as_of_instant", Objects.firstNonNull(versionAsOf, now))
.addTimestamp("corrected_to_instant", Objects.firstNonNull(correctedTo, now));
final PositionDocumentExtractor extractor = new PositionDocumentExtractor();
final NamedParameterJdbcOperations namedJdbc = getDbConnector().getJdbcTemplate();
final String sql = getElSqlBundle().getSql("GetTradeByOidInstants", args);
final List<PositionDocument> docs = namedJdbc.query(sql, args, extractor);
if (docs.isEmpty()) {
throw new DataNotFoundException("Trade not found: " + uniqueId);
}
return docs.get(0).getPosition().getTrades().get(0); // SQL loads desired trade as only trade
}
/**
* Gets a trade by identifier.
*
* @param uniqueId the unique identifier, not null
* @return the trade, null if not found
*/
protected ManageableTrade getTradeById(final UniqueId uniqueId) {
s_logger.debug("getTradeById {}", uniqueId);
final DbMapSqlParameterSource args = createParameterSource().addValue("trade_id", extractRowId(uniqueId));
final PositionDocumentExtractor extractor = new PositionDocumentExtractor();
final NamedParameterJdbcOperations namedJdbc = getDbConnector().getJdbcTemplate();
final String sql = getElSqlBundle().getSql("GetTradeById", args);
final List<PositionDocument> docs = namedJdbc.query(sql, args, extractor);
if (docs.isEmpty()) {
throw new DataNotFoundException("Trade not found: " + uniqueId);
}
return docs.get(0).getPosition().getTrades().get(0); // SQL loads desired trade as only trade
}
//-------------------------------------------------------------------------
@Override
protected AbstractHistoryResult<PositionDocument> historyByVersionsCorrections(final AbstractHistoryRequest request) {
final PositionHistoryRequest historyRequest = new PositionHistoryRequest();
historyRequest.setCorrectionsFromInstant(request.getCorrectionsFromInstant());
historyRequest.setCorrectionsToInstant(request.getCorrectionsToInstant());
historyRequest.setVersionsFromInstant(request.getVersionsFromInstant());
historyRequest.setVersionsToInstant(request.getVersionsToInstant());
historyRequest.setObjectId(request.getObjectId());
return history(historyRequest);
}
//-------------------------------------------------------------------------
/**
* Mapper from SQL rows to a PositionDocument.
*/
protected final class PositionDocumentExtractor implements ResultSetExtractor<List<PositionDocument>> {
private long _lastPositionId = -1;
private long _lastTradeId = -1;
private ManageablePosition _position;
private ManageableTrade _trade;
private final List<PositionDocument> _documents = new ArrayList<PositionDocument>();
@Override
public List<PositionDocument> extractData(final ResultSet rs) throws SQLException, DataAccessException {
while (rs.next()) {
final long positionId = rs.getLong("POSITION_ID");
if (_lastPositionId != positionId) {
_lastPositionId = positionId;
buildPosition(rs, positionId);
}
final String posIdScheme = rs.getString("POS_KEY_SCHEME");
final String posIdValue = rs.getString("POS_KEY_VALUE");
if (posIdScheme != null && posIdValue != null) {
if (posIdScheme.equals(ObjectId.EXTERNAL_SCHEME.getName())) {
final ObjectId oid = ObjectId.parse(posIdValue);
_position.getSecurityLink().setObjectId(oid);
} else {
final ExternalId id = ExternalId.of(posIdScheme, posIdValue);
_position.getSecurityLink().addExternalId(id);
}
}
final String posAttrKey = rs.getString("POS_ATTR_KEY");
final String posAttrValue = rs.getString("POS_ATTR_VALUE");
if (posAttrKey != null && posAttrValue != null) {
_position.addAttribute(posAttrKey, posAttrValue);
}
final long tradeId = rs.getLong("TRADE_ID");
if (_lastTradeId != tradeId && tradeId != 0) {
buildTrade(rs, tradeId);
}
final String tradeIdScheme = rs.getString("TRADE_KEY_SCHEME");
final String tradeIdValue = rs.getString("TRADE_KEY_VALUE");
if (tradeIdScheme != null && tradeIdValue != null) {
if (tradeIdScheme.equals(ObjectId.EXTERNAL_SCHEME.getName())) {
final ObjectId oid = ObjectId.parse(tradeIdValue);
_trade.getSecurityLink().setObjectId(oid);
} else {
final ExternalId id = ExternalId.of(tradeIdScheme, tradeIdValue);
_trade.getSecurityLink().addExternalId(id);
}
}
final String tradeAttrKey = rs.getString("TRADE_ATTR_KEY");
final String tradeAttrValue = rs.getString("TRADE_ATTR_VALUE");
if (tradeAttrKey != null && tradeAttrValue != null) {
_trade.addAttribute(tradeAttrKey, tradeAttrValue);
}
}
return _documents;
}
private void buildPosition(final ResultSet rs, final long positionId) throws SQLException {
final long positionOid = rs.getLong("POSITION_OID");
final BigDecimal quantity = extractBigDecimal(rs, "POS_QUANTITY");
final Timestamp versionFrom = rs.getTimestamp("VER_FROM_INSTANT");
final Timestamp versionTo = rs.getTimestamp("VER_TO_INSTANT");
final Timestamp correctionFrom = rs.getTimestamp("CORR_FROM_INSTANT");
final Timestamp correctionTo = rs.getTimestamp("CORR_TO_INSTANT");
final String providerScheme = rs.getString("POS_PROVIDER_SCHEME");
final String providerValue = rs.getString("POS_PROVIDER_VALUE");
_position = new ManageablePosition(quantity, ExternalIdBundle.EMPTY);
_position.setUniqueId(createUniqueId(positionOid, positionId));
if (providerScheme != null && providerValue != null) {
_position.setProviderId(ExternalId.of(providerScheme, providerValue));
}
final PositionDocument doc = new PositionDocument(_position);
doc.setVersionFromInstant(DbDateUtils.fromSqlTimestamp(versionFrom));
doc.setVersionToInstant(DbDateUtils.fromSqlTimestampNullFarFuture(versionTo));
doc.setCorrectionFromInstant(DbDateUtils.fromSqlTimestamp(correctionFrom));
doc.setCorrectionToInstant(DbDateUtils.fromSqlTimestampNullFarFuture(correctionTo));
doc.setUniqueId(createUniqueId(positionOid, positionId));
_documents.add(doc);
}
private void buildTrade(final ResultSet rs, final long tradeId) throws SQLException {
_lastTradeId = tradeId;
final long tradeOid = rs.getLong("TRADE_OID");
final BigDecimal tradeQuantity = extractBigDecimal(rs, "TRADE_QUANTITY");
final LocalDate tradeDate = DbDateUtils.fromSqlDate(rs.getDate("TRADE_DATE"));
final LocalTime tradeTime = rs.getTimestamp("TRADE_TIME") != null ? DbDateUtils.fromSqlTime(rs.getTimestamp("TRADE_TIME")) : null;
final int zoneOffset = rs.getInt("ZONE_OFFSET");
final String cpartyScheme = rs.getString("CPARTY_SCHEME");
final String cpartyValue = rs.getString("CPARTY_VALUE");
final String providerScheme = rs.getString("TRADE_PROVIDER_SCHEME");
final String providerValue = rs.getString("TRADE_PROVIDER_VALUE");
OffsetTime tradeOffsetTime = null;
if (tradeTime != null) {
tradeOffsetTime = OffsetTime.of(tradeTime, ZoneOffset.ofTotalSeconds(zoneOffset));
}
ExternalId counterpartyId = null;
if (cpartyScheme != null && cpartyValue != null) {
counterpartyId = ExternalId.of(cpartyScheme, cpartyValue);
}
_trade = new ManageableTrade(tradeQuantity, ExternalIdBundle.EMPTY, tradeDate, tradeOffsetTime, counterpartyId);
_trade.setUniqueId(createUniqueId(tradeOid, tradeId));
if (providerScheme != null && providerValue != null) {
_trade.setProviderId(ExternalId.of(providerScheme, providerValue));
}
// different databases return different types, notably BigDecimal and Double
final Object premiumValue = rs.getObject("PREMIUM_VALUE");
if (premiumValue != null) {
_trade.setPremium(rs.getDouble("PREMIUM_VALUE"));
}
final String currencyCode = rs.getString("PREMIUM_CURRENCY");
if (currencyCode != null) {
_trade.setPremiumCurrency(Currency.of(currencyCode));
}
final Date premiumDate = rs.getDate("PREMIUM_DATE");
if (premiumDate != null) {
_trade.setPremiumDate(DbDateUtils.fromSqlDate(premiumDate));
}
_trade.setParentPositionId(_position.getUniqueId());
final LocalTime premiumTime = rs.getTimestamp("PREMIUM_TIME") != null ? DbDateUtils.fromSqlTime(rs.getTimestamp("PREMIUM_TIME")) : null;
final int premiumZoneOffset = rs.getInt("PREMIUM_ZONE_OFFSET");
if (premiumTime != null) {
_trade.setPremiumTime(OffsetTime.of(premiumTime, ZoneOffset.ofTotalSeconds(premiumZoneOffset)));
}
_position.getTrades().add(_trade);
}
}
}
| PLAT-4609 - Oracle DB - Fixup from PR
| projects/OG-MasterDB/src/main/java/com/opengamma/masterdb/position/DbPositionMaster.java | PLAT-4609 - Oracle DB - Fixup from PR | <ide><path>rojects/OG-MasterDB/src/main/java/com/opengamma/masterdb/position/DbPositionMaster.java
<ide> _trade.setProviderId(ExternalId.of(providerScheme, providerValue));
<ide> }
<ide> // different databases return different types, notably BigDecimal and Double
<add> // note that getObject(key, Double.class) does not seem to work
<ide> final Object premiumValue = rs.getObject("PREMIUM_VALUE");
<ide> if (premiumValue != null) {
<ide> _trade.setPremium(rs.getDouble("PREMIUM_VALUE")); |
|
Java | mit | 54f5e3b52a774bf9c69df300d4e4a6aa7bd0035d | 0 | jakobehmsen/duro | package duro.reflang;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.util.stream.Collectors;
import org.antlr.v4.runtime.ANTLRErrorListener;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.RuleNode;
import org.antlr.v4.runtime.tree.TerminalNode;
import duro.debugging.Debug;
import duro.reflang.antlr4.DuroBaseListener;
import duro.reflang.antlr4.DuroLexer;
import duro.reflang.antlr4.DuroListener;
import duro.reflang.antlr4.DuroParser;
import duro.reflang.antlr4.DuroParser.ArgumentParameterContext;
import duro.reflang.antlr4.DuroParser.ArrayContext;
import duro.reflang.antlr4.DuroParser.ArrayOperandContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionArithmetic1ApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionArithmetic2ApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionEqualityApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionEqualityContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionGreaterLessApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionGreaterLessContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionLogicalAndApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionLogicalAndContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionLogicalOrApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionLogicalOrContext;
import duro.reflang.antlr4.DuroParser.BoolContext;
import duro.reflang.antlr4.DuroParser.BreakStatementContext;
import duro.reflang.antlr4.DuroParser.ClosureBodyContext;
import duro.reflang.antlr4.DuroParser.ClosureLiteralContext;
import duro.reflang.antlr4.DuroParser.ConditionalExpressionConditionContext;
import duro.reflang.antlr4.DuroParser.ConditionalExpressionContext;
import duro.reflang.antlr4.DuroParser.ConditionalExpressionFalseContext;
import duro.reflang.antlr4.DuroParser.ConditionalExpressionTrueContext;
import duro.reflang.antlr4.DuroParser.DictProcessContext;
import duro.reflang.antlr4.DuroParser.DictProcessEntryContext;
import duro.reflang.antlr4.DuroParser.ElseStatementContext;
import duro.reflang.antlr4.DuroParser.ExplicitMessageExchangeContext;
import duro.reflang.antlr4.DuroParser.ForInStatementBodyContext;
import duro.reflang.antlr4.DuroParser.ForInStatementContext;
import duro.reflang.antlr4.DuroParser.ForInStatementVarContext;
import duro.reflang.antlr4.DuroParser.ForStatementBodyContext;
import duro.reflang.antlr4.DuroParser.ForStatementConditionContext;
import duro.reflang.antlr4.DuroParser.ForStatementContext;
import duro.reflang.antlr4.DuroParser.ForStatementUpdateContext;
import duro.reflang.antlr4.DuroParser.FrameContext;
import duro.reflang.antlr4.DuroParser.FunctionBodyContext;
import duro.reflang.antlr4.DuroParser.FunctionDefinitionContext;
import duro.reflang.antlr4.DuroParser.FunctionLiteralContext;
import duro.reflang.antlr4.DuroParser.IfStatementConditionContext;
import duro.reflang.antlr4.DuroParser.IfStatementOnTrueContext;
import duro.reflang.antlr4.DuroParser.IndexAccessContext;
import duro.reflang.antlr4.DuroParser.IndexAssignmentContext;
import duro.reflang.antlr4.DuroParser.IndexAssignmentKeyContext;
import duro.reflang.antlr4.DuroParser.IntegerContext;
import duro.reflang.antlr4.DuroParser.InterfaceIdContext;
import duro.reflang.antlr4.DuroParser.LookupContext;
import duro.reflang.antlr4.DuroParser.MemberAccessContext;
import duro.reflang.antlr4.DuroParser.MemberAssignmentContext;
import duro.reflang.antlr4.DuroParser.NilContext;
import duro.reflang.antlr4.DuroParser.PauseContext;
import duro.reflang.antlr4.DuroParser.PrimitiveContext;
import duro.reflang.antlr4.DuroParser.PrimitiveOperand2Context;
import duro.reflang.antlr4.DuroParser.ProgramContext;
import duro.reflang.antlr4.DuroParser.ProgramElementContext;
import duro.reflang.antlr4.DuroParser.ProgramElementsContext;
import duro.reflang.antlr4.DuroParser.ProgramElementsPartContext;
import duro.reflang.antlr4.DuroParser.ReturnStatementContext;
import duro.reflang.antlr4.DuroParser.SelfContext;
import duro.reflang.antlr4.DuroParser.StringContext;
import duro.reflang.antlr4.DuroParser.ThisMessageExchangeContext;
import duro.reflang.antlr4.DuroParser.TopExpressionContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionNotApplicationContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionPostIncDecApplicationContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionPostIncDecApplicationIndexAccessReceiverContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionPostIncDecApplicationMemberAccessContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionPostIncDecApplicationVariableContext;
import duro.reflang.antlr4.DuroParser.VariableAssignmentContext;
import duro.reflang.antlr4.DuroParser.VariableDeclarationAndAssignmentContext;
import duro.reflang.antlr4.DuroParser.VariableDeclarationContext;
import duro.reflang.antlr4.DuroParser.WhileStatementBodyContext;
import duro.reflang.antlr4.DuroParser.WhileStatementConditionContext;
import duro.reflang.antlr4.DuroParser.WhileStatementContext;
import duro.reflang.antlr4.DuroParser.YieldStatementContext;
import duro.reflang.antlr4.DuroParser.YieldStatementExpressionContext;
import duro.runtime.CustomProcess;
import duro.runtime.Instruction;
public class Compiler {
private MessageCollector errors = new MessageCollector();
private void appendError(ParserRuleContext ctx, String message) {
errors.appendMessage(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine(), message);
}
private void appendError(int line, int charPositionInLine, String message) {
errors.appendMessage(line, charPositionInLine, message);
}
private void appendErrors(MessageCollector errors) {
this.errors.appendMessages(errors);
}
public boolean hasErrors() {
return errors.hasMessages();
}
public void printErrors() {
errors.printMessages();
}
public CustomProcess compile(InputStream sourceCode) throws IOException {
CharStream charStream = new ANTLRInputStream(sourceCode);
DuroLexer lexer = new DuroLexer(charStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
DuroParser parser = new DuroParser(tokenStream);
parser.removeErrorListeners();
parser.addErrorListener(new ANTLRErrorListener() {
@Override
public void syntaxError(Recognizer<?,?> recognizer, java.lang.Object offendingSymbol, int line, int charPositionInLine, java.lang.String msg, RecognitionException e) {
appendError(line, charPositionInLine, msg);
}
@Override
public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs) {
new String();
}
@Override
public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, java.util.BitSet conflictingAlts, ATNConfigSet configs) {
new String();
}
@Override
public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact, java.util.BitSet ambigAlts, ATNConfigSet configs) {
new String();
}
});
Debug.println(Debug.LEVEL_HIGH, "Parsing program...");
ProgramContext programCtx;
// Parsing approach following https://theantlrguy.atlassian.net/wiki/pages/viewpage.action?pageId=1900591
parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
try {
programCtx = parser.program(); // STAGE 1
}
catch (Exception ex) {
tokenStream.reset(); // rewind input stream
parser.reset();
parser.getInterpreter().setPredictionMode(PredictionMode.LL);
programCtx = parser.program(); // STAGE 2
// if we parse ok, it's LL not SLL
}
Debug.println(Debug.LEVEL_HIGH, "Parsed program.");
OrdinalAllocator idToParameterOrdinalMap = new OrdinalAllocator();
OrdinalAllocator idToVariableOrdinalMap = new OrdinalAllocator();
Debug.println(Debug.LEVEL_HIGH, "Generating program...");
BodyInfo bodyInfo = getBodyInfo(idToParameterOrdinalMap, idToVariableOrdinalMap, programCtx);
Debug.println(Debug.LEVEL_HIGH, "Generated program.");
return new CustomProcess(idToParameterOrdinalMap.size(), bodyInfo.localCount, bodyInfo.instructions.toArray(new Instruction[bodyInfo.instructions.size()]));
}
private static class ConditionalTreeWalker extends ParseTreeWalker {
private boolean suspendWalk;
private RuleNode ruleSuspendedAt;
@Override
protected void enterRule(ParseTreeListener listener, RuleNode r) {
if(!suspendWalk)
super.enterRule(listener, r);
}
@Override
protected void exitRule(ParseTreeListener listener, RuleNode r) {
if(ruleSuspendedAt == r)
suspendWalk = false;
if(!suspendWalk)
super.exitRule(listener, r);
}
public void suspendWalkWithin(RuleNode r) {
suspendWalk = true;
ruleSuspendedAt = r;
}
}
private DuroListener createBodyListener(
final ConditionalTreeWalker walker, OrdinalAllocator idToParameterOrdinalMap, OrdinalAllocator idToVariableOrdinalMapArg,
final ArrayList<Instruction> instructions, final ArrayList<YieldStatementContext> yieldStatements) {
return new DuroBaseListener() {
OrdinalAllocator idToVariableOrdinalMap = idToVariableOrdinalMapArg;
@Override
public void exitProgram(ProgramContext ctx) {
// Add finish instruction to the end
instructions.add(new Instruction(Instruction.OPCODE_FINISH));
}
Stack<Integer> conditionalConditionalJumpIndexesStack = new Stack<Integer>();
Stack<Integer> conditionalJumpIndexStack = new Stack<Integer>();
@Override
public void enterConditionalExpression(ConditionalExpressionContext ctx) {
}
@Override
public void exitConditionalExpressionCondition(ConditionalExpressionConditionContext ctx) {
// [<bool>]
instructions.add(new Instruction(Instruction.OPCODE_DUP));
int conditionalJumpIndex = instructions.size();
instructions.add(null); // If false, jump to else expression
conditionalConditionalJumpIndexesStack.add(conditionalJumpIndex);
}
@Override
public void exitConditionalExpressionTrue(ConditionalExpressionTrueContext ctx) {
int jumpIndex = instructions.size();
conditionalJumpIndexStack.push(jumpIndex);
instructions.add(null); // Jump to the end of the conditional expression
int trueEndIndex = instructions.size();
int conditionalConditionalJumpIndex = conditionalConditionalJumpIndexesStack.pop();
int conditionalJump = trueEndIndex - conditionalConditionalJumpIndex;
instructions.set(conditionalConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
}
@Override
public void exitConditionalExpressionFalse(ConditionalExpressionFalseContext ctx) {
int jumpIndex = conditionalJumpIndexStack.pop();
int jump = instructions.size() - jumpIndex;
instructions.set(jumpIndex, new Instruction(Instruction.OPCODE_JUMP, jump));
}
@Override
public void exitConditionalExpression(ConditionalExpressionContext ctx) {
}
Stack<ArrayList<Integer>> orConditionalJumpIndexesStack = new Stack<ArrayList<Integer>>();
@Override
public void enterBinaryExpressionLogicalOr(BinaryExpressionLogicalOrContext ctx) {
orConditionalJumpIndexesStack.push(new ArrayList<Integer>());
}
@Override
public void enterBinaryExpressionLogicalOrApplication(BinaryExpressionLogicalOrApplicationContext ctx) {
ArrayList<Integer> orConditionalJumpIndexes = orConditionalJumpIndexesStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
int conditionalJumpIndex = instructions.size();
instructions.add(null);
orConditionalJumpIndexes.add(conditionalJumpIndex);
}
@Override
public void exitBinaryExpressionLogicalOrApplication(BinaryExpressionLogicalOrApplicationContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SP_BOOLEAN_OR));
}
@Override
public void exitBinaryExpressionLogicalOr(BinaryExpressionLogicalOrContext ctx) {
int orEndIndex = instructions.size();
ArrayList<Integer> orConditionalJumpIndexes = orConditionalJumpIndexesStack.pop();
for(int orConditionalJumpIndex: orConditionalJumpIndexes) {
int conditionalJump = orEndIndex - orConditionalJumpIndex;
// If true, skip the rest
instructions.set(orConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_TRUE, conditionalJump));
}
}
Stack<ArrayList<Integer>> andConditionalJumpIndexesStack = new Stack<ArrayList<Integer>>();
@Override
public void enterBinaryExpressionLogicalAnd(BinaryExpressionLogicalAndContext ctx) {
andConditionalJumpIndexesStack.push(new ArrayList<Integer>());
}
@Override
public void enterBinaryExpressionLogicalAndApplication(BinaryExpressionLogicalAndApplicationContext ctx) {
ArrayList<Integer> andConditionalJumpIndexes = andConditionalJumpIndexesStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
int conditionalJumpIndex = instructions.size();
instructions.add(null);
andConditionalJumpIndexes.add(conditionalJumpIndex);
}
@Override
public void exitBinaryExpressionLogicalAndApplication(BinaryExpressionLogicalAndApplicationContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SP_BOOLEAN_AND));
}
@Override
public void exitBinaryExpressionLogicalAnd(BinaryExpressionLogicalAndContext ctx) {
int andEndIndex = instructions.size();
ArrayList<Integer> andConditionalJumpIndexes = andConditionalJumpIndexesStack.pop();
for(int andConditionalJumpIndex: andConditionalJumpIndexes) {
int conditionalJump = andEndIndex - andConditionalJumpIndex;
// If false, skip the rest
instructions.set(andConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
}
}
Stack<ArrayList<Integer>> equalsConditionalJumpIndexesStack = new Stack<ArrayList<Integer>>();
@Override
public void enterBinaryExpressionEquality(BinaryExpressionEqualityContext ctx) {
equalsConditionalJumpIndexesStack.add(new ArrayList<Integer>());
}
@Override
public void exitBinaryExpressionEqualityApplication(BinaryExpressionEqualityApplicationContext ctx) {
ArrayList<Integer> equalsConditionalJumpIndexes = equalsConditionalJumpIndexesStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
instructions.add(new Instruction(Instruction.OPCODE_SWAP1));
String operatorId = ctx.op.getText();
instructions.add(new Instruction(Instruction.OPCODE_SEND, operatorId, 1));
int conditionalJumpIndex = instructions.size();
instructions.add(null);
equalsConditionalJumpIndexes.add(conditionalJumpIndex);
}
@Override
public void exitBinaryExpressionEquality(BinaryExpressionEqualityContext ctx) {
ArrayList<Integer> equalsConditionalJumpIndexes = equalsConditionalJumpIndexesStack.pop();
if(equalsConditionalJumpIndexes.size() > 0) {
// If there were any applications
instructions.add(new Instruction(Instruction.OPCODE_LOAD_TRUE));
instructions.add(new Instruction(Instruction.OPCODE_JUMP, 2));
int equalsEndIndex = instructions.size();
for(int equalsConditionalJumpIndex: equalsConditionalJumpIndexes) {
int conditionalJump = equalsEndIndex - equalsConditionalJumpIndex;
// If false, skip the rest
instructions.set(equalsConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
}
instructions.add(new Instruction(Instruction.OPCODE_LOAD_FALSE));
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
instructions.add(new Instruction(Instruction.OPCODE_POP));
}
}
Stack<ArrayList<Integer>> greaterLessConditionalJumpIndexesStack = new Stack<ArrayList<Integer>>();
Stack<Integer> greaterLessOperandCountStack = new Stack<Integer>();
@Override
public void enterBinaryExpressionGreaterLess(BinaryExpressionGreaterLessContext ctx) {
int operandCount = ctx.binaryExpressionGreaterLessApplication().size() + 1;
greaterLessOperandCountStack.push(operandCount);
if(operandCount > 2) {
greaterLessConditionalJumpIndexesStack.add(new ArrayList<Integer>());
}
}
@Override
public void exitBinaryExpressionGreaterLessApplication(BinaryExpressionGreaterLessApplicationContext ctx) {
int operandCount = greaterLessOperandCountStack.peek();
if(operandCount > 2) {
ArrayList<Integer> greaterLessConditionalJumpIndexes = greaterLessConditionalJumpIndexesStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
instructions.add(new Instruction(Instruction.OPCODE_SWAP1));
appendGreaterLessOperator(ctx);
int conditionalJumpIndex = instructions.size();
instructions.add(null);
greaterLessConditionalJumpIndexes.add(conditionalJumpIndex);
} else if(operandCount == 2){
appendGreaterLessOperator(ctx);
}
}
private void appendGreaterLessOperator(BinaryExpressionGreaterLessApplicationContext ctx) {
String operator = ctx.op.getText();
instructions.add(new Instruction(Instruction.OPCODE_SEND, operator, 1));
}
@Override
public void exitBinaryExpressionGreaterLess(BinaryExpressionGreaterLessContext ctx) {
int operandCount = greaterLessOperandCountStack.pop();
if(operandCount > 2) {
ArrayList<Integer> greaterLessConditionalJumpIndexes = greaterLessConditionalJumpIndexesStack.pop();
if(greaterLessConditionalJumpIndexes.size() > 0) {
// If there were any applications
instructions.add(new Instruction(Instruction.OPCODE_LOAD_TRUE));
instructions.add(new Instruction(Instruction.OPCODE_JUMP, 2));
int equalsEndIndex = instructions.size();
for(int greaterLessConditionalJumpIndex: greaterLessConditionalJumpIndexes) {
int conditionalJump = equalsEndIndex - greaterLessConditionalJumpIndex;
// If false, skip the rest
instructions.set(greaterLessConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
}
instructions.add(new Instruction(Instruction.OPCODE_LOAD_FALSE));
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
instructions.add(new Instruction(Instruction.OPCODE_POP));
}
}
}
@Override
public void exitBinaryExpressionArithmetic1Application(BinaryExpressionArithmetic1ApplicationContext ctx) {
String id = ctx.BIN_OP1().getText();
instructions.add(new Instruction(Instruction.OPCODE_SEND, id, 1));
}
@Override
public void exitBinaryExpressionArithmetic2Application(BinaryExpressionArithmetic2ApplicationContext ctx) {
String id = ctx.BIN_OP2().getText();
instructions.add(new Instruction(Instruction.OPCODE_SEND, id, 1));
}
@Override
public void exitUnaryExpressionNotApplication(UnaryExpressionNotApplicationContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SP_BOOLEAN_NOT));
}
@Override
public void exitUnaryExpressionPostIncDecApplicationIndexAccessReceiver(UnaryExpressionPostIncDecApplicationIndexAccessReceiverContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Dup receiver
}
@Override
public void exitUnaryExpressionPostIncDecApplication(UnaryExpressionPostIncDecApplicationContext ctx) {
ParserRuleContext targetCtx = (ParserRuleContext)ctx.getChild(0);
switch(targetCtx.getRuleIndex()) {
case DuroParser.RULE_unaryExpressionPostIncDecApplicationVariable: {
// Either variable assignment or member assignment
String id = ((UnaryExpressionPostIncDecApplicationVariableContext)targetCtx).ID().getText();;
if(idToVariableOrdinalMap.isDeclared(id))
appendUnaryExpressionPostIncDecApplicationVariable(ctx, targetCtx);
else {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
// receiver
appendUnaryExpressionPostIncDecApplicationMemberAccess(ctx, id);
}
break;
} case DuroParser.RULE_unaryExpressionPostIncDecApplicationMemberAccess: {
String id = ((UnaryExpressionPostIncDecApplicationMemberAccessContext)targetCtx).ID().getText();
appendUnaryExpressionPostIncDecApplicationMemberAccess(ctx, id);
break;
} case DuroParser.RULE_unaryExpressionPostIncDecApplicationIndexAccess:
// receiver, receiver, id
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// receiver, id, receiver, id
instructions.add(new Instruction(Instruction.OPCODE_SEND, "get", 1));
// receiver, id, value
instructions.add(new Instruction(Instruction.OPCODE_DUP2));
// value, receiver, id, value,
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, 1));
// value, receiver, id, value, 1
appendIncDec(ctx.op);
// value, receiver, id, value'
instructions.add(new Instruction(Instruction.OPCODE_SEND, "set", 2));
instructions.add(new Instruction(Instruction.OPCODE_POP));
break;
}
}
private void appendUnaryExpressionPostIncDecApplicationVariable(UnaryExpressionPostIncDecApplicationContext ctx, ParserRuleContext targetCtx) {
String id = ((UnaryExpressionPostIncDecApplicationVariableContext)targetCtx).ID().getText();
int ordinal = idToVariableOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_LOAD_LOC, ordinal));
instructions.add(new Instruction(Instruction.OPCODE_DUP));
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, 1));
appendIncDec(ctx.op);
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, ordinal));
}
private void appendUnaryExpressionPostIncDecApplicationMemberAccess(UnaryExpressionPostIncDecApplicationContext ctx, String id) {
// receiver
instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Dup receiver
// receiver, receiver
instructions.add(new Instruction(Instruction.OPCODE_GET, id));
// receiver, value
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// value, receiver, value
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, 1));
// value, receiver, value, 1
appendIncDec(ctx.op);
// value, receiver, value'
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
// value
}
private void appendIncDec(Token opToken) {
switch(opToken.getType()) {
case DuroLexer.DOUBLE_PLUS:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "+", 1));
break;
case DuroLexer.DOUBLE_MINUS:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "-", 1));
break;
}
}
@Override
public void enterVariableAssignment(VariableAssignmentContext ctx) {
String firstId = ctx.ID(0).getText();
if(idToVariableOrdinalMap.isDeclared(firstId)) {
// Variable assignment
int firstOrdinal = idToVariableOrdinalMap.ordinalFor(firstId);
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN: {
break;
} default: {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_LOC, firstOrdinal));
// oldValue
break;
}
}
} else {
// Member assignment for this
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN: {
break;
} default: {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
instructions.add(new Instruction(Instruction.OPCODE_GET, firstId));
// oldValue
break;
}
}
}
}
@Override
public void exitVariableAssignment(VariableAssignmentContext ctx) {
String firstId = ctx.ID(0).getText();
if(idToVariableOrdinalMap.isDeclared(firstId)) {
int firstOrdinal = idToVariableOrdinalMap.ordinalFor(firstId);
// Variable assignment
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN: {
instructions.add(new Instruction(Instruction.OPCODE_DUP_ANY, 0, ctx.ID().size() - 1));
for(int i = 0; i < ctx.ID().size(); i++) {
String id = ctx.ID(i).getText();
int ordinal = idToVariableOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, ordinal));
}
break;
} default: {
// Multiple returns values are not supported here yet.
// oldValue, newValuePart
appendAssignmentReducer(ctx.op);
// newValue
instructions.add(new Instruction(Instruction.OPCODE_DUP));
// newValue, newValue
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, firstOrdinal));
// newValue
break;
}
}
} else {
// Member assignment for this
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN: {
instructions.add(new Instruction(Instruction.OPCODE_DUP_ANY, 0, ctx.ID().size() - 1));
for(int i = 0; i < ctx.ID().size(); i++) {
String id = ctx.ID(i).getText();
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
}
break;
} default: {
// Multiple returns values are not supported here yet.
// oldValue, newValuePart
appendAssignmentReducer(ctx.op);
// newValue
instructions.add(new Instruction(Instruction.OPCODE_DUP));
// newValue, newValue
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
// newValue, newValue, receiver
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
// newValue, receiver, newValue
instructions.add(new Instruction(Instruction.OPCODE_SET, firstId));
// newValue
break;
}
}
}
}
private void appendAssignmentReducer(Token op) {
switch(op.getType()) {
case DuroLexer.ASSIGN_ADD:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "+", 1));
break;
case DuroLexer.ASSIGN_SUB:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "-", 1));
break;
case DuroLexer.ASSIGN_MULT:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "*", 1));
break;
case DuroLexer.ASSIGN_DIV:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "/", 1));
break;
case DuroLexer.ASSIGN_REM:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "%", 1));
break;
}
}
@Override
public void enterLookup(LookupContext ctx) {
String id = ctx.ID().getText();
Integer parameterOrdinal = idToParameterOrdinalMap.ordinalFor(id);
if(parameterOrdinal != null) {
// Load argument
instructions.add(new Instruction(Instruction.OPCODE_LOAD_ARG, parameterOrdinal));
return;
}
Integer variableOrdinal = idToVariableOrdinalMap.ordinalFor(id);
if(variableOrdinal != null) {
// Load variable
instructions.add(new Instruction(Instruction.OPCODE_LOAD_LOC, variableOrdinal));
return;
}
// Get member
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
instructions.add(new Instruction(Instruction.OPCODE_GET, id));
}
@Override
public void enterArgumentParameter(ArgumentParameterContext ctx) {
int parameterOrdinal = idToParameterOrdinalMap.declare(ctx.ID().getText());
instructions.add(new Instruction(Instruction.OPCODE_LOAD_ARG, parameterOrdinal));
}
@Override
public void enterThisMessageExchange(ThisMessageExchangeContext ctx) {
String id = ctx.messageExchange().messageId().getText();
if(idToParameterOrdinalMap.isDeclared(id)) {
// Call argument
int ordinal = idToParameterOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_LOAD_ARG, ordinal));
} else if(idToVariableOrdinalMap.isDeclared(id)) {
// Call variable
int ordinal = idToVariableOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_LOAD_LOC, ordinal));
} else {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
}
}
@Override
public void exitThisMessageExchange(ThisMessageExchangeContext ctx) {
int argumentCount = ctx.messageExchange().expression().size();
String id = ctx.messageExchange().messageId().getText();
if(idToParameterOrdinalMap.isDeclared(id)) {
// Call argument
instructions.add(new Instruction(Instruction.OPCODE_CALL, argumentCount));
} else if(idToVariableOrdinalMap.isDeclared(id)) {
// Call variable
instructions.add(new Instruction(Instruction.OPCODE_CALL, argumentCount));
} else {
appendMessageExchange(id, argumentCount);
}
}
private void appendMessageExchange(String id, int argumentCount) {
// Currently: just resolve function and then call it.
instructions.add(new Instruction(Instruction.OPCODE_SEND, id, argumentCount));
}
@Override
public void enterInteger(IntegerContext ctx) {
int value = Integer.parseInt(ctx.INT().getText());
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, value));
}
@Override
public void enterBool(BoolContext ctx) {
boolean value = Boolean.parseBoolean(ctx.getText());
if(value)
instructions.add(new Instruction(Instruction.OPCODE_LOAD_TRUE, value));
else
instructions.add(new Instruction(Instruction.OPCODE_LOAD_FALSE, value));
}
@Override
public void enterString(StringContext ctx) {
String rawString = ctx.getText();
// Should the string enter properly prepared?
// - i.e., no need for filtering the string.
String string = extractStringLiteral(rawString);
instructions.add(new Instruction(Instruction.OPCODE_LOAD_STRING, string));
}
@Override
public void enterDictProcess(DictProcessContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_DICT));
}
@Override
public void enterDictProcessEntry(DictProcessEntryContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_DUP));
}
@Override
public void exitDictProcessEntry(DictProcessEntryContext ctx) {
String id = ctx.messageId().getText();
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
}
@Override
public void enterFunctionLiteral(FunctionLiteralContext ctx) {
walker.suspendWalkWithin(ctx);
}
@Override
public void exitFunctionLiteral(FunctionLiteralContext ctx) {
OrdinalAllocator newIdToParameterOrdinalMap = new OrdinalAllocator();
OrdinalAllocator newIdToVariableOrdinalMap = new OrdinalAllocator();
for(TerminalNode parameterIdNode: ctx.functionParameters().ID()) {
String parameterId = parameterIdNode.getText();
newIdToParameterOrdinalMap.declare(parameterId);
}
BodyInfo functionBodyInfo = getBodyInfo(newIdToParameterOrdinalMap, newIdToVariableOrdinalMap, ctx.functionBody());
int parameterCount = newIdToParameterOrdinalMap.size();
Instruction[] bodyInstructions = functionBodyInfo.instructions.toArray(new Instruction[functionBodyInfo.instructions.size()]);
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, functionBodyInfo.localCount, bodyInstructions)); // Should this create a function process?
}
@Override
public void enterClosureLiteral(ClosureLiteralContext ctx) {
// TODO: Instead of this, there could be a stack of instructions, where it is the top instructions that are manipulated
// In exit body, the instructions stack can be popped
walker.suspendWalkWithin(ctx);
}
@Override
public void exitClosureBody(ClosureBodyContext ctx) {
if(instructions.size() > 0) {
if(instructions.get(instructions.size() - 1).opcode == Instruction.OPCODE_POP) {
// Replace pop with return
instructions.set(instructions.size() - 1, new Instruction(Instruction.OPCODE_RET, 1));
} else if(!Instruction.isReturn(instructions.get(instructions.size() - 1).opcode)) {
// If the last program elements isn't an expression, e.g. a for statement
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
}
} else {
if(yieldStatements.size() > 0) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
} else {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
}
}
}
@Override
public void exitClosureLiteral(ClosureLiteralContext ctx) {
OrdinalAllocator newIdToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
OrdinalAllocator newIdToParameterOrdinalMap = idToParameterOrdinalMap.newInner();
for(TerminalNode parameterIdNode: ctx.closureParameters().ID()) {
String parameterId = parameterIdNode.getText();
newIdToParameterOrdinalMap.declare(parameterId);
}
BodyInfo functionBodyInfo = getBodyInfo(newIdToParameterOrdinalMap, newIdToVariableOrdinalMap, ctx.closureBody());
// int[] ordinals = newIdToParameterOrdinalMap.getOrdinals();
int parameterCount = newIdToParameterOrdinalMap.size();
int closureParameterOffset = newIdToParameterOrdinalMap.getLocalParameterOffset();
int closureParameterCount = newIdToParameterOrdinalMap.getLocalParameterCount();
Instruction[] bodyInstructions = functionBodyInfo.instructions.toArray(new Instruction[functionBodyInfo.instructions.size()]);
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, functionBodyInfo.localCount, bodyInstructions));
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_CLOSURE, closureParameterOffset, closureParameterCount));
// [closure]
}
Stack<Integer> arrayOperandNumberStack = new Stack<Integer>();
@Override
public void enterArray(ArrayContext ctx) {
int length = ctx.arrayOperand().size();
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, length));
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_ARRAY));
arrayOperandNumberStack.push(0);
}
@Override
public void enterArrayOperand(ArrayOperandContext ctx) {
int arrayOperandNumber = arrayOperandNumberStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, arrayOperandNumber));
arrayOperandNumberStack.set(arrayOperandNumberStack.size() - 1, arrayOperandNumber + 1);
}
@Override
public void exitArrayOperand(ArrayOperandContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SEND, "set", 2));
instructions.add(new Instruction(Instruction.OPCODE_POP));
}
@Override
public void exitArray(ArrayContext ctx) {
arrayOperandNumberStack.pop();
}
@Override
public void enterSelf(SelfContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
}
@Override
public void enterNil(NilContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
}
@Override
public void enterFrame(FrameContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS_FRAME));
}
@Override
public void enterPrimitiveOperand2(PrimitiveOperand2Context ctx) {
walker.suspendWalkWithin(ctx);
}
@Override
public void exitPrimitiveOperand2(PrimitiveOperand2Context ctx) {
super.exitPrimitiveOperand2(ctx);
}
@Override
public void exitPrimitive(PrimitiveContext ctx) {
MessageCollector errors = new MessageCollector();
String opcodeId = ctx.ID().getText();
Integer opcode = Instruction.getOpcodeFromId(opcodeId);
Object[] operands = new Object[Math.max(ctx.primitiveOperand2().size(), 3)];
if(opcode != null) {
if(Instruction.isExpressionCompatible(opcode)) {
Class<?>[] expectedOperandTypes = Instruction.getOperandTypes(opcode);
Class<?>[] actualOperandTypes = new Class<?>[ctx.primitiveOperand2().size()];
for(int i = 0; i < ctx.primitiveOperand2().size(); i++) {
operands[i] = getLiteral(ctx.primitiveOperand2().get(i));
actualOperandTypes[i] = operands[i].getClass();
}
if(!Arrays.equals(expectedOperandTypes, actualOperandTypes)) {
int givenOperandCount = ctx.primitiveOperand2().size();
String givenOperandsStr = givenOperandCount > 0
? noun(givenOperandCount, "Operand") + " " + operandsToString(operands, givenOperandCount)
: "No operands";
String expectedOperandsStr = expectedOperandTypes.length > 0
? "operand sequence " + literalTypesToString(expectedOperandTypes) + " was"
: "no operands where";
errors.appendMessage(ctx,
givenOperandsStr + " " + wasWhere(givenOperandCount) +
" given when " + expectedOperandsStr + " expected for opcode '" + opcodeId + "'.");
}
if(ctx.primitiveArgument().size() != Instruction.getPopCount(opcode)) {
String was1 = nounWasWhere(ctx.primitiveArgument().size(), "argument");
String was2 = nounWasWhere(Instruction.getPopCount(opcode), "argument");
errors.appendMessage(ctx,
ctx.primitiveArgument().size() + " " + was1 + " given when " +
Instruction.getPopCount(opcode) + " " + was2 +
" expected for opcode '" + opcodeId + "'.");
}
} else {
errors.appendMessage(ctx, "Opcode '" + opcodeId + "' not compatible with expressions");
}
} else {
errors.appendMessage(ctx, "Invalid opcode '" + opcodeId + "'.");
}
if(!errors.hasMessages()) {
instructions.add(new Instruction(opcode, operands[0], operands[1], operands[2]));
if(!Instruction.doesReturn(opcode)) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
}
}
appendErrors(errors);
}
private String nounWasWhere(int count, String noun) {
return count == 1 ? noun + " was" : noun + "s where";
}
private String noun(int count, String noun) {
return count == 1 ? noun : noun + "s";
}
private String wasWhere(int count) {
return count == 1 ? "was" : "where";
}
private String operandsToString(Object[] operands, int count) {
if(operands.length > 0) {
return Arrays.asList(operands).stream().limit(count).map(x -> {
return x.getClass().getSimpleName() + "(" + x + ")";
}).collect(Collectors.joining(", "));
}
return "no";
}
private String literalTypesToString(Class<?>[] literalTypes) {
if(literalTypes.length > 0) {
return Arrays.asList(literalTypes).stream().map(x -> {
return x.getSimpleName();
}).collect(Collectors.joining(", ", "(", ")"));
}
return "no";
}
@Override
public void enterPause(PauseContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_PAUSE));
}
@Override
public void exitVariableDeclarationAndAssignment(VariableDeclarationAndAssignmentContext ctx) {
for(TerminalNode idNode: ctx.ID()) {
if(!idToVariableOrdinalMap.isDeclaredLocally(idNode.getText()) && !idToParameterOrdinalMap.isDeclared(idNode.getText())) {
int ordinal = idToVariableOrdinalMap.declare(idNode.getText());
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, ordinal));
} else {
appendError(ctx, "Variable '" + idNode.getText() + "' is already declared in this scope.");
}
}
}
@Override
public void enterVariableDeclaration(VariableDeclarationContext ctx) {
if(!idToVariableOrdinalMap.isDeclaredLocally(ctx.ID().getText()) && !idToParameterOrdinalMap.isDeclared(ctx.ID().getText())) {
idToVariableOrdinalMap.declare(ctx.ID().getText());
} else {
appendError(ctx, "Variable '" + ctx.ID().getText() + "' is already declared in this scope.");
}
}
@Override
public void exitReturnStatement(ReturnStatementContext ctx) {
int returnCount = ctx.expression().size();
instructions.add(new Instruction(Instruction.OPCODE_RET, returnCount));
}
private Stack<ArrayList<Integer>> breakIndexesStack = new Stack<ArrayList<Integer>>();
private void startBreakable() {
breakIndexesStack.push(new ArrayList<Integer>());
}
private void endBreakable() {
ArrayList<Integer> breakIndexes = breakIndexesStack.pop();
for(int breakIndex: breakIndexes)
instructions.set(breakIndex, new Instruction(Instruction.OPCODE_JUMP, instructions.size() - breakIndex));
}
@Override
public void enterBreakStatement(BreakStatementContext ctx) {
ArrayList<Integer> breakIndexes = breakIndexesStack.peek();
breakIndexes.add(instructions.size());
instructions.add(null);
}
@Override
public void enterFunctionDefinition(FunctionDefinitionContext ctx) {
walker.suspendWalkWithin(ctx);
}
@Override
public void exitFunctionDefinition(FunctionDefinitionContext ctx) {
String id = ctx.messageId().getText();
OrdinalAllocator newIdToParameterOrdinalMap = new OrdinalAllocator();
OrdinalAllocator newIdToVariableOrdinalMap = new OrdinalAllocator();
for(TerminalNode parameterIdNode: ctx.functionParameters().ID()) {
String parameterId = parameterIdNode.getText();
newIdToParameterOrdinalMap.declare(parameterId);
}
BodyInfo functionBodyInfo = getBodyInfo(newIdToParameterOrdinalMap, newIdToVariableOrdinalMap, ctx.functionBody());
Instruction[] bodyInstructions = functionBodyInfo.instructions.toArray(new Instruction[functionBodyInfo.instructions.size()]);
int parameterCount = newIdToParameterOrdinalMap.size();
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
// this
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, functionBodyInfo.localCount, bodyInstructions)); // Should this create a function process?
// this, behavior
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// behavior, this, behavior
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
// behavior
}
@Override
public void enterYieldStatementExpression(YieldStatementExpressionContext ctx) {
int generatableOrdinal = idToParameterOrdinalMap.declare("generator");
instructions.add(new Instruction(Instruction.OPCODE_LOAD_ARG, generatableOrdinal));
}
@Override
public void exitYieldStatementExpression(YieldStatementExpressionContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SEND, "put", 1));
}
@Override
public void exitYieldStatement(YieldStatementContext ctx) {
yieldStatements.add(ctx);
}
@Override
public void exitFunctionBody(FunctionBodyContext ctx) {
if(yieldStatements.size() > 0) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
} else if(instructions.size() == 0/* || !Instruction.isReturn(instructions.get(instructions.size() - 1).opcode)*/) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
} else if(!Instruction.isReturn(instructions.get(instructions.size() - 1).opcode)) {
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
}
}
// @Override
// public void enterPrimitiveBody(PrimitiveBodyContext ctx) {
// walker.suspendWalkWithin(ctx);
// }
//
// @Override
// public void exitPrimitiveBody(PrimitiveBodyContext ctx) {
// final Hashtable<String, Integer> labelDefinitionsToIndexMap = new Hashtable<String, Integer>();
// ArrayList<Runnable> labelUsageLinkers = new ArrayList<Runnable>();
//
// for(PrimitiveBodyPartContext primitiveBodyPartCtx: ctx.primitiveBodyPart()) {
// ParserRuleContext part = (ParserRuleContext)primitiveBodyPartCtx.getChild(0);
// switch(part.getRuleIndex()) {
// case DuroParser.RULE_primitiveLabel:
// PrimitiveLabelContext primitiveLabelCtx = (PrimitiveLabelContext)part;
// String label = primitiveLabelCtx.ID().getText();
// int index = instructions.size();
// labelDefinitionsToIndexMap.put(label, index);
// break;
// case DuroParser.RULE_primitiveCall:
// Instruction instruction;
//
// PrimitiveCallContext primitiveCallCtx = (PrimitiveCallContext)part;
// String opcodeId = primitiveCallCtx.ID().getText();
//
// int opcode = Instruction.getOpcodeFromId(opcodeId);
//
// switch(opcode) {
// case Instruction.OPCODE_IF_TRUE:
// case Instruction.OPCODE_IF_FALSE:
// instruction = null;
// final int indexUsage = instructions.size();
// final String jumpLabel = primitiveCallCtx.primitiveOperand().get(0).getText();
// labelUsageLinkers.add(() -> {
// int indexDefinition = labelDefinitionsToIndexMap.get(jumpLabel);
// int jump = indexDefinition - indexUsage;
// instructions.set(indexUsage, new Instruction(opcode, jump));
// });
// break;
// default:
// Object operand1 = null;
// Object operand2 = null;
// Object operand3 = null;
//
// if(primitiveCallCtx.primitiveOperand().size() > 0) {
// operand1 = getLiteral(primitiveCallCtx.primitiveOperand().get(0));
//
// if(primitiveCallCtx.primitiveOperand().size() > 1) {
// operand2 = getLiteral(primitiveCallCtx.primitiveOperand().get(1));
//
// if(primitiveCallCtx.primitiveOperand().size() > 2) {
// operand3 = getLiteral(primitiveCallCtx.primitiveOperand().get(2));
// }
// }
// }
//
// instruction = new Instruction(opcode, operand1, operand2, operand3);
// }
//
// instructions.add(instruction);
// break;
// }
// }
//
// for(Runnable labelUsageLinker: labelUsageLinkers)
// labelUsageLinker.run();
// }
private Stack<Integer> ifConditionalJumpIndexStack = new Stack<Integer>();
private Stack<Integer> ifJumpIndexStack = new Stack<Integer>();
@Override
public void exitIfStatementCondition(IfStatementConditionContext ctx) {
// After condition is generated, then a conditional jump should be generated
// Leave a spot allocated here and write to it later
int conditionalJumpIndex = instructions.size();
ifConditionalJumpIndexStack.push(conditionalJumpIndex);
instructions.add(null);
}
@Override
public void enterIfStatementOnTrue(IfStatementOnTrueContext ctx) {
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
}
@Override
public void exitIfStatementOnTrue(IfStatementOnTrueContext ctx) {
// After statement on true is generated, then a jump should be generated
// Leave a spot allocated here and write to it later
int jumpIndex = instructions.size();
ifJumpIndexStack.push(jumpIndex);
instructions.add(null);
int conditionalJumpIndex = ifConditionalJumpIndexStack.pop();
// Now, the spot allocated for a conditional jump can be populated
int ifEndIndex = instructions.size();
int jump = ifEndIndex - conditionalJumpIndex;
instructions.set(conditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, jump));
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
}
@Override
public void enterElseStatement(ElseStatementContext ctx) {
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
if(ctx.ifStatementOnFalse() == null)
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
}
@Override
public void exitElseStatement(ElseStatementContext ctx) {
int jumpIndex = ifJumpIndexStack.pop();
// Now, the spot allocated for a jump can be populated
int elseEndIndex = instructions.size();
int jump = elseEndIndex - jumpIndex;
instructions.set(jumpIndex, new Instruction(Instruction.OPCODE_JUMP, jump));
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
}
private Stack<Integer> whileConditionalJumpIndexStack = new Stack<Integer>();
private Stack<Integer> whileJumpIndexStack = new Stack<Integer>();
@Override
public void enterWhileStatement(WhileStatementContext ctx) {
startBreakable();
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
int jumpIndex = instructions.size();
whileJumpIndexStack.push(jumpIndex);
}
@Override
public void exitWhileStatementCondition(WhileStatementConditionContext ctx) {
int conditionalJumpIndex = instructions.size();
whileConditionalJumpIndexStack.push(conditionalJumpIndex);
instructions.add(null);
}
@Override
public void exitWhileStatementBody(WhileStatementBodyContext ctx) {
int jumpIndex = whileJumpIndexStack.pop();
int whileBodyEndIndex = instructions.size();
int jump = jumpIndex - whileBodyEndIndex;
instructions.add(new Instruction(Instruction.OPCODE_JUMP, jump));
}
@Override
public void exitWhileStatement(WhileStatementContext ctx) {
int whileEndIndex = instructions.size();
int conditionalJumpIndex = whileConditionalJumpIndexStack.pop();
int conditionalJump = whileEndIndex - conditionalJumpIndex;
instructions.set(conditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
endBreakable();
}
private Stack<Integer> forConditionalJumpIndexStack = new Stack<Integer>();
private Stack<Integer> forJumpIndexStack = new Stack<Integer>();
@Override
public void enterForStatement(ForStatementContext ctx) {
startBreakable();
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
}
@Override
public void enterForStatementCondition(ForStatementConditionContext ctx) {
forJumpIndexStack.push(instructions.size());
}
@Override
public void enterForStatementUpdate(ForStatementUpdateContext ctx) {
// Postpone generation of update till after body
walker.suspendWalkWithin(ctx);
}
@Override
public void enterForStatementBody(ForStatementBodyContext ctx) {
int conditionalJumpIndex = instructions.size();
forConditionalJumpIndexStack.push(conditionalJumpIndex);
instructions.add(null);
}
@Override
public void exitForStatement(ForStatementContext ctx) {
ConditionalTreeWalker walker = new ConditionalTreeWalker();
ParseTree updateElement = ctx.forStatementUpdate().delimitedProgramElement();
walker.walk(
createBodyListener(walker, idToParameterOrdinalMap, idToVariableOrdinalMap, instructions, yieldStatements),
updateElement
);
int indexAtCondition = forJumpIndexStack.pop();
int conditionJump = indexAtCondition - instructions.size();
instructions.add(new Instruction(Instruction.OPCODE_JUMP, conditionJump));
int conditionalJumpIndex = forConditionalJumpIndexStack.pop();
int conditionalJump = instructions.size() - conditionalJumpIndex;
instructions.set(conditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
endBreakable();
}
private Stack<Integer> forInConditionalJumpIndexStack = new Stack<Integer>();
private Stack<Integer> forInJumpIndexStack = new Stack<Integer>();
@Override
public void enterForInStatement(ForInStatementContext ctx) {
startBreakable();
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
for(ForInStatementVarContext varCtx: ctx.forInStatementVar())
idToVariableOrdinalMap.declare(varCtx.ID().getText());
}
@Override
public void enterForInStatementBody(ForInStatementBodyContext ctx) {
ForInStatementContext forInStatementCtx = (ForInStatementContext)ctx.getParent();
// iterable
instructions.add(new Instruction(Instruction.OPCODE_SEND, "iterator", 0));
// iterator
int jumpIndex = instructions.size();
forInJumpIndexStack.push(jumpIndex);
instructions.add(new Instruction(Instruction.OPCODE_DUP));
// iterator, iterator
instructions.add(new Instruction(Instruction.OPCODE_SEND, "atEnd", 0));
// iterator, bool
int conditionalJumpIndex = instructions.size();
forInConditionalJumpIndexStack.push(conditionalJumpIndex);
instructions.add(null);
// iterator
for(ForInStatementVarContext varCtx: forInStatementCtx.forInStatementVar()) {
// iterator
instructions.add(new Instruction(Instruction.OPCODE_DUP));
// iterator, iterator
instructions.add(new Instruction(Instruction.OPCODE_SEND, "next", 0));
// iterator, next
String id = varCtx.ID().getText();
int ordinal = idToVariableOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, ordinal));
// iterator
}
// iterator
}
@Override
public void exitForInStatementBody(ForInStatementBodyContext ctx) {
int jumpIndex = forInJumpIndexStack.pop();
int jump = jumpIndex - instructions.size();
instructions.add(new Instruction(Instruction.OPCODE_JUMP, jump));
int conditionalJumpIndex = forInConditionalJumpIndexStack.pop();
int conditionalJump = instructions.size() - conditionalJumpIndex;
instructions.set(conditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_TRUE, conditionalJump));
// iterator
instructions.add(new Instruction(Instruction.OPCODE_POP));
//
}
@Override
public void exitForInStatement(ForInStatementContext ctx) {
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
endBreakable();
}
@Override
public void enterInterfaceId(InterfaceIdContext ctx) {
String interfaceId = ctx.ID().getText();
instructions.add(new Instruction(Instruction.OPCODE_EXTEND_INTER_ID, interfaceId));
}
@Override
public void exitInterfaceId(InterfaceIdContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SHRINK_INTER_ID));
}
@Override
public void exitMemberAccess(MemberAccessContext ctx) {
String id = ctx.messageId().getText();
instructions.add(new Instruction(Instruction.OPCODE_GET, id));
}
@Override
public void exitIndexAccess(IndexAccessContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SEND, "get", 1));
}
@Override
public void exitExplicitMessageExchange(ExplicitMessageExchangeContext ctx) {
int argumentCount = ctx.messageExchange().expression().size();
String id = ctx.messageExchange().messageId().getText();
appendMessageExchange(id, argumentCount);
}
@Override
public void enterMemberAssignment(MemberAssignmentContext ctx) {
// receiver
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN:
case DuroLexer.PROTO_ASSIGN:
break;
default:
String id = ctx.messageId().getText();
// For computed value +=, -=, ...
instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Dup receiver
// receiver, receiver
instructions.add(new Instruction(Instruction.OPCODE_GET, id));
// receiver, oldValue
break;
}
}
@Override
public void exitMemberAssignment(MemberAssignmentContext ctx) {
String id = ctx.messageId().getText();
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN:
// receiver, value
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// value, receiver, value
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
// value
break;
case DuroLexer.PROTO_ASSIGN:
// receiver, value
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// value, receiver, value
instructions.add(new Instruction(Instruction.OPCODE_SET_PROTO, id));
// value
break;
default:
// receiver, oldValue, newValuePart
appendAssignmentReducer(ctx.op);
// receiver, newValue
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// newValue, receiver, newValue
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
// newValue, receiver, id, newValue
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
// newValue
break;
}
}
@Override
public void enterIndexAssignment(IndexAssignmentContext ctx) {
// receiver
if(ctx.op.getType() != DuroLexer.ASSIGN) {
// For computed value +=, -=, ...
instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Dup receiver
// receiver, receiver
ParseTree keyExpression = ctx.indexAssignmentKey().expression();
walker.walk(
createBodyListener(walker, idToParameterOrdinalMap, idToVariableOrdinalMap, instructions, yieldStatements),
keyExpression
);
// receiver, receiver, id
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// receiver, id, receiver, id
instructions.add(new Instruction(Instruction.OPCODE_SEND, "get", 1));
// receiver, id, oldValue
}
}
@Override
public void enterIndexAssignmentKey(IndexAssignmentKeyContext ctx) {
IndexAssignmentContext computedMemberAssignmentCtx = (IndexAssignmentContext)ctx.getParent();
if(computedMemberAssignmentCtx.op.getType() != DuroLexer.ASSIGN)
walker.suspendWalkWithin(ctx);
}
@Override
public void exitIndexAssignment(IndexAssignmentContext ctx) {
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN:
// receiver, id, value
instructions.add(new Instruction(Instruction.OPCODE_DUP2));
// value, receiver, id, value
instructions.add(new Instruction(Instruction.OPCODE_SEND, "set", 2));
instructions.add(new Instruction(Instruction.OPCODE_POP));
break;
default:
// receiver, id, oldValue, newValuePart
appendAssignmentReducer(ctx.op);
// receiver, id, newValue
instructions.add(new Instruction(Instruction.OPCODE_DUP2));
// newValue, receiver, id, newValue
instructions.add(new Instruction(Instruction.OPCODE_SEND, "set", 2));
instructions.add(new Instruction(Instruction.OPCODE_POP));
// newValue
break;
}
}
private Stack<Integer> programElementCountStack = new Stack<Integer>();
private Stack<Integer> programElementIndexStack = new Stack<Integer>();
@Override
public void enterProgramElements(ProgramElementsContext ctx) {
programElementCountStack.push(ctx.programElementsPart().size());
programElementIndexStack.push(0);
}
@Override
public void enterProgramElementsPart(ProgramElementsPartContext ctx) {
}
@Override
public void exitProgramElementsPart(ProgramElementsPartContext ctx) {
programElementIndexStack.set(programElementIndexStack.size() - 1, programElementIndexStack.peek() + 1);
}
@Override
public void exitProgramElements(ProgramElementsContext ctx) {
programElementCountStack.pop();
programElementIndexStack.pop();
}
@Override
public void enterProgramElement(ProgramElementContext ctx) {
programElementCountStack.push(1);
programElementIndexStack.push(0);
}
@Override
public void exitProgramElement(ProgramElementContext ctx) {
programElementCountStack.pop();
programElementIndexStack.pop();
}
@Override
public void exitTopExpression(TopExpressionContext ctx) {
int programElementCount = programElementCountStack.peek();
int programElementIndex = programElementIndexStack.peek();
if(programElementIndex + 1 < programElementCount)
instructions.add(new Instruction(Instruction.OPCODE_POP));
}
};
}
private static String extractStringLiteral(String rawString) {
return rawString.substring(1, rawString.length() - 1)
.replace("\\n", "\n")
.replace("\\r", "\r")
.replace("\\t", "\t");
}
private BodyInfo getBodyInfo(
OrdinalAllocator idToParameterOrdinalMap, OrdinalAllocator idToVariableOrdinalMap, ParseTree tree) {
ArrayList<Instruction> instructions = new ArrayList<Instruction>();
ArrayList<YieldStatementContext> yieldStatements = new ArrayList<YieldStatementContext>();
ConditionalTreeWalker walker = new ConditionalTreeWalker();
walker.walk(
createBodyListener(walker, idToParameterOrdinalMap, idToVariableOrdinalMap, instructions, yieldStatements),
tree
);
int variableCount = idToVariableOrdinalMap.size();
if(yieldStatements.size() > 0) {
// Generatable/generator
// Function returns iterables
int distinctYieldCount = (int)yieldStatements.stream().map(i -> i.yieldStatementExpression().size()).distinct().count();
if(distinctYieldCount > 1)
throw new RuntimeException("Multiple distinct yield counts.");
ArrayList<Instruction> iteratorInstructions = instructions;
ArrayList<Instruction> generatorInstructions = new ArrayList<Instruction>();
// int[] ordinals = new int[] {idToParameterOrdinalMap.ordinalFor("generator")};
int argumentOffset = idToParameterOrdinalMap.ordinalFor("generator");
int parameterCount = idToParameterOrdinalMap.size();
int closureParameterCount = 1;
Instruction[] bodyInstructions = iteratorInstructions.toArray(new Instruction[iteratorInstructions.size()]);
generatorInstructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS, 1));
// This
generatorInstructions.add(new Instruction(Instruction.OPCODE_GET, "Generatable"));
// Generatable
generatorInstructions.add(new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, variableCount, bodyInstructions));
// Generatable, Behavior
generatorInstructions.add(new Instruction(Instruction.OPCODE_SP_NEW_CLOSURE, argumentOffset, closureParameterCount));
// Generatable, Closure
generatorInstructions.add(new Instruction(Instruction.OPCODE_SEND, "on", 1));
// a generatable
generatorInstructions.add(new Instruction(Instruction.OPCODE_RET, 1));
return new BodyInfo(variableCount, generatorInstructions);
} else
return new BodyInfo(variableCount, instructions);
}
private static class LiteralDuroListener extends DuroBaseListener {
private Object literal;
public Object getLiteral() {
return literal;
}
@Override
public void enterInteger(IntegerContext ctx) {
literal = Integer.parseInt(ctx.INT().getText());
}
@Override
public void enterString(StringContext ctx) {
literal = extractStringLiteral(ctx.STRING_LITERAL().getText());
}
}
private static Object getLiteral(ParseTree tree) {
ParseTreeWalker walker = new ParseTreeWalker();
LiteralDuroListener listener = new LiteralDuroListener();
walker.walk(listener, tree);
return listener.getLiteral();
}
private static class BodyInfo {
private final int localCount;
private final ArrayList<Instruction> instructions;
public BodyInfo(int ordinalCount, ArrayList<Instruction> instructions) {
this.localCount = ordinalCount;
this.instructions = instructions;
}
}
}
| eclipse/src/duro/reflang/Compiler.java | package duro.reflang;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.util.stream.Collectors;
import org.antlr.v4.runtime.ANTLRErrorListener;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.RuleNode;
import org.antlr.v4.runtime.tree.TerminalNode;
import duro.debugging.Debug;
import duro.reflang.antlr4.DuroBaseListener;
import duro.reflang.antlr4.DuroLexer;
import duro.reflang.antlr4.DuroListener;
import duro.reflang.antlr4.DuroParser;
import duro.reflang.antlr4.DuroParser.ArgumentParameterContext;
import duro.reflang.antlr4.DuroParser.ArrayContext;
import duro.reflang.antlr4.DuroParser.ArrayOperandContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionArithmetic1ApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionArithmetic2ApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionEqualityApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionEqualityContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionGreaterLessApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionGreaterLessContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionLogicalAndApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionLogicalAndContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionLogicalOrApplicationContext;
import duro.reflang.antlr4.DuroParser.BinaryExpressionLogicalOrContext;
import duro.reflang.antlr4.DuroParser.BoolContext;
import duro.reflang.antlr4.DuroParser.BreakStatementContext;
import duro.reflang.antlr4.DuroParser.ClosureBodyContext;
import duro.reflang.antlr4.DuroParser.ClosureLiteralContext;
import duro.reflang.antlr4.DuroParser.ConditionalExpressionConditionContext;
import duro.reflang.antlr4.DuroParser.ConditionalExpressionContext;
import duro.reflang.antlr4.DuroParser.ConditionalExpressionFalseContext;
import duro.reflang.antlr4.DuroParser.ConditionalExpressionTrueContext;
import duro.reflang.antlr4.DuroParser.DictProcessContext;
import duro.reflang.antlr4.DuroParser.DictProcessEntryContext;
import duro.reflang.antlr4.DuroParser.ElseStatementContext;
import duro.reflang.antlr4.DuroParser.ExplicitMessageExchangeContext;
import duro.reflang.antlr4.DuroParser.ForInStatementBodyContext;
import duro.reflang.antlr4.DuroParser.ForInStatementContext;
import duro.reflang.antlr4.DuroParser.ForInStatementVarContext;
import duro.reflang.antlr4.DuroParser.ForStatementBodyContext;
import duro.reflang.antlr4.DuroParser.ForStatementConditionContext;
import duro.reflang.antlr4.DuroParser.ForStatementContext;
import duro.reflang.antlr4.DuroParser.ForStatementUpdateContext;
import duro.reflang.antlr4.DuroParser.FrameContext;
import duro.reflang.antlr4.DuroParser.FunctionBodyContext;
import duro.reflang.antlr4.DuroParser.FunctionDefinitionContext;
import duro.reflang.antlr4.DuroParser.FunctionLiteralContext;
import duro.reflang.antlr4.DuroParser.IfStatementConditionContext;
import duro.reflang.antlr4.DuroParser.IfStatementOnTrueContext;
import duro.reflang.antlr4.DuroParser.IndexAccessContext;
import duro.reflang.antlr4.DuroParser.IndexAssignmentContext;
import duro.reflang.antlr4.DuroParser.IndexAssignmentKeyContext;
import duro.reflang.antlr4.DuroParser.IntegerContext;
import duro.reflang.antlr4.DuroParser.InterfaceIdContext;
import duro.reflang.antlr4.DuroParser.LookupContext;
import duro.reflang.antlr4.DuroParser.MemberAccessContext;
import duro.reflang.antlr4.DuroParser.MemberAssignmentContext;
import duro.reflang.antlr4.DuroParser.NilContext;
import duro.reflang.antlr4.DuroParser.PauseContext;
import duro.reflang.antlr4.DuroParser.PrimitiveContext;
import duro.reflang.antlr4.DuroParser.PrimitiveOperand2Context;
import duro.reflang.antlr4.DuroParser.ProgramContext;
import duro.reflang.antlr4.DuroParser.ProgramElementContext;
import duro.reflang.antlr4.DuroParser.ProgramElementsContext;
import duro.reflang.antlr4.DuroParser.ProgramElementsPartContext;
import duro.reflang.antlr4.DuroParser.ReturnStatementContext;
import duro.reflang.antlr4.DuroParser.SelfContext;
import duro.reflang.antlr4.DuroParser.StringContext;
import duro.reflang.antlr4.DuroParser.ThisMessageExchangeContext;
import duro.reflang.antlr4.DuroParser.TopExpressionContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionNotApplicationContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionPostIncDecApplicationContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionPostIncDecApplicationIndexAccessReceiverContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionPostIncDecApplicationMemberAccessContext;
import duro.reflang.antlr4.DuroParser.UnaryExpressionPostIncDecApplicationVariableContext;
import duro.reflang.antlr4.DuroParser.VariableAssignmentContext;
import duro.reflang.antlr4.DuroParser.VariableDeclarationAndAssignmentContext;
import duro.reflang.antlr4.DuroParser.VariableDeclarationContext;
import duro.reflang.antlr4.DuroParser.WhileStatementBodyContext;
import duro.reflang.antlr4.DuroParser.WhileStatementConditionContext;
import duro.reflang.antlr4.DuroParser.WhileStatementContext;
import duro.reflang.antlr4.DuroParser.YieldStatementContext;
import duro.reflang.antlr4.DuroParser.YieldStatementExpressionContext;
import duro.runtime.CustomProcess;
import duro.runtime.Instruction;
public class Compiler {
private MessageCollector errors = new MessageCollector();
private void appendError(ParserRuleContext ctx, String message) {
errors.appendMessage(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine(), message);
}
private void appendError(int line, int charPositionInLine, String message) {
errors.appendMessage(line, charPositionInLine, message);
}
private void appendErrors(MessageCollector errors) {
this.errors.appendMessages(errors);
}
public boolean hasErrors() {
return errors.hasMessages();
}
public void printErrors() {
errors.printMessages();
}
public CustomProcess compile(InputStream sourceCode) throws IOException {
CharStream charStream = new ANTLRInputStream(sourceCode);
DuroLexer lexer = new DuroLexer(charStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
DuroParser parser = new DuroParser(tokenStream);
parser.removeErrorListeners();
parser.addErrorListener(new ANTLRErrorListener() {
@Override
public void syntaxError(Recognizer<?,?> recognizer, java.lang.Object offendingSymbol, int line, int charPositionInLine, java.lang.String msg, RecognitionException e) {
appendError(line, charPositionInLine, msg);
}
@Override
public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs) {
new String();
}
@Override
public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, java.util.BitSet conflictingAlts, ATNConfigSet configs) {
new String();
}
@Override
public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact, java.util.BitSet ambigAlts, ATNConfigSet configs) {
new String();
}
});
Debug.println(Debug.LEVEL_HIGH, "Parsing program...");
ProgramContext programCtx;
// Parsing approach following https://theantlrguy.atlassian.net/wiki/pages/viewpage.action?pageId=1900591
parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
try {
programCtx = parser.program(); // STAGE 1
}
catch (Exception ex) {
tokenStream.reset(); // rewind input stream
parser.reset();
parser.getInterpreter().setPredictionMode(PredictionMode.LL);
programCtx = parser.program(); // STAGE 2
// if we parse ok, it's LL not SLL
}
Debug.println(Debug.LEVEL_HIGH, "Parsed program.");
OrdinalAllocator idToParameterOrdinalMap = new OrdinalAllocator();
OrdinalAllocator idToVariableOrdinalMap = new OrdinalAllocator();
Debug.println(Debug.LEVEL_HIGH, "Generating program...");
BodyInfo bodyInfo = getBodyInfo(idToParameterOrdinalMap, idToVariableOrdinalMap, programCtx);
Debug.println(Debug.LEVEL_HIGH, "Generated program.");
return new CustomProcess(idToParameterOrdinalMap.size(), bodyInfo.localCount, bodyInfo.instructions.toArray(new Instruction[bodyInfo.instructions.size()]));
}
private static class ConditionalTreeWalker extends ParseTreeWalker {
private boolean suspendWalk;
private RuleNode ruleSuspendedAt;
@Override
protected void enterRule(ParseTreeListener listener, RuleNode r) {
if(!suspendWalk)
super.enterRule(listener, r);
}
@Override
protected void exitRule(ParseTreeListener listener, RuleNode r) {
if(ruleSuspendedAt == r)
suspendWalk = false;
if(!suspendWalk)
super.exitRule(listener, r);
}
public void suspendWalkWithin(RuleNode r) {
suspendWalk = true;
ruleSuspendedAt = r;
}
}
private DuroListener createBodyListener(
final ConditionalTreeWalker walker, OrdinalAllocator idToParameterOrdinalMap, OrdinalAllocator idToVariableOrdinalMapArg,
final ArrayList<Instruction> instructions, final ArrayList<YieldStatementContext> yieldStatements) {
return new DuroBaseListener() {
OrdinalAllocator idToVariableOrdinalMap = idToVariableOrdinalMapArg;
@Override
public void exitProgram(ProgramContext ctx) {
// Add finish instruction to the end
instructions.add(new Instruction(Instruction.OPCODE_FINISH));
}
Stack<Integer> conditionalConditionalJumpIndexesStack = new Stack<Integer>();
Stack<Integer> conditionalJumpIndexStack = new Stack<Integer>();
@Override
public void enterConditionalExpression(ConditionalExpressionContext ctx) {
}
@Override
public void exitConditionalExpressionCondition(ConditionalExpressionConditionContext ctx) {
// [<bool>]
instructions.add(new Instruction(Instruction.OPCODE_DUP));
int conditionalJumpIndex = instructions.size();
instructions.add(null); // If false, jump to else expression
conditionalConditionalJumpIndexesStack.add(conditionalJumpIndex);
}
@Override
public void exitConditionalExpressionTrue(ConditionalExpressionTrueContext ctx) {
int jumpIndex = instructions.size();
conditionalJumpIndexStack.push(jumpIndex);
instructions.add(null); // Jump to the end of the conditional expression
int trueEndIndex = instructions.size();
int conditionalConditionalJumpIndex = conditionalConditionalJumpIndexesStack.pop();
int conditionalJump = trueEndIndex - conditionalConditionalJumpIndex;
instructions.set(conditionalConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
}
@Override
public void exitConditionalExpressionFalse(ConditionalExpressionFalseContext ctx) {
int jumpIndex = conditionalJumpIndexStack.pop();
int jump = instructions.size() - jumpIndex;
instructions.set(jumpIndex, new Instruction(Instruction.OPCODE_JUMP, jump));
}
@Override
public void exitConditionalExpression(ConditionalExpressionContext ctx) {
}
Stack<ArrayList<Integer>> orConditionalJumpIndexesStack = new Stack<ArrayList<Integer>>();
@Override
public void enterBinaryExpressionLogicalOr(BinaryExpressionLogicalOrContext ctx) {
orConditionalJumpIndexesStack.push(new ArrayList<Integer>());
}
@Override
public void enterBinaryExpressionLogicalOrApplication(BinaryExpressionLogicalOrApplicationContext ctx) {
ArrayList<Integer> orConditionalJumpIndexes = orConditionalJumpIndexesStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
int conditionalJumpIndex = instructions.size();
instructions.add(null);
orConditionalJumpIndexes.add(conditionalJumpIndex);
}
@Override
public void exitBinaryExpressionLogicalOrApplication(BinaryExpressionLogicalOrApplicationContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SP_BOOLEAN_OR));
}
@Override
public void exitBinaryExpressionLogicalOr(BinaryExpressionLogicalOrContext ctx) {
int orEndIndex = instructions.size();
ArrayList<Integer> orConditionalJumpIndexes = orConditionalJumpIndexesStack.pop();
for(int orConditionalJumpIndex: orConditionalJumpIndexes) {
int conditionalJump = orEndIndex - orConditionalJumpIndex;
// If true, skip the rest
instructions.set(orConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_TRUE, conditionalJump));
}
}
Stack<ArrayList<Integer>> andConditionalJumpIndexesStack = new Stack<ArrayList<Integer>>();
@Override
public void enterBinaryExpressionLogicalAnd(BinaryExpressionLogicalAndContext ctx) {
andConditionalJumpIndexesStack.push(new ArrayList<Integer>());
}
@Override
public void enterBinaryExpressionLogicalAndApplication(BinaryExpressionLogicalAndApplicationContext ctx) {
ArrayList<Integer> andConditionalJumpIndexes = andConditionalJumpIndexesStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
int conditionalJumpIndex = instructions.size();
instructions.add(null);
andConditionalJumpIndexes.add(conditionalJumpIndex);
}
@Override
public void exitBinaryExpressionLogicalAndApplication(BinaryExpressionLogicalAndApplicationContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SP_BOOLEAN_AND));
}
@Override
public void exitBinaryExpressionLogicalAnd(BinaryExpressionLogicalAndContext ctx) {
int andEndIndex = instructions.size();
ArrayList<Integer> andConditionalJumpIndexes = andConditionalJumpIndexesStack.pop();
for(int andConditionalJumpIndex: andConditionalJumpIndexes) {
int conditionalJump = andEndIndex - andConditionalJumpIndex;
// If false, skip the rest
instructions.set(andConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
}
}
Stack<ArrayList<Integer>> equalsConditionalJumpIndexesStack = new Stack<ArrayList<Integer>>();
@Override
public void enterBinaryExpressionEquality(BinaryExpressionEqualityContext ctx) {
equalsConditionalJumpIndexesStack.add(new ArrayList<Integer>());
}
@Override
public void exitBinaryExpressionEqualityApplication(BinaryExpressionEqualityApplicationContext ctx) {
ArrayList<Integer> equalsConditionalJumpIndexes = equalsConditionalJumpIndexesStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
instructions.add(new Instruction(Instruction.OPCODE_SWAP1));
String operatorId = ctx.op.getText();
instructions.add(new Instruction(Instruction.OPCODE_SEND, operatorId, 1));
int conditionalJumpIndex = instructions.size();
instructions.add(null);
equalsConditionalJumpIndexes.add(conditionalJumpIndex);
}
@Override
public void exitBinaryExpressionEquality(BinaryExpressionEqualityContext ctx) {
ArrayList<Integer> equalsConditionalJumpIndexes = equalsConditionalJumpIndexesStack.pop();
if(equalsConditionalJumpIndexes.size() > 0) {
// If there were any applications
instructions.add(new Instruction(Instruction.OPCODE_LOAD_TRUE));
instructions.add(new Instruction(Instruction.OPCODE_JUMP, 2));
int equalsEndIndex = instructions.size();
for(int equalsConditionalJumpIndex: equalsConditionalJumpIndexes) {
int conditionalJump = equalsEndIndex - equalsConditionalJumpIndex;
// If false, skip the rest
instructions.set(equalsConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
}
instructions.add(new Instruction(Instruction.OPCODE_LOAD_FALSE));
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
instructions.add(new Instruction(Instruction.OPCODE_POP));
}
}
Stack<ArrayList<Integer>> greaterLessConditionalJumpIndexesStack = new Stack<ArrayList<Integer>>();
Stack<Integer> greaterLessOperandCountStack = new Stack<Integer>();
@Override
public void enterBinaryExpressionGreaterLess(BinaryExpressionGreaterLessContext ctx) {
int operandCount = ctx.binaryExpressionGreaterLessApplication().size() + 1;
greaterLessOperandCountStack.push(operandCount);
if(operandCount > 2) {
greaterLessConditionalJumpIndexesStack.add(new ArrayList<Integer>());
}
}
@Override
public void exitBinaryExpressionGreaterLessApplication(BinaryExpressionGreaterLessApplicationContext ctx) {
int operandCount = greaterLessOperandCountStack.peek();
if(operandCount > 2) {
ArrayList<Integer> greaterLessConditionalJumpIndexes = greaterLessConditionalJumpIndexesStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
instructions.add(new Instruction(Instruction.OPCODE_SWAP1));
appendGreaterLessOperator(ctx);
int conditionalJumpIndex = instructions.size();
instructions.add(null);
greaterLessConditionalJumpIndexes.add(conditionalJumpIndex);
} else if(operandCount == 2){
appendGreaterLessOperator(ctx);
}
}
private void appendGreaterLessOperator(BinaryExpressionGreaterLessApplicationContext ctx) {
String operator = ctx.op.getText();
instructions.add(new Instruction(Instruction.OPCODE_SEND, operator, 1));
}
@Override
public void exitBinaryExpressionGreaterLess(BinaryExpressionGreaterLessContext ctx) {
int operandCount = greaterLessOperandCountStack.pop();
if(operandCount > 2) {
ArrayList<Integer> greaterLessConditionalJumpIndexes = greaterLessConditionalJumpIndexesStack.pop();
if(greaterLessConditionalJumpIndexes.size() > 0) {
// If there were any applications
instructions.add(new Instruction(Instruction.OPCODE_LOAD_TRUE));
instructions.add(new Instruction(Instruction.OPCODE_JUMP, 2));
int equalsEndIndex = instructions.size();
for(int greaterLessConditionalJumpIndex: greaterLessConditionalJumpIndexes) {
int conditionalJump = equalsEndIndex - greaterLessConditionalJumpIndex;
// If false, skip the rest
instructions.set(greaterLessConditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
}
instructions.add(new Instruction(Instruction.OPCODE_LOAD_FALSE));
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
instructions.add(new Instruction(Instruction.OPCODE_POP));
}
}
}
@Override
public void exitBinaryExpressionArithmetic1Application(BinaryExpressionArithmetic1ApplicationContext ctx) {
String id = ctx.BIN_OP1().getText();
instructions.add(new Instruction(Instruction.OPCODE_SEND, id, 1));
}
@Override
public void exitBinaryExpressionArithmetic2Application(BinaryExpressionArithmetic2ApplicationContext ctx) {
String id = ctx.BIN_OP2().getText();
instructions.add(new Instruction(Instruction.OPCODE_SEND, id, 1));
}
@Override
public void exitUnaryExpressionNotApplication(UnaryExpressionNotApplicationContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SP_BOOLEAN_NOT));
}
@Override
public void exitUnaryExpressionPostIncDecApplicationIndexAccessReceiver(UnaryExpressionPostIncDecApplicationIndexAccessReceiverContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Dup receiver
}
@Override
public void exitUnaryExpressionPostIncDecApplication(UnaryExpressionPostIncDecApplicationContext ctx) {
ParserRuleContext targetCtx = (ParserRuleContext)ctx.getChild(0);
switch(targetCtx.getRuleIndex()) {
case DuroParser.RULE_unaryExpressionPostIncDecApplicationVariable: {
// Either variable assignment or member assignment
String id = ((UnaryExpressionPostIncDecApplicationVariableContext)targetCtx).ID().getText();;
if(idToVariableOrdinalMap.isDeclared(id))
appendUnaryExpressionPostIncDecApplicationVariable(ctx, targetCtx);
else {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
// receiver
appendUnaryExpressionPostIncDecApplicationMemberAccess(ctx, id);
}
break;
} case DuroParser.RULE_unaryExpressionPostIncDecApplicationMemberAccess: {
String id = ((UnaryExpressionPostIncDecApplicationMemberAccessContext)targetCtx).ID().getText();
appendUnaryExpressionPostIncDecApplicationMemberAccess(ctx, id);
break;
} case DuroParser.RULE_unaryExpressionPostIncDecApplicationIndexAccess:
// receiver, receiver, id
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// receiver, id, receiver, id
instructions.add(new Instruction(Instruction.OPCODE_SEND, "get", 1));
// receiver, id, value
instructions.add(new Instruction(Instruction.OPCODE_DUP2));
// value, receiver, id, value,
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, 1));
// value, receiver, id, value, 1
appendIncDec(ctx.op);
// value, receiver, id, value'
instructions.add(new Instruction(Instruction.OPCODE_SEND, "set", 2));
instructions.add(new Instruction(Instruction.OPCODE_POP));
break;
}
}
private void appendUnaryExpressionPostIncDecApplicationVariable(UnaryExpressionPostIncDecApplicationContext ctx, ParserRuleContext targetCtx) {
String id = ((UnaryExpressionPostIncDecApplicationVariableContext)targetCtx).ID().getText();
int ordinal = idToVariableOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_LOAD_LOC, ordinal));
instructions.add(new Instruction(Instruction.OPCODE_DUP));
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, 1));
appendIncDec(ctx.op);
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, ordinal));
}
private void appendUnaryExpressionPostIncDecApplicationMemberAccess(UnaryExpressionPostIncDecApplicationContext ctx, String id) {
// receiver
instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Dup receiver
// receiver, receiver
instructions.add(new Instruction(Instruction.OPCODE_GET, id));
// receiver, value
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// value, receiver, value
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, 1));
// value, receiver, value, 1
appendIncDec(ctx.op);
// value, receiver, value'
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
// value
}
private void appendIncDec(Token opToken) {
switch(opToken.getType()) {
case DuroLexer.DOUBLE_PLUS:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "+", 1));
break;
case DuroLexer.DOUBLE_MINUS:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "-", 1));
break;
}
}
@Override
public void enterVariableAssignment(VariableAssignmentContext ctx) {
String firstId = ctx.ID(0).getText();
if(idToVariableOrdinalMap.isDeclared(firstId)) {
// Variable assignment
int firstOrdinal = idToVariableOrdinalMap.ordinalFor(firstId);
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN: {
break;
} default: {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_LOC, firstOrdinal));
// oldValue
break;
}
}
} else {
// Member assignment for this
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN: {
break;
} default: {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
instructions.add(new Instruction(Instruction.OPCODE_GET, firstId));
// oldValue
break;
}
}
}
}
@Override
public void exitVariableAssignment(VariableAssignmentContext ctx) {
String firstId = ctx.ID(0).getText();
if(idToVariableOrdinalMap.isDeclared(firstId)) {
int firstOrdinal = idToVariableOrdinalMap.ordinalFor(firstId);
// Variable assignment
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN: {
instructions.add(new Instruction(Instruction.OPCODE_DUP_ANY, 0, ctx.ID().size() - 1));
for(int i = 0; i < ctx.ID().size(); i++) {
String id = ctx.ID(i).getText();
int ordinal = idToVariableOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, ordinal));
}
break;
} default: {
// Multiple returns values are not supported here yet.
// oldValue, newValuePart
appendAssignmentReducer(ctx.op);
// newValue
instructions.add(new Instruction(Instruction.OPCODE_DUP));
// newValue, newValue
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, firstOrdinal));
// newValue
break;
}
}
} else {
// Member assignment for this
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN: {
instructions.add(new Instruction(Instruction.OPCODE_DUP_ANY, 0, ctx.ID().size() - 1));
for(int i = 0; i < ctx.ID().size(); i++) {
String id = ctx.ID(i).getText();
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
}
break;
} default: {
// Multiple returns values are not supported here yet.
// oldValue, newValuePart
appendAssignmentReducer(ctx.op);
// newValue
instructions.add(new Instruction(Instruction.OPCODE_DUP));
// newValue, newValue
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
// newValue, newValue, receiver
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
// newValue, receiver, newValue
instructions.add(new Instruction(Instruction.OPCODE_SET, firstId));
// newValue
break;
}
}
}
}
private void appendAssignmentReducer(Token op) {
switch(op.getType()) {
case DuroLexer.ASSIGN_ADD:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "+", 1));
break;
case DuroLexer.ASSIGN_SUB:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "-", 1));
break;
case DuroLexer.ASSIGN_MULT:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "*", 1));
break;
case DuroLexer.ASSIGN_DIV:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "/", 1));
break;
case DuroLexer.ASSIGN_REM:
instructions.add(new Instruction(Instruction.OPCODE_SEND, "%", 1));
break;
}
}
@Override
public void enterLookup(LookupContext ctx) {
String id = ctx.ID().getText();
Integer parameterOrdinal = idToParameterOrdinalMap.ordinalFor(id);
if(parameterOrdinal != null) {
// Load argument
instructions.add(new Instruction(Instruction.OPCODE_LOAD_ARG, parameterOrdinal));
return;
}
Integer variableOrdinal = idToVariableOrdinalMap.ordinalFor(id);
if(variableOrdinal != null) {
// Load variable
instructions.add(new Instruction(Instruction.OPCODE_LOAD_LOC, variableOrdinal));
return;
}
// Get member
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
instructions.add(new Instruction(Instruction.OPCODE_GET, id));
}
@Override
public void enterArgumentParameter(ArgumentParameterContext ctx) {
int parameterOrdinal = idToParameterOrdinalMap.declare(ctx.ID().getText());
instructions.add(new Instruction(Instruction.OPCODE_LOAD_ARG, parameterOrdinal));
}
@Override
public void enterThisMessageExchange(ThisMessageExchangeContext ctx) {
String id = ctx.messageExchange().messageId().getText();
if(idToParameterOrdinalMap.isDeclared(id)) {
// Call argument
int ordinal = idToParameterOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_LOAD_ARG, ordinal));
} else if(idToVariableOrdinalMap.isDeclared(id)) {
// Call variable
int ordinal = idToVariableOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_LOAD_LOC, ordinal));
} else {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
}
}
@Override
public void exitThisMessageExchange(ThisMessageExchangeContext ctx) {
int argumentCount = ctx.messageExchange().expression().size();
String id = ctx.messageExchange().messageId().getText();
if(idToParameterOrdinalMap.isDeclared(id)) {
// Call argument
instructions.add(new Instruction(Instruction.OPCODE_CALL, argumentCount));
} else if(idToVariableOrdinalMap.isDeclared(id)) {
// Call variable
instructions.add(new Instruction(Instruction.OPCODE_CALL, argumentCount));
} else {
appendMessageExchange(id, argumentCount);
}
}
private void appendMessageExchange(String id, int argumentCount) {
// Currently: just resolve function and then call it.
instructions.add(new Instruction(Instruction.OPCODE_SEND, id, argumentCount));
}
@Override
public void enterInteger(IntegerContext ctx) {
int value = Integer.parseInt(ctx.INT().getText());
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, value));
}
@Override
public void enterBool(BoolContext ctx) {
boolean value = Boolean.parseBoolean(ctx.getText());
if(value)
instructions.add(new Instruction(Instruction.OPCODE_LOAD_TRUE, value));
else
instructions.add(new Instruction(Instruction.OPCODE_LOAD_FALSE, value));
}
@Override
public void enterString(StringContext ctx) {
String rawString = ctx.getText();
// Should the string enter properly prepared?
// - i.e., no need for filtering the string.
String string = extractStringLiteral(rawString);
instructions.add(new Instruction(Instruction.OPCODE_LOAD_STRING, string));
}
@Override
public void enterDictProcess(DictProcessContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_DICT));
}
@Override
public void enterDictProcessEntry(DictProcessEntryContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_DUP));
}
@Override
public void exitDictProcessEntry(DictProcessEntryContext ctx) {
String id = ctx.messageId().getText();
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
}
@Override
public void enterFunctionLiteral(FunctionLiteralContext ctx) {
walker.suspendWalkWithin(ctx);
}
@Override
public void exitFunctionLiteral(FunctionLiteralContext ctx) {
OrdinalAllocator newIdToParameterOrdinalMap = new OrdinalAllocator();
OrdinalAllocator newIdToVariableOrdinalMap = new OrdinalAllocator();
for(TerminalNode parameterIdNode: ctx.functionParameters().ID()) {
String parameterId = parameterIdNode.getText();
newIdToParameterOrdinalMap.declare(parameterId);
}
BodyInfo functionBodyInfo = getBodyInfo(newIdToParameterOrdinalMap, newIdToVariableOrdinalMap, ctx.functionBody());
int parameterCount = newIdToParameterOrdinalMap.size();
Instruction[] bodyInstructions = functionBodyInfo.instructions.toArray(new Instruction[functionBodyInfo.instructions.size()]);
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, functionBodyInfo.localCount, bodyInstructions)); // Should this create a function process?
}
@Override
public void enterClosureLiteral(ClosureLiteralContext ctx) {
// TODO: Instead of this, there could be a stack of instructions, where it is the top instructions that are manipulated
// In exit body, the instructions stack can be popped
walker.suspendWalkWithin(ctx);
}
@Override
public void exitClosureBody(ClosureBodyContext ctx) {
if(instructions.size() > 0) {
if(instructions.get(instructions.size() - 1).opcode == Instruction.OPCODE_POP) {
// Replace pop with return
instructions.set(instructions.size() - 1, new Instruction(Instruction.OPCODE_RET, 1));
} else if(!Instruction.isReturn(instructions.get(instructions.size() - 1).opcode)) {
// If the last program elements isn't an expression, e.g. a for statement
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
}
} else {
if(yieldStatements.size() > 0) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
} else {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
}
}
}
@Override
public void exitClosureLiteral(ClosureLiteralContext ctx) {
OrdinalAllocator newIdToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
OrdinalAllocator newIdToParameterOrdinalMap = idToParameterOrdinalMap.newInner();
for(TerminalNode parameterIdNode: ctx.closureParameters().ID()) {
String parameterId = parameterIdNode.getText();
newIdToParameterOrdinalMap.declare(parameterId);
}
BodyInfo functionBodyInfo = getBodyInfo(newIdToParameterOrdinalMap, newIdToVariableOrdinalMap, ctx.closureBody());
// int[] ordinals = newIdToParameterOrdinalMap.getOrdinals();
int parameterCount = newIdToParameterOrdinalMap.size();
int closureParameterOffset = newIdToParameterOrdinalMap.getLocalParameterOffset();
int closureParameterCount = newIdToParameterOrdinalMap.getLocalParameterCount();
Instruction[] bodyInstructions = functionBodyInfo.instructions.toArray(new Instruction[functionBodyInfo.instructions.size()]);
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, functionBodyInfo.localCount, bodyInstructions));
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_CLOSURE, closureParameterOffset, closureParameterCount));
// [closure]
}
Stack<Integer> arrayOperandNumberStack = new Stack<Integer>();
@Override
public void enterArray(ArrayContext ctx) {
int length = ctx.arrayOperand().size();
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, length));
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_ARRAY));
arrayOperandNumberStack.push(0);
}
@Override
public void enterArrayOperand(ArrayOperandContext ctx) {
int arrayOperandNumber = arrayOperandNumberStack.peek();
instructions.add(new Instruction(Instruction.OPCODE_DUP));
instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, arrayOperandNumber));
arrayOperandNumberStack.set(arrayOperandNumberStack.size() - 1, arrayOperandNumber + 1);
}
@Override
public void exitArrayOperand(ArrayOperandContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SEND, "set", 2));
instructions.add(new Instruction(Instruction.OPCODE_POP));
}
@Override
public void exitArray(ArrayContext ctx) {
arrayOperandNumberStack.pop();
}
@Override
public void enterSelf(SelfContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
}
@Override
public void enterNil(NilContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
}
@Override
public void enterFrame(FrameContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS_FRAME));
}
@Override
public void enterPrimitiveOperand2(PrimitiveOperand2Context ctx) {
walker.suspendWalkWithin(ctx);
}
@Override
public void exitPrimitiveOperand2(PrimitiveOperand2Context ctx) {
super.exitPrimitiveOperand2(ctx);
}
@Override
public void exitPrimitive(PrimitiveContext ctx) {
MessageCollector errors = new MessageCollector();
String opcodeId = ctx.ID().getText();
Integer opcode = Instruction.getOpcodeFromId(opcodeId);
Object[] operands = new Object[Math.max(ctx.primitiveOperand2().size(), 3)];
if(opcode != null) {
if(Instruction.isExpressionCompatible(opcode)) {
Class<?>[] expectedOperandTypes = Instruction.getOperandTypes(opcode);
Class<?>[] actualOperandTypes = new Class<?>[ctx.primitiveOperand2().size()];
for(int i = 0; i < ctx.primitiveOperand2().size(); i++) {
operands[i] = getLiteral(ctx.primitiveOperand2().get(i));
actualOperandTypes[i] = operands[i].getClass();
}
if(!Arrays.equals(expectedOperandTypes, actualOperandTypes)) {
int givenOperandCount = ctx.primitiveOperand2().size();
String givenOperandsStr = givenOperandCount > 0
? noun(givenOperandCount, "Operand") + " " + operandsToString(operands, givenOperandCount)
: "No operands";
String expectedOperandsStr = expectedOperandTypes.length > 0
? "operand sequence " + literalTypesToString(expectedOperandTypes) + " was"
: "no operands where";
errors.appendMessage(ctx,
givenOperandsStr + " " + wasWhere(givenOperandCount) +
" given when " + expectedOperandsStr + " expected for opcode '" + opcodeId + "'.");
}
if(ctx.primitiveArgument().size() != Instruction.getPopCount(opcode)) {
String was1 = nounWasWhere(ctx.primitiveArgument().size(), "argument");
String was2 = nounWasWhere(Instruction.getPopCount(opcode), "argument");
errors.appendMessage(ctx,
ctx.primitiveArgument().size() + " " + was1 + " given when " +
Instruction.getPopCount(opcode) + " " + was2 +
" expected for opcode '" + opcodeId + "'.");
}
} else {
errors.appendMessage(ctx, "Opcode '" + opcodeId + "' not compatible with expressions");
}
} else {
errors.appendMessage(ctx, "Invalid opcode '" + opcodeId + "'.");
}
if(!errors.hasMessages()) {
instructions.add(new Instruction(opcode, operands[0], operands[1], operands[2]));
if(!Instruction.doesReturn(opcode)) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
}
}
appendErrors(errors);
}
private String nounWasWhere(int count, String noun) {
return count == 1 ? noun + " was" : noun + "s where";
}
private String noun(int count, String noun) {
return count == 1 ? noun : noun + "s";
}
private String wasWhere(int count) {
return count == 1 ? "was" : "where";
}
private String operandsToString(Object[] operands, int count) {
if(operands.length > 0) {
return Arrays.asList(operands).stream().limit(count).map(x -> {
return x.getClass().getSimpleName() + "(" + x + ")";
}).collect(Collectors.joining(", "));
}
return "no";
}
private String literalTypesToString(Class<?>[] literalTypes) {
if(literalTypes.length > 0) {
return Arrays.asList(literalTypes).stream().map(x -> {
return x.getSimpleName();
}).collect(Collectors.joining(", ", "(", ")"));
}
return "no";
}
@Override
public void enterPause(PauseContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_PAUSE));
}
@Override
public void exitVariableDeclarationAndAssignment(VariableDeclarationAndAssignmentContext ctx) {
for(TerminalNode idNode: ctx.ID()) {
if(!idToVariableOrdinalMap.isDeclaredLocally(idNode.getText()) && !idToParameterOrdinalMap.isDeclared(idNode.getText())) {
int ordinal = idToVariableOrdinalMap.declare(idNode.getText());
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, ordinal));
} else {
appendError(ctx, "Variable '" + idNode.getText() + "' is already declared in this scope.");
}
}
}
@Override
public void enterVariableDeclaration(VariableDeclarationContext ctx) {
if(!idToVariableOrdinalMap.isDeclaredLocally(ctx.ID().getText()) && !idToParameterOrdinalMap.isDeclared(ctx.ID().getText())) {
idToVariableOrdinalMap.declare(ctx.ID().getText());
} else {
appendError(ctx, "Variable '" + ctx.ID().getText() + "' is already declared in this scope.");
}
}
@Override
public void exitReturnStatement(ReturnStatementContext ctx) {
int returnCount = ctx.expression().size();
instructions.add(new Instruction(Instruction.OPCODE_RET, returnCount));
}
private Stack<ArrayList<Integer>> breakIndexesStack = new Stack<ArrayList<Integer>>();
private void startBreakable() {
breakIndexesStack.push(new ArrayList<Integer>());
}
private void endBreakable() {
ArrayList<Integer> breakIndexes = breakIndexesStack.pop();
for(int breakIndex: breakIndexes)
instructions.set(breakIndex, new Instruction(Instruction.OPCODE_JUMP, instructions.size() - breakIndex));
}
@Override
public void enterBreakStatement(BreakStatementContext ctx) {
ArrayList<Integer> breakIndexes = breakIndexesStack.peek();
breakIndexes.add(instructions.size());
instructions.add(null);
}
@Override
public void enterFunctionDefinition(FunctionDefinitionContext ctx) {
walker.suspendWalkWithin(ctx);
}
@Override
public void exitFunctionDefinition(FunctionDefinitionContext ctx) {
String id = ctx.messageId().getText();
OrdinalAllocator newIdToParameterOrdinalMap = new OrdinalAllocator();
OrdinalAllocator newIdToVariableOrdinalMap = new OrdinalAllocator();
for(TerminalNode parameterIdNode: ctx.functionParameters().ID()) {
String parameterId = parameterIdNode.getText();
newIdToParameterOrdinalMap.declare(parameterId);
}
BodyInfo functionBodyInfo = getBodyInfo(newIdToParameterOrdinalMap, newIdToVariableOrdinalMap, ctx.functionBody());
Instruction[] bodyInstructions = functionBodyInfo.instructions.toArray(new Instruction[functionBodyInfo.instructions.size()]);
int parameterCount = newIdToParameterOrdinalMap.size();
instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS));
// this
instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, functionBodyInfo.localCount, bodyInstructions)); // Should this create a function process?
// this, behavior
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// behavior, this, behavior
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
// behavior
}
@Override
public void enterYieldStatementExpression(YieldStatementExpressionContext ctx) {
int generatableOrdinal = idToParameterOrdinalMap.declare("generator");
instructions.add(new Instruction(Instruction.OPCODE_LOAD_ARG, generatableOrdinal));
}
@Override
public void exitYieldStatementExpression(YieldStatementExpressionContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SEND, "put", 1));
}
@Override
public void exitYieldStatement(YieldStatementContext ctx) {
yieldStatements.add(ctx);
}
@Override
public void exitFunctionBody(FunctionBodyContext ctx) {
if(yieldStatements.size() > 0) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
} else if(instructions.size() == 0/* || !Instruction.isReturn(instructions.get(instructions.size() - 1).opcode)*/) {
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
} else if(!Instruction.isReturn(instructions.get(instructions.size() - 1).opcode)) {
instructions.add(new Instruction(Instruction.OPCODE_RET, 1));
}
}
// @Override
// public void enterPrimitiveBody(PrimitiveBodyContext ctx) {
// walker.suspendWalkWithin(ctx);
// }
//
// @Override
// public void exitPrimitiveBody(PrimitiveBodyContext ctx) {
// final Hashtable<String, Integer> labelDefinitionsToIndexMap = new Hashtable<String, Integer>();
// ArrayList<Runnable> labelUsageLinkers = new ArrayList<Runnable>();
//
// for(PrimitiveBodyPartContext primitiveBodyPartCtx: ctx.primitiveBodyPart()) {
// ParserRuleContext part = (ParserRuleContext)primitiveBodyPartCtx.getChild(0);
// switch(part.getRuleIndex()) {
// case DuroParser.RULE_primitiveLabel:
// PrimitiveLabelContext primitiveLabelCtx = (PrimitiveLabelContext)part;
// String label = primitiveLabelCtx.ID().getText();
// int index = instructions.size();
// labelDefinitionsToIndexMap.put(label, index);
// break;
// case DuroParser.RULE_primitiveCall:
// Instruction instruction;
//
// PrimitiveCallContext primitiveCallCtx = (PrimitiveCallContext)part;
// String opcodeId = primitiveCallCtx.ID().getText();
//
// int opcode = Instruction.getOpcodeFromId(opcodeId);
//
// switch(opcode) {
// case Instruction.OPCODE_IF_TRUE:
// case Instruction.OPCODE_IF_FALSE:
// instruction = null;
// final int indexUsage = instructions.size();
// final String jumpLabel = primitiveCallCtx.primitiveOperand().get(0).getText();
// labelUsageLinkers.add(() -> {
// int indexDefinition = labelDefinitionsToIndexMap.get(jumpLabel);
// int jump = indexDefinition - indexUsage;
// instructions.set(indexUsage, new Instruction(opcode, jump));
// });
// break;
// default:
// Object operand1 = null;
// Object operand2 = null;
// Object operand3 = null;
//
// if(primitiveCallCtx.primitiveOperand().size() > 0) {
// operand1 = getLiteral(primitiveCallCtx.primitiveOperand().get(0));
//
// if(primitiveCallCtx.primitiveOperand().size() > 1) {
// operand2 = getLiteral(primitiveCallCtx.primitiveOperand().get(1));
//
// if(primitiveCallCtx.primitiveOperand().size() > 2) {
// operand3 = getLiteral(primitiveCallCtx.primitiveOperand().get(2));
// }
// }
// }
//
// instruction = new Instruction(opcode, operand1, operand2, operand3);
// }
//
// instructions.add(instruction);
// break;
// }
// }
//
// for(Runnable labelUsageLinker: labelUsageLinkers)
// labelUsageLinker.run();
// }
private Stack<Integer> ifConditionalJumpIndexStack = new Stack<Integer>();
private Stack<Integer> ifJumpIndexStack = new Stack<Integer>();
@Override
public void exitIfStatementCondition(IfStatementConditionContext ctx) {
// After condition is generated, then a conditional jump should be generated
// Leave a spot allocated here and write to it later
int conditionalJumpIndex = instructions.size();
ifConditionalJumpIndexStack.push(conditionalJumpIndex);
instructions.add(null);
}
@Override
public void enterIfStatementOnTrue(IfStatementOnTrueContext ctx) {
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
}
@Override
public void exitIfStatementOnTrue(IfStatementOnTrueContext ctx) {
// After statement on true is generated, then a jump should be generated
// Leave a spot allocated here and write to it later
int jumpIndex = instructions.size();
ifJumpIndexStack.push(jumpIndex);
instructions.add(null);
int conditionalJumpIndex = ifConditionalJumpIndexStack.pop();
// Now, the spot allocated for a conditional jump can be populated
int ifEndIndex = instructions.size();
int jump = ifEndIndex - conditionalJumpIndex;
instructions.set(conditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, jump));
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
}
@Override
public void enterElseStatement(ElseStatementContext ctx) {
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
if(ctx.ifStatementOnFalse() == null)
instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
}
@Override
public void exitElseStatement(ElseStatementContext ctx) {
int jumpIndex = ifJumpIndexStack.pop();
// Now, the spot allocated for a jump can be populated
int elseEndIndex = instructions.size();
int jump = elseEndIndex - jumpIndex;
instructions.set(jumpIndex, new Instruction(Instruction.OPCODE_JUMP, jump));
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
}
private Stack<Integer> whileConditionalJumpIndexStack = new Stack<Integer>();
private Stack<Integer> whileJumpIndexStack = new Stack<Integer>();
@Override
public void enterWhileStatement(WhileStatementContext ctx) {
startBreakable();
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
int jumpIndex = instructions.size();
whileJumpIndexStack.push(jumpIndex);
}
@Override
public void exitWhileStatementCondition(WhileStatementConditionContext ctx) {
int conditionalJumpIndex = instructions.size();
whileConditionalJumpIndexStack.push(conditionalJumpIndex);
instructions.add(null);
}
@Override
public void exitWhileStatementBody(WhileStatementBodyContext ctx) {
int jumpIndex = whileJumpIndexStack.pop();
int whileBodyEndIndex = instructions.size();
int jump = jumpIndex - whileBodyEndIndex;
instructions.add(new Instruction(Instruction.OPCODE_JUMP, jump));
}
@Override
public void exitWhileStatement(WhileStatementContext ctx) {
int whileEndIndex = instructions.size();
int conditionalJumpIndex = whileConditionalJumpIndexStack.pop();
int conditionalJump = whileEndIndex - conditionalJumpIndex;
instructions.set(conditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
endBreakable();
}
private Stack<Integer> forConditionalJumpIndexStack = new Stack<Integer>();
private Stack<Integer> forJumpIndexStack = new Stack<Integer>();
@Override
public void enterForStatement(ForStatementContext ctx) {
startBreakable();
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
}
@Override
public void enterForStatementCondition(ForStatementConditionContext ctx) {
forJumpIndexStack.push(instructions.size());
}
@Override
public void enterForStatementUpdate(ForStatementUpdateContext ctx) {
// Postpone generation of update till after body
walker.suspendWalkWithin(ctx);
}
@Override
public void enterForStatementBody(ForStatementBodyContext ctx) {
int conditionalJumpIndex = instructions.size();
forConditionalJumpIndexStack.push(conditionalJumpIndex);
instructions.add(null);
}
@Override
public void exitForStatement(ForStatementContext ctx) {
ConditionalTreeWalker walker = new ConditionalTreeWalker();
ParseTree updateElement = ctx.forStatementUpdate().delimitedProgramElement();
walker.walk(
createBodyListener(walker, idToParameterOrdinalMap, idToVariableOrdinalMap, instructions, yieldStatements),
updateElement
);
int indexAtCondition = forJumpIndexStack.pop();
int conditionJump = indexAtCondition - instructions.size();
instructions.add(new Instruction(Instruction.OPCODE_JUMP, conditionJump));
int conditionalJumpIndex = forConditionalJumpIndexStack.pop();
int conditionalJump = instructions.size() - conditionalJumpIndex;
instructions.set(conditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
endBreakable();
}
private Stack<Integer> forInConditionalJumpIndexStack = new Stack<Integer>();
private Stack<Integer> forInJumpIndexStack = new Stack<Integer>();
@Override
public void enterForInStatement(ForInStatementContext ctx) {
startBreakable();
idToVariableOrdinalMap = idToVariableOrdinalMap.newInner();
for(ForInStatementVarContext varCtx: ctx.forInStatementVar())
idToVariableOrdinalMap.declare(varCtx.ID().getText());
}
@Override
public void enterForInStatementBody(ForInStatementBodyContext ctx) {
ForInStatementContext forInStatementCtx = (ForInStatementContext)ctx.getParent();
// iterable
instructions.add(new Instruction(Instruction.OPCODE_SEND, "iterator", 0));
// iterator
int jumpIndex = instructions.size();
forInJumpIndexStack.push(jumpIndex);
instructions.add(new Instruction(Instruction.OPCODE_DUP));
// iterator, iterator
instructions.add(new Instruction(Instruction.OPCODE_SEND, "atEnd", 0));
// iterator, bool
int conditionalJumpIndex = instructions.size();
forInConditionalJumpIndexStack.push(conditionalJumpIndex);
instructions.add(null);
// iterator
for(ForInStatementVarContext varCtx: forInStatementCtx.forInStatementVar()) {
// iterator
instructions.add(new Instruction(Instruction.OPCODE_DUP));
// iterator, iterator
instructions.add(new Instruction(Instruction.OPCODE_SEND, "next", 0));
// iterator, next
String id = varCtx.ID().getText();
int ordinal = idToVariableOrdinalMap.ordinalFor(id);
instructions.add(new Instruction(Instruction.OPCODE_STORE_LOC, ordinal));
// iterator
}
// iterator
}
@Override
public void exitForInStatementBody(ForInStatementBodyContext ctx) {
int jumpIndex = forInJumpIndexStack.pop();
int jump = jumpIndex - instructions.size();
instructions.add(new Instruction(Instruction.OPCODE_JUMP, jump));
int conditionalJumpIndex = forInConditionalJumpIndexStack.pop();
int conditionalJump = instructions.size() - conditionalJumpIndex;
instructions.set(conditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_TRUE, conditionalJump));
// iterator
instructions.add(new Instruction(Instruction.OPCODE_POP));
//
}
@Override
public void exitForInStatement(ForInStatementContext ctx) {
idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
endBreakable();
}
@Override
public void enterInterfaceId(InterfaceIdContext ctx) {
String interfaceId = ctx.ID().getText();
instructions.add(new Instruction(Instruction.OPCODE_EXTEND_INTER_ID, interfaceId));
}
@Override
public void exitInterfaceId(InterfaceIdContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SHRINK_INTER_ID));
}
@Override
public void exitMemberAccess(MemberAccessContext ctx) {
String id = ctx.messageId().getText();
instructions.add(new Instruction(Instruction.OPCODE_GET, id));
}
@Override
public void exitIndexAccess(IndexAccessContext ctx) {
instructions.add(new Instruction(Instruction.OPCODE_SEND, "get", 1));
}
@Override
public void exitExplicitMessageExchange(ExplicitMessageExchangeContext ctx) {
int argumentCount = ctx.messageExchange().expression().size();
String id = ctx.messageExchange().messageId().getText();
appendMessageExchange(id, argumentCount);
}
@Override
public void enterMemberAssignment(MemberAssignmentContext ctx) {
// receiver
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN:
case DuroLexer.PROTO_ASSIGN:
break;
default:
String id = ctx.messageId().getText();
// For computed value +=, -=, ...
instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Dup receiver
// receiver, receiver
instructions.add(new Instruction(Instruction.OPCODE_GET, id));
// receiver, oldValue
break;
}
}
@Override
public void exitMemberAssignment(MemberAssignmentContext ctx) {
String id = ctx.messageId().getText();
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN:
// receiver, value
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// value, receiver, value
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
// value
break;
case DuroLexer.PROTO_ASSIGN:
// receiver, value
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// value, receiver, value
instructions.add(new Instruction(Instruction.OPCODE_SET_PROTO, id));
// value
break;
default:
// receiver, oldValue, newValuePart
appendAssignmentReducer(ctx.op);
// receiver, newValue
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// newValue, receiver, newValue
instructions.add(new Instruction(Instruction.OPCODE_SWAP));
// newValue, receiver, id, newValue
instructions.add(new Instruction(Instruction.OPCODE_SET, id));
// newValue
break;
}
}
@Override
public void enterIndexAssignment(IndexAssignmentContext ctx) {
// receiver
if(ctx.op.getType() != DuroLexer.ASSIGN) {
// For computed value +=, -=, ...
instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Dup receiver
// receiver, receiver
ParseTree keyExpression = ctx.indexAssignmentKey().expression();
walker.walk(
createBodyListener(walker, idToParameterOrdinalMap, idToVariableOrdinalMap, instructions, yieldStatements),
keyExpression
);
// receiver, receiver, id
instructions.add(new Instruction(Instruction.OPCODE_DUP1));
// receiver, id, receiver, id
instructions.add(new Instruction(Instruction.OPCODE_SEND, "get", 1));
// receiver, id, oldValue
}
}
@Override
public void enterIndexAssignmentKey(IndexAssignmentKeyContext ctx) {
IndexAssignmentContext computedMemberAssignmentCtx = (IndexAssignmentContext)ctx.getParent();
if(computedMemberAssignmentCtx.op.getType() != DuroLexer.ASSIGN)
walker.suspendWalkWithin(ctx);
}
@Override
public void exitIndexAssignment(IndexAssignmentContext ctx) {
switch(ctx.op.getType()) {
case DuroLexer.ASSIGN:
// receiver, id, value
instructions.add(new Instruction(Instruction.OPCODE_DUP2));
// value, receiver, id, value
instructions.add(new Instruction(Instruction.OPCODE_SEND, "set", 2));
instructions.add(new Instruction(Instruction.OPCODE_POP));
break;
default:
// receiver, id, oldValue, newValuePart
appendAssignmentReducer(ctx.op);
// receiver, id, newValue
instructions.add(new Instruction(Instruction.OPCODE_DUP2));
// newValue, receiver, id, newValue
instructions.add(new Instruction(Instruction.OPCODE_SEND, "set", 2));
instructions.add(new Instruction(Instruction.OPCODE_POP));
// newValue
break;
}
}
private Stack<Integer> programElementCountStack = new Stack<Integer>();
private Stack<Integer> programElementIndexStack = new Stack<Integer>();
@Override
public void enterProgramElements(ProgramElementsContext ctx) {
programElementCountStack.push(ctx.programElementsPart().size());
programElementIndexStack.push(0);
}
@Override
public void enterProgramElementsPart(ProgramElementsPartContext ctx) {
}
@Override
public void exitProgramElementsPart(ProgramElementsPartContext ctx) {
programElementIndexStack.set(programElementIndexStack.size() - 1, programElementIndexStack.peek() + 1);
}
@Override
public void exitProgramElements(ProgramElementsContext ctx) {
programElementCountStack.pop();
programElementIndexStack.pop();
}
@Override
public void enterProgramElement(ProgramElementContext ctx) {
programElementCountStack.push(1);
programElementIndexStack.push(0);
}
@Override
public void exitProgramElement(ProgramElementContext ctx) {
programElementCountStack.pop();
programElementIndexStack.pop();
}
@Override
public void exitTopExpression(TopExpressionContext ctx) {
int programElementCount = programElementCountStack.peek();
int programElementIndex = programElementIndexStack.peek();
if(programElementIndex + 1 < programElementCount)
instructions.add(new Instruction(Instruction.OPCODE_POP));
}
};
}
private static String extractStringLiteral(String rawString) {
return rawString.substring(1, rawString.length() - 1)
.replace("\\n", "\n")
.replace("\\r", "\r")
.replace("\\t", "\t");
}
private BodyInfo getBodyInfo(
OrdinalAllocator idToParameterOrdinalMap, OrdinalAllocator idToVariableOrdinalMap, ParseTree tree) {
ArrayList<Instruction> instructions = new ArrayList<Instruction>();
ArrayList<YieldStatementContext> yieldStatements = new ArrayList<YieldStatementContext>();
ConditionalTreeWalker walker = new ConditionalTreeWalker();
walker.walk(
createBodyListener(walker, idToParameterOrdinalMap, idToVariableOrdinalMap, instructions, yieldStatements),
tree
);
int variableCount = idToVariableOrdinalMap.size();
if(yieldStatements.size() > 0) {
// Generatable/generator
// Function returns iterables
int distinctYieldCount = (int)yieldStatements.stream().map(i -> i.yieldStatementExpression().size()).distinct().count();
if(distinctYieldCount > 1)
throw new RuntimeException("Multiple distinct yield counts.");
ArrayList<Instruction> iteratorInstructions = instructions;
ArrayList<Instruction> generatorInstructions = new ArrayList<Instruction>();
// int[] ordinals = new int[] {idToParameterOrdinalMap.ordinalFor("generator")};
int argumentOffset = idToParameterOrdinalMap.ordinalFor("generator");
int parameterCount = idToParameterOrdinalMap.size();
int closureParameterCount = 1;
Instruction[] bodyInstructions = iteratorInstructions.toArray(new Instruction[iteratorInstructions.size()]);
generatorInstructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS, 1));
// This
generatorInstructions.add(new Instruction(Instruction.OPCODE_GET, "Generatable"));
// Generatable
generatorInstructions.add(new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, variableCount, bodyInstructions));
// Generatable, Behavior
generatorInstructions.add(new Instruction(Instruction.OPCODE_SP_NEW_CLOSURE, argumentOffset, closureParameterCount));
// Generatable, Closure
generatorInstructions.add(new Instruction(Instruction.OPCODE_SEND, "on", 1));
// a generatable
generatorInstructions.add(new Instruction(Instruction.OPCODE_RET, 1));
return new BodyInfo(variableCount, generatorInstructions);
} else
return new BodyInfo(variableCount, instructions);
}
private static class LiteralDuroListener extends DuroBaseListener {
private Object literal;
public Object getLiteral() {
return literal;
}
@Override
public void enterInteger(IntegerContext ctx) {
literal = Integer.parseInt(ctx.INT().getText());
}
@Override
public void enterString(StringContext ctx) {
literal = extractStringLiteral(ctx.STRING_LITERAL().getText());
}
}
private static Object getLiteral(ParseTree tree) {
ParseTreeWalker walker = new ParseTreeWalker();
LiteralDuroListener listener = new LiteralDuroListener();
walker.walk(listener, tree);
return listener.getLiteral();
}
private static class BodyInfo {
private final int localCount;
private final ArrayList<Instruction> instructions;
public BodyInfo(int ordinalCount, ArrayList<Instruction> instructions) {
this.localCount = ordinalCount;
this.instructions = instructions;
}
}
}
| Changed while statements to be compiled as expressions.
Signed-off-by: Jakob Brandsborg Ehmsen <[email protected]> | eclipse/src/duro/reflang/Compiler.java | Changed while statements to be compiled as expressions. | <ide><path>clipse/src/duro/reflang/Compiler.java
<ide> int conditionalJumpIndex = whileConditionalJumpIndexStack.pop();
<ide> int conditionalJump = whileEndIndex - conditionalJumpIndex;
<ide> instructions.set(conditionalJumpIndex, new Instruction(Instruction.OPCODE_IF_FALSE, conditionalJump));
<add>
<add> instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL));
<ide>
<ide> idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter();
<ide> endBreakable(); |
|
Java | apache-2.0 | b3848d6f5c011673f81519e4c7fc71cedc87c5a3 | 0 | bgaudaen/camel,sirlatrom/camel,pax95/camel,onders86/camel,pkletsko/camel,gautric/camel,tkopczynski/camel,zregvart/camel,driseley/camel,cunningt/camel,mgyongyosi/camel,scranton/camel,dmvolod/camel,yuruki/camel,apache/camel,bhaveshdt/camel,kevinearls/camel,apache/camel,mgyongyosi/camel,gilfernandes/camel,scranton/camel,neoramon/camel,cunningt/camel,ullgren/camel,gnodet/camel,driseley/camel,driseley/camel,isavin/camel,lburgazzoli/apache-camel,yuruki/camel,jamesnetherton/camel,tdiesler/camel,Fabryprog/camel,lburgazzoli/apache-camel,tadayosi/camel,apache/camel,anton-k11/camel,pmoerenhout/camel,lburgazzoli/camel,acartapanis/camel,neoramon/camel,jonmcewen/camel,gnodet/camel,NickCis/camel,sverkera/camel,akhettar/camel,alvinkwekel/camel,pkletsko/camel,RohanHart/camel,rmarting/camel,jamesnetherton/camel,veithen/camel,adessaigne/camel,alvinkwekel/camel,rmarting/camel,jamesnetherton/camel,alvinkwekel/camel,anoordover/camel,veithen/camel,sverkera/camel,hqstevenson/camel,gautric/camel,Thopap/camel,tdiesler/camel,tdiesler/camel,mcollovati/camel,kevinearls/camel,NickCis/camel,jkorab/camel,w4tson/camel,Fabryprog/camel,anton-k11/camel,kevinearls/camel,drsquidop/camel,sverkera/camel,jonmcewen/camel,ssharma/camel,christophd/camel,jonmcewen/camel,Thopap/camel,sverkera/camel,gautric/camel,allancth/camel,allancth/camel,acartapanis/camel,anoordover/camel,ullgren/camel,tdiesler/camel,jkorab/camel,nikhilvibhav/camel,davidkarlsen/camel,veithen/camel,driseley/camel,christophd/camel,objectiser/camel,davidkarlsen/camel,sirlatrom/camel,DariusX/camel,mgyongyosi/camel,gautric/camel,neoramon/camel,ssharma/camel,tlehoux/camel,kevinearls/camel,chirino/camel,akhettar/camel,pax95/camel,zregvart/camel,Thopap/camel,bgaudaen/camel,tlehoux/camel,Thopap/camel,nicolaferraro/camel,pkletsko/camel,veithen/camel,christophd/camel,cunningt/camel,pmoerenhout/camel,sabre1041/camel,snurmine/camel,chirino/camel,pax95/camel,isavin/camel,curso007/camel,zregvart/camel,lburgazzoli/camel,allancth/camel,pmoerenhout/camel,pax95/camel,sverkera/camel,jonmcewen/camel,gilfernandes/camel,onders86/camel,snurmine/camel,lburgazzoli/camel,rmarting/camel,prashant2402/camel,punkhorn/camel-upstream,RohanHart/camel,yuruki/camel,gnodet/camel,apache/camel,zregvart/camel,cunningt/camel,tadayosi/camel,lburgazzoli/apache-camel,apache/camel,lburgazzoli/apache-camel,RohanHart/camel,driseley/camel,isavin/camel,akhettar/camel,curso007/camel,w4tson/camel,drsquidop/camel,cunningt/camel,NickCis/camel,w4tson/camel,tadayosi/camel,CodeSmell/camel,jamesnetherton/camel,onders86/camel,anoordover/camel,CodeSmell/camel,chirino/camel,gautric/camel,dmvolod/camel,snurmine/camel,tdiesler/camel,mcollovati/camel,lburgazzoli/camel,Thopap/camel,isavin/camel,adessaigne/camel,tadayosi/camel,nboukhed/camel,drsquidop/camel,nboukhed/camel,tadayosi/camel,dmvolod/camel,drsquidop/camel,NickCis/camel,sabre1041/camel,RohanHart/camel,alvinkwekel/camel,objectiser/camel,veithen/camel,curso007/camel,objectiser/camel,akhettar/camel,drsquidop/camel,adessaigne/camel,sabre1041/camel,anton-k11/camel,sabre1041/camel,kevinearls/camel,rmarting/camel,neoramon/camel,jonmcewen/camel,ssharma/camel,davidkarlsen/camel,jamesnetherton/camel,tkopczynski/camel,punkhorn/camel-upstream,ssharma/camel,tkopczynski/camel,isavin/camel,isavin/camel,scranton/camel,rmarting/camel,yuruki/camel,ssharma/camel,mcollovati/camel,anton-k11/camel,sirlatrom/camel,tdiesler/camel,snurmine/camel,anoordover/camel,mgyongyosi/camel,objectiser/camel,apache/camel,bgaudaen/camel,davidkarlsen/camel,jkorab/camel,lburgazzoli/apache-camel,Fabryprog/camel,punkhorn/camel-upstream,w4tson/camel,onders86/camel,gnodet/camel,sirlatrom/camel,chirino/camel,tkopczynski/camel,bhaveshdt/camel,CodeSmell/camel,pkletsko/camel,tlehoux/camel,gilfernandes/camel,gilfernandes/camel,veithen/camel,pmoerenhout/camel,sirlatrom/camel,tlehoux/camel,lburgazzoli/apache-camel,tkopczynski/camel,ullgren/camel,nicolaferraro/camel,yuruki/camel,adessaigne/camel,jkorab/camel,onders86/camel,christophd/camel,dmvolod/camel,adessaigne/camel,prashant2402/camel,anton-k11/camel,Fabryprog/camel,ullgren/camel,akhettar/camel,salikjan/camel,dmvolod/camel,RohanHart/camel,w4tson/camel,tlehoux/camel,jamesnetherton/camel,bgaudaen/camel,sabre1041/camel,chirino/camel,tlehoux/camel,punkhorn/camel-upstream,pax95/camel,sirlatrom/camel,anoordover/camel,christophd/camel,acartapanis/camel,RohanHart/camel,scranton/camel,bhaveshdt/camel,DariusX/camel,DariusX/camel,jkorab/camel,christophd/camel,bhaveshdt/camel,pkletsko/camel,bgaudaen/camel,Thopap/camel,allancth/camel,acartapanis/camel,curso007/camel,tkopczynski/camel,bhaveshdt/camel,onders86/camel,anoordover/camel,bgaudaen/camel,adessaigne/camel,mgyongyosi/camel,hqstevenson/camel,snurmine/camel,snurmine/camel,neoramon/camel,jkorab/camel,nboukhed/camel,chirino/camel,nikhilvibhav/camel,curso007/camel,anton-k11/camel,pax95/camel,pmoerenhout/camel,nboukhed/camel,prashant2402/camel,lburgazzoli/camel,ssharma/camel,gautric/camel,nikhilvibhav/camel,rmarting/camel,prashant2402/camel,cunningt/camel,bhaveshdt/camel,hqstevenson/camel,dmvolod/camel,prashant2402/camel,NickCis/camel,tadayosi/camel,nboukhed/camel,jonmcewen/camel,salikjan/camel,prashant2402/camel,drsquidop/camel,DariusX/camel,kevinearls/camel,sabre1041/camel,lburgazzoli/camel,nicolaferraro/camel,w4tson/camel,gilfernandes/camel,sverkera/camel,driseley/camel,gilfernandes/camel,neoramon/camel,pmoerenhout/camel,scranton/camel,nboukhed/camel,curso007/camel,pkletsko/camel,hqstevenson/camel,scranton/camel,mgyongyosi/camel,nikhilvibhav/camel,akhettar/camel,acartapanis/camel,acartapanis/camel,yuruki/camel,gnodet/camel,allancth/camel,mcollovati/camel,hqstevenson/camel,NickCis/camel,hqstevenson/camel,nicolaferraro/camel,allancth/camel,CodeSmell/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.spring.boot.issues;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@EnableAutoConfiguration
@SpringBootTest(classes = { SimpleOgnlTest.class })
public class SimpleOgnlTest {
@EndpointInject(uri = "mock:result")
protected MockEndpoint resultEndpoint;
@Produce(uri = "direct:start")
protected ProducerTemplate template;
@Test
public void testSimpleOgnlListExpression() throws Exception {
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
resultEndpoint.expectedBodiesReceived(list.get(0));
template.sendBody(list);
resultEndpoint.assertIsSatisfied();
}
@Configuration
public static class ContextConfig {
@Bean
public RouteBuilder route() {
return new RouteBuilder() {
public void configure() {
from("direct:start").setBody(simple("${body[0]}")).to("mock:result");
}
};
}
}
}
| components/camel-spring-boot/src/test/java/org/apache/camel/spring/boot/issues/SimpleOgnlTest.java | package org.apache.camel.spring.boot.issues;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@EnableAutoConfiguration
@SpringBootTest(classes = {SimpleOgnlTest.class})
public class SimpleOgnlTest {
@EndpointInject(uri = "mock:result")
protected MockEndpoint resultEndpoint;
@Produce(uri = "direct:start")
protected ProducerTemplate template;
@Test
public void testSimpleOgnlListExpression() throws Exception {
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
resultEndpoint.expectedBodiesReceived(list.get(0));
template.sendBody(list);
resultEndpoint.assertIsSatisfied();
}
@Configuration
public static class ContextConfig {
@Bean
public RouteBuilder route() {
return new RouteBuilder() {
public void configure() {
from("direct:start").setBody(simple("${body[0]}")).to("mock:result");
}
};
}
}
}
| CAMEL-10385: fix checkstyle errors | components/camel-spring-boot/src/test/java/org/apache/camel/spring/boot/issues/SimpleOgnlTest.java | CAMEL-10385: fix checkstyle errors | <ide><path>omponents/camel-spring-boot/src/test/java/org/apache/camel/spring/boot/issues/SimpleOgnlTest.java
<add>/**
<add> * Licensed to the Apache Software Foundation (ASF) under one or more
<add> * contributor license agreements. See the NOTICE file distributed with
<add> * this work for additional information regarding copyright ownership.
<add> * The ASF licenses this file to You under the Apache License, Version 2.0
<add> * (the "License"); you may not use this file except in compliance with
<add> * the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<ide> package org.apache.camel.spring.boot.issues;
<ide>
<ide> import java.util.ArrayList;
<ide>
<ide> @RunWith(SpringRunner.class)
<ide> @EnableAutoConfiguration
<del>@SpringBootTest(classes = {SimpleOgnlTest.class})
<add>@SpringBootTest(classes = { SimpleOgnlTest.class })
<ide> public class SimpleOgnlTest {
<ide> @EndpointInject(uri = "mock:result")
<del> protected MockEndpoint resultEndpoint;
<del>
<del> @Produce(uri = "direct:start")
<del> protected ProducerTemplate template;
<del>
<add> protected MockEndpoint resultEndpoint;
<add>
<add> @Produce(uri = "direct:start")
<add> protected ProducerTemplate template;
<add>
<ide> @Test
<del> public void testSimpleOgnlListExpression() throws Exception {
<add> public void testSimpleOgnlListExpression() throws Exception {
<ide> List<String> list = new ArrayList<String>();
<ide> list.add("one");
<ide> list.add("two");
<del>
<del> resultEndpoint.expectedBodiesReceived(list.get(0));
<del>
<del> template.sendBody(list);
<del>
<del> resultEndpoint.assertIsSatisfied();
<del> }
<del>
<add>
<add> resultEndpoint.expectedBodiesReceived(list.get(0));
<add>
<add> template.sendBody(list);
<add>
<add> resultEndpoint.assertIsSatisfied();
<add> }
<add>
<ide> @Configuration
<del> public static class ContextConfig {
<del> @Bean
<del> public RouteBuilder route() {
<del> return new RouteBuilder() {
<del> public void configure() {
<del> from("direct:start").setBody(simple("${body[0]}")).to("mock:result");
<del> }
<del> };
<del> }
<del> }
<add> public static class ContextConfig {
<add> @Bean
<add> public RouteBuilder route() {
<add> return new RouteBuilder() {
<add> public void configure() {
<add> from("direct:start").setBody(simple("${body[0]}")).to("mock:result");
<add> }
<add> };
<add> }
<add> }
<ide> } |
|
JavaScript | mit | fd4fc400690383cd2929ee47401098e9c9674758 | 0 | redxdev/hvzsite,redxdev/hvzsite-next,redxdev/hvzsite,redxdev/hvzsite | var passport = require('passport');
function generateResult(success, message, key) {
if (typeof message === 'object')
message = message.message;
var obj = {success: success, message: message};
if (key)
obj.key = key;
return {
result: JSON.stringify(obj),
origin: process.env.NODE_ENV === 'development' ? '*' : sails.config.hvz.url
}
}
module.exports = {
logout: function (req, res) {
if (!req.isAuthenticated()) {
return res.view('result', generateResult(true, "You aren't logged in!"));
}
req.logout();
return res.view('result', generateResult(true, "You have been logged out."));
},
apiKey: function (req, res) {
var user = req.user;
if (!user) {
return res.unauthorized({message: "You are not logged in!"});
}
else {
return res.ok({key: user.apiKey});
}
},
// Passport Methods
loginGoogle: function (req, res) {
if (req.isAuthenticated()) {
return res.view('result', generateResult(true, "You are already logged in."));
}
passport.authenticate('google', {scope: ['profile', 'email']})(req, res);
},
callbackGoogle: function (req, res) {
passport.authenticate('google', {failureRedirect: '/error'}, function (err, user) {
if (err) {
sails.log.error(err);
return res.view('result', generateResult(false, err));
}
if (!user) {
return res.view('result', generateResult(false, 'There was a problem logging you in. Have you registered?'));
}
req.logIn(user, function (err) {
if (err) {
sails.log.error(err);
return res.view('result', generateResult(false, err));
}
return res.view('result', generateResult(true, 'You have been logged in.', req.user.apiKey));
});
})(req, res);
},
registerGoogle: passport.authenticate('google-register', {scope: ['profile', 'email']}),
callbackRegisterGoogle: function (req, res) {
passport.authenticate('google-register', {failureRedirect: '/error'}, function (err, user) {
if (err) {
sails.log.error(err);
return res.view('result', generateResult(false, err));
}
if (!user) {
return res.view('result', generateResult(false, 'There was a problem creating your account.'));
}
return res.view('result', generateResult(true, 'You have been registered. Go see a moderator to activate your account!'));
})(req, res);
}
}
| server/api/controllers/AuthController.js | var passport = require('passport');
function generateResult(success, message, key) {
if (typeof message === 'object')
message = message.message;
var obj = {success: success, message: message};
if (key)
obj.key = key;
return {
result: JSON.stringify(obj),
origin: sails.config.hvz.url
}
}
module.exports = {
logout: function (req, res) {
if (!req.isAuthenticated()) {
return res.view('result', generateResult(true, "You aren't logged in!"));
}
req.logout();
return res.view('result', generateResult(true, "You have been logged out."));
},
apiKey: function (req, res) {
var user = req.user;
if (!user) {
return res.unauthorized({message: "You are not logged in!"});
}
else {
return res.ok({key: user.apiKey});
}
},
// Passport Methods
loginGoogle: function (req, res) {
if (req.isAuthenticated()) {
return res.view('result', generateResult(true, "You are already logged in."));
}
passport.authenticate('google', {scope: ['profile', 'email']})(req, res);
},
callbackGoogle: function (req, res) {
passport.authenticate('google', {failureRedirect: '/error'}, function (err, user) {
if (err) {
sails.log.error(err);
return res.view('result', generateResult(false, err));
}
if (!user) {
return res.view('result', generateResult(false, 'There was a problem logging you in. Have you registered?'));
}
req.logIn(user, function (err) {
if (err) {
sails.log.error(err);
return res.view('result', generateResult(false, err));
}
return res.view('result', generateResult(true, 'You have been logged in.', req.user.apiKey));
});
})(req, res);
},
registerGoogle: passport.authenticate('google-register', {scope: ['profile', 'email']}),
callbackRegisterGoogle: function (req, res) {
passport.authenticate('google-register', {failureRedirect: '/error'}, function (err, user) {
if (err) {
sails.log.error(err);
return res.view('result', generateResult(false, err));
}
if (!user) {
return res.view('result', generateResult(false, 'There was a problem creating your account.'));
}
return res.view('result', generateResult(true, 'You have been registered. Go see a moderator to activate your account!'));
})(req, res);
}
}
| allow all origins for login in development
| server/api/controllers/AuthController.js | allow all origins for login in development | <ide><path>erver/api/controllers/AuthController.js
<ide>
<ide> return {
<ide> result: JSON.stringify(obj),
<del> origin: sails.config.hvz.url
<add> origin: process.env.NODE_ENV === 'development' ? '*' : sails.config.hvz.url
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | a77f846d5657dd07789b9b48d95abfff3eee859c | 0 | l-ra/openeet-java | package openeet.lite;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class EetResponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String errCode;
private String errText;
private String uuid;
private String bkp;
private String time;
private String fik;
private String test;
private String warnings; // all warnings joined into one string as [code1]
// text1\n[code2] text2...
public EetResponse(String response) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(response, new EetHandler());
}
public EetResponse(File file) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(file, new EetHandler());
}
public boolean isError() {
return errCode != null;
}
public boolean hasWarnings() {
return warnings != null;
}
private class EetHandler extends DefaultHandler {
private String element;
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
element = qName;
if (element.equals("eet:Hlavicka")) {
uuid = attributes.getValue("uuid_zpravy");
bkp = attributes.getValue("bkp");
time = attributes.getValue("dat_prij");
String h = attributes.getValue("dat_odmit");
if (h != null)
time = h;
} else if (element.equals("eet:Potvrzeni")) {
fik = attributes.getValue("fik");
test = attributes.getValue("test");
} else if (element.equals("eet:Chyba")) {
errCode = attributes.getValue("kod");
test = attributes.getValue("test");
} else if (element.equals("eet:Varovani")) {
String code = attributes.getValue("kod_varov");
code = "[" + code + "]";
if (warnings == null)
warnings = code;
else
warnings += "\n" + code;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
element = "";
}
public void characters(char ch[], int start, int length) throws SAXException {
if (element.equals("eet:Chyba"))
errText = createPureString(ch, start, length);
else if (element.equals("eet:Varovani"))
warnings += " " + createPureString(ch, start, length);
}
private String createPureString(char ch[], int start, int length) {
String h = new String(ch, start, length);
h = h.replace('\n', ' ');
h = h.trim();
return h;
}
}
public static void main(String argv[]) {
try {
EetResponse r = new EetResponse(new File("response_test.xml"));
if (r.isError()) {
System.out.println("Err code: " + r.errCode);
System.out.println("Err text: " + r.errText);
}
System.out.println("Time: " + r.time);
System.out.println("Uuid: " + r.uuid);
System.out.println("Bkp: " + r.bkp);
System.out.println("Fik: " + r.fik);
System.out.println("Test: " + r.test);
if (r.hasWarnings())
System.out.println("Warnings:\n" + r.warnings);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| openeet-lite/src/main/java/openeet/lite/EetResponse.java | package openeet.lite;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class EetResponse {
private String errCode;
private String errText;
private String uuid;
private String bkp;
private String time;
private String fik;
private String test;
private String warnings; // all warnings joined into one string as [code1]
// text1\n[code2] text2...
public EetResponse(String response) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(response, new EetHandler());
}
public EetResponse(File file) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(file, new EetHandler());
}
public boolean isError() {
return errCode != null;
}
public boolean hasWarnings() {
return warnings != null;
}
private class EetHandler extends DefaultHandler {
private String element;
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
element = qName;
if (element.equals("eet:Hlavicka")) {
uuid = attributes.getValue("uuid_zpravy");
bkp = attributes.getValue("bkp");
time = attributes.getValue("dat_prij");
String h = attributes.getValue("dat_odmit");
if (h != null)
time = h;
} else if (element.equals("eet:Potvrzeni")) {
fik = attributes.getValue("fik");
test = attributes.getValue("test");
} else if (element.equals("eet:Chyba")) {
errCode = attributes.getValue("kod");
test = attributes.getValue("test");
} else if (element.equals("eet:Varovani")) {
String code = attributes.getValue("kod_varov");
code = "[" + code + "]";
if (warnings == null)
warnings = code;
else
warnings += "\n" + code;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
element = "";
}
public void characters(char ch[], int start, int length) throws SAXException {
if (element.equals("eet:Chyba"))
errText = createPureString(ch, start, length);
else if (element.equals("eet:Varovani"))
warnings += " " + createPureString(ch, start, length);
}
private String createPureString(char ch[], int start, int length) {
String h = new String(ch, start, length);
h = h.replace('\n', ' ');
h = h.trim();
return h;
}
}
public static void main(String argv[]) {
try {
EetResponse r = new EetResponse(new File("response_test.xml"));
if (r.isError()) {
System.out.println("Err code: " + r.errCode);
System.out.println("Err text: " + r.errText);
}
System.out.println("Time: " + r.time);
System.out.println("Uuid: " + r.uuid);
System.out.println("Bkp: " + r.bkp);
System.out.println("Fik: " + r.fik);
System.out.println("Test: " + r.test);
if (r.hasWarnings())
System.out.println("Warnings:\n" + r.warnings);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| EetRespoinse made serializable
| openeet-lite/src/main/java/openeet/lite/EetResponse.java | EetRespoinse made serializable | <ide><path>peneet-lite/src/main/java/openeet/lite/EetResponse.java
<ide>
<ide> import java.io.File;
<ide> import java.io.IOException;
<add>import java.io.Serializable;
<ide>
<ide> import javax.xml.parsers.ParserConfigurationException;
<ide> import javax.xml.parsers.SAXParser;
<ide> import org.xml.sax.SAXException;
<ide> import org.xml.sax.helpers.DefaultHandler;
<ide>
<del>public class EetResponse {
<add>public class EetResponse implements Serializable {
<ide>
<add> /**
<add> *
<add> */
<add> private static final long serialVersionUID = 1L;
<add>
<ide> private String errCode;
<ide> private String errText;
<ide> private String uuid; |
|
JavaScript | mit | aa84c2b3e8fb8bb3be062f93f77c458dea1e8d2b | 0 | pitronalldak/farzad-bot-api | const fs = require('fs');
const readline = require('readline');
const google = require('googleapis');
const googleAuth = require('google-auth-library');
const moment = require('moment');
// test: 15xQEWvKK88W4eALxThmtHIzsdPXFqfYHir8QvjH8Jq0
// origin: 1LOUGqVKIm-crpOjIgTPUY7QlY6ubaSyclRZjqsGUx2U
// dev: 1TAidjIed5goBfdtIk81L955tSx-zyChioCHT2VzkdBg
// v2 dev: 1-ZFmyF-Iz7wyzdMLGEI9IjBbxL9l_FSFG8ogqWLVJc8
const spreadsheet = '1TAidjIed5goBfdtIk81L955tSx-zyChioCHT2VzkdBg';
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
const TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
const TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
// Load client secrets from a local file.
exports.postSpreadSheets = (questions, users, surveys) => fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Sheets API.
authorize(JSON.parse(content), listMajors(questions, users, surveys));
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const clientSecret = credentials.installed.client_secret;
const clientId = credentials.installed.client_id;
const redirectUrl = credentials.installed.redirect_uris[0];
const auth = new googleAuth();
const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function (err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function (code) {
rl.close();
oauth2Client.getToken(code, function (err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Helper mapping count to letter
* It's one-based, so 1 is A, 26 is Z, 27 is AA.
*/
function toLetters(num) {
"use strict";
var mod = num % 26,
pow = num / 26 | 0,
out = mod ? String.fromCharCode(64 + mod) : (--pow, 'Z');
return pow ? toLetters(pow) + out : out;
}
/**
* Print the data in a spreadsheet:
*/
function writeDataToSheets(auth, sheets, users, questions, survey) {
let userList = [];
let columns = [];
let userQuantity = 0;
let questionQuantity = 0;
for (let user of users) {
if (user.survey === survey.id) {
userQuantity++;
let juser = [];
juser.push({
userEnteredValue: {
stringValue: user.telegramId,
}
});
juser.push({
userEnteredValue: {
stringValue: user.date,
}
});
juser.push({
userEnteredValue: {
stringValue: user.username,
}
});
for (let answer of user.answers) {
let answ = '';
if (answer.answerId) {
answ = answer.answerId
} else {
answ = answer.answer
}
juser.push({
userEnteredValue: {
stringValue: answ,
}
});
}
userList.push({
values: juser
});
}
}
userList.sort(function (a, b) {
if (moment().diff(a.values[1].userEnteredValue.stringValue) > moment().diff(b.values[1].userEnteredValue.stringValue)) {
return -1;
}
if (moment().diff(a.values[1].userEnteredValue.stringValue) < moment().diff(b.values[1].userEnteredValue.stringValue)) {
return 1;
}
});
columns.push({
userEnteredValue: {
stringValue: 'telegramId',
}
},
{
userEnteredValue: {
stringValue: 'date',
}
},
{
userEnteredValue: {
stringValue: 'Username',
}
});
for (let q of questions) {
if (q.survey === survey.id) {
questionQuantity++;
columns.push({
userEnteredValue: {
stringValue: q.question,
}
});
}
}
columns.push({
userEnteredValue: {
stringValue: 'total number of questions - ' + questionQuantity,
}
},
{
userEnteredValue: {
stringValue: 'total number of users - ' + userQuantity,
}
});
sheets.spreadsheets.get({
spreadsheetId: spreadsheet,
includeGridData: true,
auth: auth,
}, function (err, receivedSpreadsheet) {
if (err) {
console.log(err);
return;
}
let sheetId = receivedSpreadsheet.sheets.find(sheet => sheet.properties.title === survey.name).properties.sheetId;
let values = [{
values: columns,
}];
userList.forEach(user => values.push(user));
sheets.spreadsheets.batchUpdate({
spreadsheetId: spreadsheet,
resource: {
requests: [{
updateCells: {
fields: '*',
start: {
sheetId: sheetId,
rowIndex: 0,
columnIndex: 0,
},
rows: values,
}
}],
},
auth: auth,
}, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(response);
});
});
}
const listMajors = (questions, users, surveys) => (
(auth) => {
const sheets = google.sheets('v4');
sheets.spreadsheets.get({
spreadsheetId: spreadsheet,
includeGridData: true,
auth: auth,
}, function (err, receivedSpreadsheet) {
if (err) {
console.log(err);
return;
}
surveys.forEach(survey => {
if (!receivedSpreadsheet.sheets.some(sheet => sheet.properties.title === survey.name)) {
sheets.spreadsheets.batchUpdate({
spreadsheetId: spreadsheet,
resource: {
requests: [{
addSheet: {
properties: {
title: survey.name,
},
}
}],
},
auth: auth,
}, function (err, response) {
if (err) {
console.log(err);
return;
}
writeDataToSheets(auth, sheets, users, questions, survey);
})
} else {
writeDataToSheets(auth, sheets, users, questions, survey);
}
});
});
}
); | src/services/google-spreadsheets.js | const fs = require('fs');
const readline = require('readline');
const google = require('googleapis');
const googleAuth = require('google-auth-library');
const moment = require('moment');
// test: 15xQEWvKK88W4eALxThmtHIzsdPXFqfYHir8QvjH8Jq0
// origin: 1LOUGqVKIm-crpOjIgTPUY7QlY6ubaSyclRZjqsGUx2U
// dev: 1TAidjIed5goBfdtIk81L955tSx-zyChioCHT2VzkdBg
// v2 dev: 1-ZFmyF-Iz7wyzdMLGEI9IjBbxL9l_FSFG8ogqWLVJc8
const spreadsheet = '1TAidjIed5goBfdtIk81L955tSx-zyChioCHT2VzkdBg';
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
const TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
const TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
// Load client secrets from a local file.
exports.postSpreadSheets = (questions, users, surveys) => fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Sheets API.
authorize(JSON.parse(content), listMajors(questions, users, surveys));
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const clientSecret = credentials.installed.client_secret;
const clientId = credentials.installed.client_id;
const redirectUrl = credentials.installed.redirect_uris[0];
const auth = new googleAuth();
const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Helper mapping count to letter
* It's one-based, so 1 is A, 26 is Z, 27 is AA.
*/
function toLetters(num) {
"use strict";
var mod = num % 26,
pow = num / 26 | 0,
out = mod ? String.fromCharCode(64 + mod) : (--pow, 'Z');
return pow ? toLetters(pow) + out : out;
}
/**
* Print the data in a spreadsheet:
*/
function writeDataToSheets(users, questions, survey) {
let userList = [];
let columns = [];
let userQuantity = 0;
let questionQuantity = 0;
for (let user of users) {
if (user.survey === survey.name) {
userQuantity++;
let juser = [];
juser.push({
userEnteredValue: {
stringValue: user.telegramId,
}
});
juser.push({
userEnteredValue: {
stringValue: user.date,
}
});
juser.push({
userEnteredValue: {
stringValue: user.username,
}
});
for (let answer of user.answers) {
let answ = '';
if (answer.answerId) {answ = answer.answerId} else {answ = answer.answer}
juser.push({
userEnteredValue: {
stringValue: answ,
}
});
}
userList.push({
values: juser
});
}
}
userList.sort(function (a, b) {
if (moment().diff(a.values[1].userEnteredValue.stringValue) > moment().diff(b.values[1].userEnteredValue.stringValue)) {
return -1;
}
if (moment().diff(a.values[1].userEnteredValue.stringValue) < moment().diff(b.values[1].userEnteredValue.stringValue)) {
return 1;
}
});
columns.push({
userEnteredValue: {
stringValue: 'telegramId',
}
},
{
userEnteredValue: {
stringValue: 'date',
}
},
{
userEnteredValue: {
stringValue: 'Username',
}
});
for (let q of questions) {
if (q.survey === survey.name) {
questionQuantity++;
columns.push({
userEnteredValue: {
stringValue: q.question,
}
});
}
}
columns.push({
userEnteredValue: {
stringValue: 'total number of questions - ' + questionQuantity,
}
},
{
userEnteredValue: {
stringValue: 'total number of users - ' + userQuantity,
}
});
sheets.spreadsheets.get({
spreadsheetId: spreadsheet,
includeGridData: true,
auth: auth,
}, function(err, receivedSpreadsheet) {
if (err) {
console.log(err);
return;
}
let sheetId = receivedSpreadsheet.sheets.find(sheet => sheet.properties.title === survey.name).properties.sheetId;
let values= [{
values: columns,
}];
userList.forEach(user => values.push(user));
sheets.spreadsheets.batchUpdate({
spreadsheetId: spreadsheet,
resource: {
requests: [{
updateCells: {
fields: '*',
start: {
sheetId: sheetId,
rowIndex: 0,
columnIndex: 0,
},
rows: values,
}
}],
},
auth: auth,
}, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(response);
});
});
}
const listMajors = (questions, users, surveys) => (
(auth) => {
const sheets = google.sheets('v4');
sheets.spreadsheets.get({
spreadsheetId: spreadsheet,
includeGridData: true,
auth: auth,
}, function(err, receivedSpreadsheet) {
if (err) {
console.log(err);
return;
}
surveys.forEach(survey => {
if (!receivedSpreadsheet.sheets.some(sheet => sheet.properties.title === survey.name)) {
sheets.spreadsheets.batchUpdate({
spreadsheetId: spreadsheet,
resource: {
requests: [{
addSheet: {
properties: {
title: survey.name,
},
}
}],
},
auth: auth,
}, function(err, response) {
if (err) {
console.log(err);
return;
}
writeDataToSheets(users, questions, survey);
})
} else {
writeDataToSheets(users, questions, survey);
}
});
});
}
); | Fixed google import
| src/services/google-spreadsheets.js | Fixed google import | <ide><path>rc/services/google-spreadsheets.js
<ide> const TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
<ide>
<ide> // Load client secrets from a local file.
<del>exports.postSpreadSheets = (questions, users, surveys) => fs.readFile('client_secret.json', function processClientSecrets(err, content) {
<add>exports.postSpreadSheets = (questions, users, surveys) => fs.readFile('client_secret.json', function processClientSecrets(err, content) {
<ide> if (err) {
<ide> console.log('Error loading client secret file: ' + err);
<ide> return;
<ide> const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
<ide>
<ide> // Check if we have previously stored a token.
<del> fs.readFile(TOKEN_PATH, function(err, token) {
<add> fs.readFile(TOKEN_PATH, function (err, token) {
<ide> if (err) {
<ide> getNewToken(oauth2Client, callback);
<ide> } else {
<ide> input: process.stdin,
<ide> output: process.stdout
<ide> });
<del> rl.question('Enter the code from that page here: ', function(code) {
<add> rl.question('Enter the code from that page here: ', function (code) {
<ide> rl.close();
<del> oauth2Client.getToken(code, function(err, token) {
<add> oauth2Client.getToken(code, function (err, token) {
<ide> if (err) {
<ide> console.log('Error while trying to retrieve access token', err);
<ide> return;
<ide> /**
<ide> * Print the data in a spreadsheet:
<ide> */
<del>function writeDataToSheets(users, questions, survey) {
<add>function writeDataToSheets(auth, sheets, users, questions, survey) {
<ide> let userList = [];
<ide> let columns = [];
<ide> let userQuantity = 0;
<ide> let questionQuantity = 0;
<ide> for (let user of users) {
<del> if (user.survey === survey.name) {
<add> if (user.survey === survey.id) {
<ide> userQuantity++;
<ide> let juser = [];
<ide> juser.push({
<ide> });
<ide> for (let answer of user.answers) {
<ide> let answ = '';
<del> if (answer.answerId) {answ = answer.answerId} else {answ = answer.answer}
<add> if (answer.answerId) {
<add> answ = answer.answerId
<add> } else {
<add> answ = answer.answer
<add> }
<ide> juser.push({
<ide> userEnteredValue: {
<ide> stringValue: answ,
<ide> }
<ide> });
<ide> for (let q of questions) {
<del> if (q.survey === survey.name) {
<add> if (q.survey === survey.id) {
<ide> questionQuantity++;
<ide> columns.push({
<ide> userEnteredValue: {
<ide> spreadsheetId: spreadsheet,
<ide> includeGridData: true,
<ide> auth: auth,
<del> }, function(err, receivedSpreadsheet) {
<add> }, function (err, receivedSpreadsheet) {
<ide> if (err) {
<ide> console.log(err);
<ide> return;
<ide> }
<ide> let sheetId = receivedSpreadsheet.sheets.find(sheet => sheet.properties.title === survey.name).properties.sheetId;
<del> let values= [{
<add> let values = [{
<ide> values: columns,
<ide> }];
<ide> userList.forEach(user => values.push(user));
<ide> spreadsheetId: spreadsheet,
<ide> includeGridData: true,
<ide> auth: auth,
<del> }, function(err, receivedSpreadsheet) {
<add> }, function (err, receivedSpreadsheet) {
<ide> if (err) {
<ide> console.log(err);
<ide> return;
<ide> }],
<ide> },
<ide> auth: auth,
<del> }, function(err, response) {
<add> }, function (err, response) {
<ide> if (err) {
<ide> console.log(err);
<ide> return;
<ide> }
<del> writeDataToSheets(users, questions, survey);
<add> writeDataToSheets(auth, sheets, users, questions, survey);
<ide> })
<ide> } else {
<del> writeDataToSheets(users, questions, survey);
<add> writeDataToSheets(auth, sheets, users, questions, survey);
<ide> }
<ide> });
<ide> }); |
|
Java | mit | 3fe6ed7b78b89606f2375fd2885b61dd6ee0c0ee | 0 | SenolOzer/jenkins,christ66/jenkins,duzifang/my-jenkins,tastatur/jenkins,shahharsh/jenkins,jenkinsci/jenkins,protazy/jenkins,dbroady1/jenkins,protazy/jenkins,samatdav/jenkins,godfath3r/jenkins,ns163/jenkins,everyonce/jenkins,Jimilian/jenkins,jpederzolli/jenkins-1,jzjzjzj/jenkins,gorcz/jenkins,guoxu0514/jenkins,brunocvcunha/jenkins,intelchen/jenkins,guoxu0514/jenkins,SenolOzer/jenkins,khmarbaise/jenkins,rashmikanta-1984/jenkins,oleg-nenashev/jenkins,aquarellian/jenkins,evernat/jenkins,godfath3r/jenkins,amruthsoft9/Jenkis,dennisjlee/jenkins,KostyaSha/jenkins,luoqii/jenkins,AustinKwang/jenkins,soenter/jenkins,arunsingh/jenkins,goldchang/jenkins,scoheb/jenkins,pjanouse/jenkins,verbitan/jenkins,rlugojr/jenkins,6WIND/jenkins,deadmoose/jenkins,yonglehou/jenkins,dariver/jenkins,bpzhang/jenkins,iqstack/jenkins,rlugojr/jenkins,v1v/jenkins,rlugojr/jenkins,my7seven/jenkins,wuwen5/jenkins,singh88/jenkins,brunocvcunha/jenkins,lilyJi/jenkins,hemantojhaa/jenkins,292388900/jenkins,vjuranek/jenkins,Vlatombe/jenkins,jpederzolli/jenkins-1,mdonohue/jenkins,aquarellian/jenkins,huybrechts/hudson,akshayabd/jenkins,hplatou/jenkins,arunsingh/jenkins,DoctorQ/jenkins,hashar/jenkins,github-api-test-org/jenkins,samatdav/jenkins,scoheb/jenkins,stephenc/jenkins,Wilfred/jenkins,vvv444/jenkins,my7seven/jenkins,NehemiahMi/jenkins,hplatou/jenkins,vjuranek/jenkins,jhoblitt/jenkins,ndeloof/jenkins,Wilfred/jenkins,stephenc/jenkins,tastatur/jenkins,damianszczepanik/jenkins,bkmeneguello/jenkins,paulwellnerbou/jenkins,jpederzolli/jenkins-1,jk47/jenkins,jcsirot/jenkins,goldchang/jenkins,chbiel/jenkins,luoqii/jenkins,scoheb/jenkins,jhoblitt/jenkins,jcarrothers-sap/jenkins,viqueen/jenkins,tangkun75/jenkins,liupugong/jenkins,synopsys-arc-oss/jenkins,mdonohue/jenkins,hashar/jenkins,jpbriend/jenkins,pselle/jenkins,jpbriend/jenkins,MadsNielsen/jtemp,arcivanov/jenkins,v1v/jenkins,kohsuke/hudson,varmenise/jenkins,paulwellnerbou/jenkins,varmenise/jenkins,nandan4/Jenkins,v1v/jenkins,jk47/jenkins,jglick/jenkins,lilyJi/jenkins,ChrisA89/jenkins,AustinKwang/jenkins,singh88/jenkins,jpederzolli/jenkins-1,amruthsoft9/Jenkis,singh88/jenkins,Ykus/jenkins,christ66/jenkins,batmat/jenkins,tangkun75/jenkins,ajshastri/jenkins,mattclark/jenkins,luoqii/jenkins,wuwen5/jenkins,iqstack/jenkins,rashmikanta-1984/jenkins,synopsys-arc-oss/jenkins,dbroady1/jenkins,vlajos/jenkins,tfennelly/jenkins,albers/jenkins,CodeShane/jenkins,escoem/jenkins,NehemiahMi/jenkins,oleg-nenashev/jenkins,protazy/jenkins,vijayto/jenkins,keyurpatankar/hudson,gusreiber/jenkins,FarmGeek4Life/jenkins,chbiel/jenkins,stephenc/jenkins,vijayto/jenkins,jpederzolli/jenkins-1,godfath3r/jenkins,nandan4/Jenkins,akshayabd/jenkins,ChrisA89/jenkins,huybrechts/hudson,azweb76/jenkins,aldaris/jenkins,wuwen5/jenkins,evernat/jenkins,ndeloof/jenkins,goldchang/jenkins,soenter/jenkins,morficus/jenkins,deadmoose/jenkins,chbiel/jenkins,vvv444/jenkins,mrooney/jenkins,Jimilian/jenkins,andresrc/jenkins,AustinKwang/jenkins,hplatou/jenkins,aldaris/jenkins,Vlatombe/jenkins,bpzhang/jenkins,batmat/jenkins,amruthsoft9/Jenkis,morficus/jenkins,wangyikai/jenkins,paulmillar/jenkins,daspilker/jenkins,gitaccountforprashant/gittest,Jimilian/jenkins,KostyaSha/jenkins,ErikVerheul/jenkins,Wilfred/jenkins,jzjzjzj/jenkins,jglick/jenkins,Jochen-A-Fuerbacher/jenkins,ChrisA89/jenkins,akshayabd/jenkins,lilyJi/jenkins,ndeloof/jenkins,svanoort/jenkins,viqueen/jenkins,gorcz/jenkins,yonglehou/jenkins,huybrechts/hudson,MarkEWaite/jenkins,hemantojhaa/jenkins,samatdav/jenkins,AustinKwang/jenkins,KostyaSha/jenkins,Krasnyanskiy/jenkins,christ66/jenkins,goldchang/jenkins,ajshastri/jenkins,amuniz/jenkins,fbelzunc/jenkins,rsandell/jenkins,gusreiber/jenkins,nandan4/Jenkins,mcanthony/jenkins,aldaris/jenkins,DanielWeber/jenkins,azweb76/jenkins,csimons/jenkins,dennisjlee/jenkins,wuwen5/jenkins,brunocvcunha/jenkins,ikedam/jenkins,amruthsoft9/Jenkis,morficus/jenkins,Jimilian/jenkins,rsandell/jenkins,escoem/jenkins,nandan4/Jenkins,bkmeneguello/jenkins,alvarolobato/jenkins,jpbriend/jenkins,patbos/jenkins,rashmikanta-1984/jenkins,my7seven/jenkins,tfennelly/jenkins,recena/jenkins,synopsys-arc-oss/jenkins,Ykus/jenkins,andresrc/jenkins,MichaelPranovich/jenkins_sc,alvarolobato/jenkins,KostyaSha/jenkins,arcivanov/jenkins,h4ck3rm1k3/jenkins,olivergondza/jenkins,pjanouse/jenkins,goldchang/jenkins,maikeffi/hudson,albers/jenkins,evernat/jenkins,vjuranek/jenkins,FarmGeek4Life/jenkins,jzjzjzj/jenkins,batmat/jenkins,synopsys-arc-oss/jenkins,rsandell/jenkins,h4ck3rm1k3/jenkins,dariver/jenkins,batmat/jenkins,fbelzunc/jenkins,msrb/jenkins,lordofthejars/jenkins,daspilker/jenkins,intelchen/jenkins,jcsirot/jenkins,AustinKwang/jenkins,svanoort/jenkins,goldchang/jenkins,aduprat/jenkins,lordofthejars/jenkins,FarmGeek4Life/jenkins,scoheb/jenkins,Vlatombe/jenkins,ikedam/jenkins,CodeShane/jenkins,DoctorQ/jenkins,pselle/jenkins,ns163/jenkins,patbos/jenkins,akshayabd/jenkins,bpzhang/jenkins,paulwellnerbou/jenkins,FTG-003/jenkins,mrooney/jenkins,recena/jenkins,KostyaSha/jenkins,vjuranek/jenkins,petermarcoen/jenkins,jenkinsci/jenkins,keyurpatankar/hudson,chbiel/jenkins,viqueen/jenkins,vijayto/jenkins,everyonce/jenkins,DanielWeber/jenkins,github-api-test-org/jenkins,jcsirot/jenkins,DoctorQ/jenkins,verbitan/jenkins,h4ck3rm1k3/jenkins,arcivanov/jenkins,singh88/jenkins,jpbriend/jenkins,amuniz/jenkins,thomassuckow/jenkins,jglick/jenkins,1and1/jenkins,SebastienGllmt/jenkins,seanlin816/jenkins,andresrc/jenkins,ydubreuil/jenkins,mattclark/jenkins,khmarbaise/jenkins,jk47/jenkins,aldaris/jenkins,6WIND/jenkins,292388900/jenkins,protazy/jenkins,varmenise/jenkins,vjuranek/jenkins,dariver/jenkins,seanlin816/jenkins,damianszczepanik/jenkins,jzjzjzj/jenkins,FTG-003/jenkins,gorcz/jenkins,wuwen5/jenkins,github-api-test-org/jenkins,dbroady1/jenkins,6WIND/jenkins,daniel-beck/jenkins,ErikVerheul/jenkins,h4ck3rm1k3/jenkins,chbiel/jenkins,Krasnyanskiy/jenkins,kzantow/jenkins,ndeloof/jenkins,albers/jenkins,jpbriend/jenkins,jglick/jenkins,dariver/jenkins,vvv444/jenkins,Jochen-A-Fuerbacher/jenkins,oleg-nenashev/jenkins,FarmGeek4Life/jenkins,rashmikanta-1984/jenkins,gusreiber/jenkins,shahharsh/jenkins,wangyikai/jenkins,aquarellian/jenkins,vvv444/jenkins,recena/jenkins,yonglehou/jenkins,SebastienGllmt/jenkins,elkingtonmcb/jenkins,arcivanov/jenkins,csimons/jenkins,AustinKwang/jenkins,shahharsh/jenkins,aquarellian/jenkins,lindzh/jenkins,elkingtonmcb/jenkins,yonglehou/jenkins,amruthsoft9/Jenkis,nandan4/Jenkins,vvv444/jenkins,rsandell/jenkins,paulmillar/jenkins,Jimilian/jenkins,bkmeneguello/jenkins,csimons/jenkins,escoem/jenkins,stephenc/jenkins,thomassuckow/jenkins,arcivanov/jenkins,hemantojhaa/jenkins,amuniz/jenkins,patbos/jenkins,singh88/jenkins,thomassuckow/jenkins,synopsys-arc-oss/jenkins,brunocvcunha/jenkins,escoem/jenkins,wuwen5/jenkins,damianszczepanik/jenkins,daniel-beck/jenkins,pjanouse/jenkins,ydubreuil/jenkins,paulwellnerbou/jenkins,1and1/jenkins,ikedam/jenkins,soenter/jenkins,jzjzjzj/jenkins,mcanthony/jenkins,thomassuckow/jenkins,thomassuckow/jenkins,soenter/jenkins,MarkEWaite/jenkins,noikiy/jenkins,deadmoose/jenkins,jhoblitt/jenkins,daspilker/jenkins,h4ck3rm1k3/jenkins,seanlin816/jenkins,shahharsh/jenkins,dennisjlee/jenkins,liorhson/jenkins,csimons/jenkins,wangyikai/jenkins,ErikVerheul/jenkins,mcanthony/jenkins,intelchen/jenkins,github-api-test-org/jenkins,MichaelPranovich/jenkins_sc,mdonohue/jenkins,gorcz/jenkins,tastatur/jenkins,kzantow/jenkins,maikeffi/hudson,alvarolobato/jenkins,kzantow/jenkins,Vlatombe/jenkins,gitaccountforprashant/gittest,sathiya-mit/jenkins,dariver/jenkins,aduprat/jenkins,viqueen/jenkins,ikedam/jenkins,vlajos/jenkins,gusreiber/jenkins,tastatur/jenkins,ns163/jenkins,tastatur/jenkins,amuniz/jenkins,SenolOzer/jenkins,ndeloof/jenkins,amruthsoft9/Jenkis,CodeShane/jenkins,MichaelPranovich/jenkins_sc,SebastienGllmt/jenkins,duzifang/my-jenkins,maikeffi/hudson,jk47/jenkins,paulmillar/jenkins,kohsuke/hudson,svanoort/jenkins,SenolOzer/jenkins,ChrisA89/jenkins,Krasnyanskiy/jenkins,jenkinsci/jenkins,ChrisA89/jenkins,tfennelly/jenkins,arunsingh/jenkins,MichaelPranovich/jenkins_sc,luoqii/jenkins,ErikVerheul/jenkins,aldaris/jenkins,hemantojhaa/jenkins,khmarbaise/jenkins,aquarellian/jenkins,wuwen5/jenkins,CodeShane/jenkins,oleg-nenashev/jenkins,h4ck3rm1k3/jenkins,noikiy/jenkins,oleg-nenashev/jenkins,christ66/jenkins,rsandell/jenkins,mrooney/jenkins,alvarolobato/jenkins,kzantow/jenkins,MichaelPranovich/jenkins_sc,Jochen-A-Fuerbacher/jenkins,ndeloof/jenkins,jcsirot/jenkins,bpzhang/jenkins,deadmoose/jenkins,akshayabd/jenkins,maikeffi/hudson,shahharsh/jenkins,bpzhang/jenkins,ChrisA89/jenkins,aquarellian/jenkins,liorhson/jenkins,maikeffi/hudson,pjanouse/jenkins,hashar/jenkins,iqstack/jenkins,daniel-beck/jenkins,hplatou/jenkins,Ykus/jenkins,CodeShane/jenkins,everyonce/jenkins,Krasnyanskiy/jenkins,mcanthony/jenkins,elkingtonmcb/jenkins,stephenc/jenkins,liorhson/jenkins,fbelzunc/jenkins,github-api-test-org/jenkins,jcarrothers-sap/jenkins,daspilker/jenkins,mrooney/jenkins,nandan4/Jenkins,azweb76/jenkins,sathiya-mit/jenkins,escoem/jenkins,kohsuke/hudson,everyonce/jenkins,gorcz/jenkins,mattclark/jenkins,Jochen-A-Fuerbacher/jenkins,wangyikai/jenkins,vlajos/jenkins,synopsys-arc-oss/jenkins,v1v/jenkins,huybrechts/hudson,recena/jenkins,aldaris/jenkins,h4ck3rm1k3/jenkins,christ66/jenkins,akshayabd/jenkins,MadsNielsen/jtemp,amruthsoft9/Jenkis,mrooney/jenkins,varmenise/jenkins,ydubreuil/jenkins,vjuranek/jenkins,mrooney/jenkins,noikiy/jenkins,godfath3r/jenkins,FTG-003/jenkins,jenkinsci/jenkins,liorhson/jenkins,tangkun75/jenkins,gusreiber/jenkins,ajshastri/jenkins,vijayto/jenkins,SebastienGllmt/jenkins,gitaccountforprashant/gittest,liorhson/jenkins,DanielWeber/jenkins,svanoort/jenkins,hplatou/jenkins,vlajos/jenkins,deadmoose/jenkins,sathiya-mit/jenkins,synopsys-arc-oss/jenkins,arunsingh/jenkins,noikiy/jenkins,msrb/jenkins,aduprat/jenkins,aldaris/jenkins,rsandell/jenkins,MichaelPranovich/jenkins_sc,varmenise/jenkins,varmenise/jenkins,evernat/jenkins,SebastienGllmt/jenkins,ydubreuil/jenkins,arunsingh/jenkins,ajshastri/jenkins,kohsuke/hudson,rlugojr/jenkins,olivergondza/jenkins,guoxu0514/jenkins,hashar/jenkins,jk47/jenkins,lordofthejars/jenkins,jenkinsci/jenkins,v1v/jenkins,fbelzunc/jenkins,daspilker/jenkins,batmat/jenkins,MadsNielsen/jtemp,dennisjlee/jenkins,andresrc/jenkins,kohsuke/hudson,intelchen/jenkins,AustinKwang/jenkins,paulmillar/jenkins,paulwellnerbou/jenkins,andresrc/jenkins,hemantojhaa/jenkins,github-api-test-org/jenkins,huybrechts/hudson,elkingtonmcb/jenkins,mattclark/jenkins,oleg-nenashev/jenkins,guoxu0514/jenkins,bkmeneguello/jenkins,recena/jenkins,dennisjlee/jenkins,liupugong/jenkins,soenter/jenkins,maikeffi/hudson,brunocvcunha/jenkins,NehemiahMi/jenkins,daniel-beck/jenkins,jpbriend/jenkins,hashar/jenkins,MarkEWaite/jenkins,verbitan/jenkins,rsandell/jenkins,scoheb/jenkins,yonglehou/jenkins,olivergondza/jenkins,gitaccountforprashant/gittest,wangyikai/jenkins,liorhson/jenkins,jzjzjzj/jenkins,jk47/jenkins,FTG-003/jenkins,aduprat/jenkins,noikiy/jenkins,tangkun75/jenkins,csimons/jenkins,chbiel/jenkins,sathiya-mit/jenkins,protazy/jenkins,liupugong/jenkins,keyurpatankar/hudson,samatdav/jenkins,brunocvcunha/jenkins,hashar/jenkins,NehemiahMi/jenkins,tfennelly/jenkins,msrb/jenkins,ikedam/jenkins,lindzh/jenkins,rashmikanta-1984/jenkins,pjanouse/jenkins,scoheb/jenkins,ikedam/jenkins,Vlatombe/jenkins,FarmGeek4Life/jenkins,vlajos/jenkins,MarkEWaite/jenkins,gorcz/jenkins,kohsuke/hudson,soenter/jenkins,pselle/jenkins,verbitan/jenkins,patbos/jenkins,duzifang/my-jenkins,lilyJi/jenkins,tfennelly/jenkins,Ykus/jenkins,DanielWeber/jenkins,csimons/jenkins,vlajos/jenkins,keyurpatankar/hudson,tastatur/jenkins,6WIND/jenkins,daniel-beck/jenkins,jpbriend/jenkins,batmat/jenkins,samatdav/jenkins,jcarrothers-sap/jenkins,292388900/jenkins,morficus/jenkins,everyonce/jenkins,ydubreuil/jenkins,jcsirot/jenkins,dennisjlee/jenkins,1and1/jenkins,dariver/jenkins,petermarcoen/jenkins,albers/jenkins,keyurpatankar/hudson,MichaelPranovich/jenkins_sc,SenolOzer/jenkins,sathiya-mit/jenkins,elkingtonmcb/jenkins,arcivanov/jenkins,kzantow/jenkins,brunocvcunha/jenkins,pselle/jenkins,aduprat/jenkins,olivergondza/jenkins,FTG-003/jenkins,kzantow/jenkins,liorhson/jenkins,jhoblitt/jenkins,intelchen/jenkins,6WIND/jenkins,recena/jenkins,liupugong/jenkins,lilyJi/jenkins,amuniz/jenkins,lilyJi/jenkins,maikeffi/hudson,arcivanov/jenkins,guoxu0514/jenkins,Jochen-A-Fuerbacher/jenkins,292388900/jenkins,Jimilian/jenkins,dbroady1/jenkins,patbos/jenkins,jcarrothers-sap/jenkins,petermarcoen/jenkins,bkmeneguello/jenkins,dennisjlee/jenkins,duzifang/my-jenkins,morficus/jenkins,gitaccountforprashant/gittest,SebastienGllmt/jenkins,singh88/jenkins,yonglehou/jenkins,my7seven/jenkins,ErikVerheul/jenkins,vvv444/jenkins,wangyikai/jenkins,thomassuckow/jenkins,seanlin816/jenkins,1and1/jenkins,godfath3r/jenkins,vvv444/jenkins,vjuranek/jenkins,SenolOzer/jenkins,ajshastri/jenkins,vijayto/jenkins,lordofthejars/jenkins,paulmillar/jenkins,292388900/jenkins,viqueen/jenkins,hemantojhaa/jenkins,KostyaSha/jenkins,jenkinsci/jenkins,daspilker/jenkins,DoctorQ/jenkins,paulwellnerbou/jenkins,dbroady1/jenkins,jglick/jenkins,wangyikai/jenkins,intelchen/jenkins,azweb76/jenkins,gorcz/jenkins,DoctorQ/jenkins,msrb/jenkins,evernat/jenkins,msrb/jenkins,292388900/jenkins,elkingtonmcb/jenkins,Krasnyanskiy/jenkins,deadmoose/jenkins,sathiya-mit/jenkins,duzifang/my-jenkins,albers/jenkins,shahharsh/jenkins,Wilfred/jenkins,alvarolobato/jenkins,verbitan/jenkins,mcanthony/jenkins,tangkun75/jenkins,DoctorQ/jenkins,bpzhang/jenkins,soenter/jenkins,lilyJi/jenkins,jhoblitt/jenkins,mattclark/jenkins,jcarrothers-sap/jenkins,MadsNielsen/jtemp,pjanouse/jenkins,lordofthejars/jenkins,Ykus/jenkins,azweb76/jenkins,stephenc/jenkins,keyurpatankar/hudson,pselle/jenkins,NehemiahMi/jenkins,FarmGeek4Life/jenkins,CodeShane/jenkins,akshayabd/jenkins,damianszczepanik/jenkins,stephenc/jenkins,sathiya-mit/jenkins,vijayto/jenkins,arunsingh/jenkins,MadsNielsen/jtemp,morficus/jenkins,singh88/jenkins,liupugong/jenkins,azweb76/jenkins,my7seven/jenkins,ns163/jenkins,godfath3r/jenkins,1and1/jenkins,shahharsh/jenkins,lindzh/jenkins,Ykus/jenkins,mrooney/jenkins,samatdav/jenkins,mdonohue/jenkins,bkmeneguello/jenkins,svanoort/jenkins,Wilfred/jenkins,ikedam/jenkins,DanielWeber/jenkins,jpederzolli/jenkins-1,everyonce/jenkins,Vlatombe/jenkins,v1v/jenkins,amuniz/jenkins,rlugojr/jenkins,protazy/jenkins,DoctorQ/jenkins,ChrisA89/jenkins,SenolOzer/jenkins,pselle/jenkins,MarkEWaite/jenkins,kzantow/jenkins,hemantojhaa/jenkins,ErikVerheul/jenkins,fbelzunc/jenkins,petermarcoen/jenkins,seanlin816/jenkins,tangkun75/jenkins,ajshastri/jenkins,msrb/jenkins,guoxu0514/jenkins,lindzh/jenkins,duzifang/my-jenkins,bpzhang/jenkins,damianszczepanik/jenkins,khmarbaise/jenkins,vijayto/jenkins,kohsuke/hudson,vlajos/jenkins,1and1/jenkins,andresrc/jenkins,everyonce/jenkins,lindzh/jenkins,andresrc/jenkins,azweb76/jenkins,Ykus/jenkins,MarkEWaite/jenkins,samatdav/jenkins,svanoort/jenkins,patbos/jenkins,rashmikanta-1984/jenkins,damianszczepanik/jenkins,yonglehou/jenkins,aquarellian/jenkins,verbitan/jenkins,hplatou/jenkins,petermarcoen/jenkins,jcarrothers-sap/jenkins,lordofthejars/jenkins,MadsNielsen/jtemp,aduprat/jenkins,rlugojr/jenkins,DanielWeber/jenkins,luoqii/jenkins,gusreiber/jenkins,my7seven/jenkins,Jimilian/jenkins,paulmillar/jenkins,daniel-beck/jenkins,6WIND/jenkins,patbos/jenkins,maikeffi/hudson,elkingtonmcb/jenkins,huybrechts/hudson,Jochen-A-Fuerbacher/jenkins,ns163/jenkins,gitaccountforprashant/gittest,aduprat/jenkins,tfennelly/jenkins,deadmoose/jenkins,pjanouse/jenkins,mdonohue/jenkins,gusreiber/jenkins,christ66/jenkins,jhoblitt/jenkins,lindzh/jenkins,arunsingh/jenkins,daniel-beck/jenkins,ydubreuil/jenkins,intelchen/jenkins,tastatur/jenkins,albers/jenkins,msrb/jenkins,jenkinsci/jenkins,DoctorQ/jenkins,huybrechts/hudson,shahharsh/jenkins,ajshastri/jenkins,amuniz/jenkins,MadsNielsen/jtemp,petermarcoen/jenkins,mcanthony/jenkins,ydubreuil/jenkins,lordofthejars/jenkins,MarkEWaite/jenkins,jzjzjzj/jenkins,mattclark/jenkins,keyurpatankar/hudson,svanoort/jenkins,seanlin816/jenkins,mcanthony/jenkins,lindzh/jenkins,goldchang/jenkins,v1v/jenkins,thomassuckow/jenkins,liupugong/jenkins,petermarcoen/jenkins,seanlin816/jenkins,olivergondza/jenkins,rlugojr/jenkins,liupugong/jenkins,nandan4/Jenkins,jglick/jenkins,fbelzunc/jenkins,noikiy/jenkins,rashmikanta-1984/jenkins,github-api-test-org/jenkins,khmarbaise/jenkins,evernat/jenkins,ErikVerheul/jenkins,oleg-nenashev/jenkins,khmarbaise/jenkins,KostyaSha/jenkins,Wilfred/jenkins,alvarolobato/jenkins,olivergondza/jenkins,292388900/jenkins,goldchang/jenkins,hplatou/jenkins,FTG-003/jenkins,evernat/jenkins,jcarrothers-sap/jenkins,iqstack/jenkins,rsandell/jenkins,kohsuke/hudson,noikiy/jenkins,recena/jenkins,Jochen-A-Fuerbacher/jenkins,dariver/jenkins,khmarbaise/jenkins,viqueen/jenkins,mdonohue/jenkins,iqstack/jenkins,DanielWeber/jenkins,ns163/jenkins,batmat/jenkins,jhoblitt/jenkins,ndeloof/jenkins,jk47/jenkins,NehemiahMi/jenkins,verbitan/jenkins,iqstack/jenkins,luoqii/jenkins,Wilfred/jenkins,guoxu0514/jenkins,escoem/jenkins,ns163/jenkins,scoheb/jenkins,dbroady1/jenkins,ikedam/jenkins,godfath3r/jenkins,jenkinsci/jenkins,gitaccountforprashant/gittest,my7seven/jenkins,github-api-test-org/jenkins,daniel-beck/jenkins,escoem/jenkins,1and1/jenkins,pselle/jenkins,jcarrothers-sap/jenkins,olivergondza/jenkins,tangkun75/jenkins,iqstack/jenkins,damianszczepanik/jenkins,Vlatombe/jenkins,6WIND/jenkins,duzifang/my-jenkins,paulmillar/jenkins,Krasnyanskiy/jenkins,mattclark/jenkins,fbelzunc/jenkins,SebastienGllmt/jenkins,albers/jenkins,CodeShane/jenkins,tfennelly/jenkins,jcsirot/jenkins,FarmGeek4Life/jenkins,chbiel/jenkins,bkmeneguello/jenkins,luoqii/jenkins,jglick/jenkins,hashar/jenkins,MarkEWaite/jenkins,NehemiahMi/jenkins,viqueen/jenkins,Krasnyanskiy/jenkins,daspilker/jenkins,jcsirot/jenkins,gorcz/jenkins,csimons/jenkins,christ66/jenkins,FTG-003/jenkins,paulwellnerbou/jenkins,varmenise/jenkins,protazy/jenkins,jpederzolli/jenkins-1,keyurpatankar/hudson,mdonohue/jenkins,dbroady1/jenkins,KostyaSha/jenkins,jzjzjzj/jenkins,morficus/jenkins,alvarolobato/jenkins,damianszczepanik/jenkins | /*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* 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 jenkins.model;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.init.*;
import hudson.model.LoadStatistics;
import hudson.model.Messages;
import hudson.model.Node;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.ModifiableViewGroup;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.ManagementLink;
import hudson.model.NoFingerprintMatch;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.Descriptor.FormException;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.model.Queue;
import hudson.model.WorkspaceCleanupThread;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.markup.MarkupFormatter;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import static hudson.Util.fixEmpty;
import static hudson.Util.fixNull;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.lifecycle.Lifecycle;
import hudson.logging.LogRecorderManager;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.markup.RawHtmlMarkupFormatter;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.StreamTaskListener;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import static hudson.init.InitMilestone.*;
import hudson.security.BasicAuthenticationFilter;
import hudson.util.NamingThreadFactory;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import static java.util.logging.Level.SEVERE;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements ModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Hudson whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Hudson.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Hudson.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Hudson system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Set of installed cluster nodes.
* <p>
* We use this field with copy-on-write semantics.
* This field has mutable list (to keep the serialization look clean),
* but it shall never be modified. Only new completely populated slave
* list can be set here.
* <p>
* The field name should be really {@code nodes}, but again the backward compatibility
* prevents us from renaming.
*/
protected volatile NodeList slaves;
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Hudson.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
/**
* Send the browser to the config page.
* use View to trim view/{default-view} from URL if possible
*/
@Override
protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException {
String redirect = result.getUrl()+"configure";
List<Ancestor> ancestors = req.getAncestors();
for (int i = ancestors.size() - 1; i >= 0; i--) {
Object o = ancestors.get(i).getObject();
if (o instanceof View) {
redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect;
break;
}
}
return redirect;
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public Jenkins getInstance() {
return theInstance;
}
};
@CLIResolver
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c,StreamTaskListener.fromStdout());
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Hudson.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Hudson by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() throws IOException {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/**
* Gets all the installed {@link SCMListener}s.
*/
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public MarkupFormatter getMarkupFormatter() {
return markupFormatter!=null ? markupFormatter : RawHtmlMarkupFormatter.INSTANCE;
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Hudson.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Hudson.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Hudson forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
final Collator collator = Collator.getInstance();
public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return collator.compare(lhs.getDisplayName(), rhs.getDisplayName());
}
});
return r;
}
@CLIResolver
public Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Hudson.
*/
public @CheckForNull Node getNode(String name) {
return slaves.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return slaves;
}
/**
* Adds one more {@link Node} to Hudson.
*/
public synchronized void addNode(Node n) throws IOException {
if(n==null) throw new IllegalArgumentException();
ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
if(!nl.contains(n)) // defensive check
nl.add(n);
setNodes(nl);
}
/**
* Removes a {@link Node} from Hudson.
*/
public synchronized void removeNode(@Nonnull Node n) throws IOException {
Computer c = n.toComputer();
if (c!=null)
c.disconnect(OfflineCause.create(Messages._Hudson_NodeBeingRemoved()));
ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
nl.remove(n);
setNodes(nl);
}
public void setNodes(List<? extends Node> nodes) throws IOException {
this.slaves = new NodeList(nodes);
updateComputerList();
trimLabels();
save();
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
private void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
public String getDisplayName() {
return "";
}
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
if (!value.contains("${")) {
File d = new File(value);
if (!d.isDirectory() && (d.getParentFile() == null || !d.getParentFile().canWrite())) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
// TODO failure to use either ITEM_* variable might be an error too?
}
return FormValidation.ok(); // TODO assumes it will be OK after substitution, but can we be sure?
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return views; }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins,
* such as "http://localhost/jenkins/".
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link StaplerRequest#getRootPath()}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return
* This method returns null if this parameter is not configured by the user.
* The caller must gracefully deal with this situation.
* The returned URL will always have the trailing '/'.
* @since 1.66
* @see Descriptor#getCheckUrl(String)
* @see #getRootUrlFromRequest()
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Hudson top page, such as "http://localhost/hudson/".
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy (e.g. when user has switched off ProxyPreserveHost, which is
* default setup or the actual url uses https) and you should use getRootUrl if
* you want to be sure you reflect user setup.
* See https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache
*
* @since 1.263
*/
public String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
StringBuilder buf = new StringBuilder();
String scheme = req.getScheme();
String forwardedScheme = req.getHeader("X-Forwarded-Proto");
if (forwardedScheme != null) {
scheme = forwardedScheme;
}
buf.append(scheme+"://");
buf.append(req.getServerName());
if(req.getServerPort()!=80)
buf.append(':').append(req.getServerPort());
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", getRootDir().getPath(),
"ITEM_ROOTDIR", item.getRootDir().getPath(),
"ITEM_FULLNAME", item.getFullName(), // legacy, deprecated
"ITEM_FULL_NAME", item.getFullName().replace(':','$')))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
public FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new Callable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Hudson would have to have crumb in it to protect
* Hudson from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes
* in Hudson.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
markupFormatter = null;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Hudson is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
this.numExecutors = n;
save();
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
public TopLevelItem getItem(String name) {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name, if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean)
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Hudson by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
for (View v : views)
v.onJobRenamed(job, oldName, newName);
save();
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
for (ItemListener l : ItemListener.all())
l.onDeleted(item);
items.remove(item.getName());
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
save();
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles(new FileFilter() {
public boolean accept(File child) {
return child.isDirectory() && Items.getConfigFile(child).exists();
}
});
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadHudson = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
// JENKINS-8043: some slaves (eg. swarm slaves) are not saved into the config file
// and will get overwritten when reloading. Make a backup copy now, and re-add them later
NodeList oldSlaves = slaves;
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
// if we are loading old data that doesn't have this field
if (slaves == null) slaves = new NodeList();
clouds.setOwner(Jenkins.this);
// JENKINS-8043: re-add the slaves which were not saved into the config file
// and are now missing, but still connected.
if (oldSlaves != null) {
ArrayList<Node> newSlaves = new ArrayList<Node>(slaves);
for (Node n: oldSlaves) {
if (n instanceof EphemeralNode) {
if(!newSlaves.contains(n)) {
newSlaves.add(n);
}
}
}
setNodes(newSlaves);
}
}
});
for (final File subdir : subdirs) {
g.requires(loadHudson).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : slaves)
// Note that not all labels are visible until the slaves have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Hudson and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
for (ItemListener l : ItemListener.all())
l.onBeforeShutdown();
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
} catch (InterruptedException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
e.printStackTrace();
} catch (ReactorException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
}
Set<Future<?>> pending = new HashSet<Future<?>>();
terminating = true;
for( Computer c : computers.values() ) {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
}
if(udpBroadcastThread!=null)
udpBroadcastThread.shutdown();
if(dnsMultiCast!=null)
dnsMultiCast.close();
interruptReloadThread();
java.util.Timer timer = Trigger.timer;
if (timer != null) {
timer.cancel();
}
// TODO: how to wait for the completion of the last job?
Trigger.timer = null;
Timer.shutdown();
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
for (Future<?> f : pending)
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
}
LogFactory.releaseAll();
theInstance = null;
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
jdks.clear();
jdks.addAll(req.bindJSONToList(JDK.class,json.get("jdks")));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
if (timeout > 0) timeout += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < timeout)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all slaves (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(MasterComputer.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return r;
}
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
/**
* Makes sure that the given name is good as a job name.
* @return trimmed name if valid; throws Failure if not
*/
private String checkJobName(String name) throws Failure {
checkGoodName(name);
name = name.trim();
projectNamingStrategy.checkName(name);
if(getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
// looks good
return name;
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
securityRealm.doLogout(req, rsp);
}
/**
* Serves jar files for JNLP slave agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@CLIMethod(name="reload-configuration")
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
executeReactor(null, loadTasks());
User.reload();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,MasterComputer.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Hudson, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Hudson for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Hudson is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Hudson is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
while (isQuietingDown
&& (overallLoad.computeTotalExecutors() > overallLoad.computeIdleExecutors())) {
Thread.sleep(5000);
}
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to shutdown Hudson",e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), MasterComputer.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), MasterComputer.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null || !ICON_SIZE.matcher(qs).matches())
throw new ServletException();
Cookie cookie = new Cookie("iconSize", qs);
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!value.equals("(Default)"))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Makes sure that the given name is good as a job name.
*/
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
checkPermission(Item.CREATE);
if(fixEmpty(value)==null)
return FormValidation.ok();
try {
checkJobName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
dependencyGraphDirty.set(false);
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
dependencyGraphDirty.set(true);
return Timer.get().submit(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
if (dependencyGraphDirty.get()) {
rebuildDependencyGraph();
}
return dependencyGraph;
}
});
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/adjuncts/")
|| rest.startsWith("/error")
|| rest.startsWith("/oops")
|| rest.startsWith("/signup")
|| rest.startsWith("/tcpSlaveAgentListener")
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
|| rest.startsWith("/federatedLoginService/")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
names.add(a.getUrlName());
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*/
public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
}
/**
* Shortcut for {@code Jenkins.getInstance().lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Hudson.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM = new XStream2();
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2 = (XStream2)XSTREAM;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
try {
InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* Version number of this Hudson.
*/
public static String VERSION="?";
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Hudson is run with "mvn hudson-dev:run")
*/
public static VersionNumber getVersion() {
try {
return new VersionNumber(VERSION);
} catch (NumberFormatException e) {
try {
// for non-released version of Hudson, this looks like "1.345 (private-foobar), so try to approximate.
int idx = VERSION.indexOf(' ');
if (idx>0)
return new VersionNumber(VERSION.substring(0,idx));
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Hudson to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* Enabled by default as of 1.337. Will keep it for a while just in case we have some serious problems.
*/
public static boolean FLYWEIGHT_SUPPORT = Configuration.getBooleanConfigParameter("flyweightSupport", true);
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+");
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
static {
XSTREAM.alias("jenkins",Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk",JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS!=null;
assert ADMINISTER!=null;
}
}
| core/src/main/java/jenkins/model/Jenkins.java | /*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* 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 jenkins.model;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.init.*;
import hudson.model.LoadStatistics;
import hudson.model.Messages;
import hudson.model.Node;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.ModifiableViewGroup;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.ManagementLink;
import hudson.model.NoFingerprintMatch;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.Descriptor.FormException;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.model.Queue;
import hudson.model.WorkspaceCleanupThread;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.markup.MarkupFormatter;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import static hudson.Util.fixEmpty;
import static hudson.Util.fixNull;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.lifecycle.Lifecycle;
import hudson.logging.LogRecorderManager;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.markup.RawHtmlMarkupFormatter;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.StreamTaskListener;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import static hudson.init.InitMilestone.*;
import hudson.security.BasicAuthenticationFilter;
import hudson.util.NamingThreadFactory;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import static java.util.logging.Level.SEVERE;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements ModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Hudson whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Hudson.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Hudson.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Hudson system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Set of installed cluster nodes.
* <p>
* We use this field with copy-on-write semantics.
* This field has mutable list (to keep the serialization look clean),
* but it shall never be modified. Only new completely populated slave
* list can be set here.
* <p>
* The field name should be really {@code nodes}, but again the backward compatibility
* prevents us from renaming.
*/
protected volatile NodeList slaves;
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Hudson.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
/**
* Send the browser to the config page.
* use View to trim view/{default-view} from URL if possible
*/
@Override
protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException {
String redirect = result.getUrl()+"configure";
List<Ancestor> ancestors = req.getAncestors();
for (int i = ancestors.size() - 1; i >= 0; i--) {
Object o = ancestors.get(i).getObject();
if (o instanceof View) {
redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect;
break;
}
}
return redirect;
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public Jenkins getInstance() {
return theInstance;
}
};
@CLIResolver
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c,StreamTaskListener.fromStdout());
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Hudson.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Hudson by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() throws IOException {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/**
* Gets all the installed {@link SCMListener}s.
*/
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public MarkupFormatter getMarkupFormatter() {
return markupFormatter!=null ? markupFormatter : RawHtmlMarkupFormatter.INSTANCE;
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Hudson.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Hudson.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Hudson forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
final Collator collator = Collator.getInstance();
public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return collator.compare(lhs.getDisplayName(), rhs.getDisplayName());
}
});
return r;
}
@CLIResolver
public Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Hudson.
*/
public @CheckForNull Node getNode(String name) {
return slaves.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return slaves;
}
/**
* Adds one more {@link Node} to Hudson.
*/
public synchronized void addNode(Node n) throws IOException {
if(n==null) throw new IllegalArgumentException();
ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
if(!nl.contains(n)) // defensive check
nl.add(n);
setNodes(nl);
}
/**
* Removes a {@link Node} from Hudson.
*/
public synchronized void removeNode(@Nonnull Node n) throws IOException {
Computer c = n.toComputer();
if (c!=null)
c.disconnect(OfflineCause.create(Messages._Hudson_NodeBeingRemoved()));
ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
nl.remove(n);
setNodes(nl);
}
public void setNodes(List<? extends Node> nodes) throws IOException {
this.slaves = new NodeList(nodes);
updateComputerList();
trimLabels();
save();
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
private void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
public String getDisplayName() {
return "";
}
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
if (!value.contains("${")) {
File d = new File(value);
if (!d.isDirectory() && (d.getParentFile() == null || !d.getParentFile().canWrite())) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
// TODO failure to use either ITEM_* variable might be an error too?
}
return FormValidation.ok(); // TODO assumes it will be OK after substitution, but can we be sure?
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return views; }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins,
* such as "http://localhost/jenkins/".
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link StaplerRequest#getRootPath()}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return
* This method returns null if this parameter is not configured by the user.
* The caller must gracefully deal with this situation.
* The returned URL will always have the trailing '/'.
* @since 1.66
* @see Descriptor#getCheckUrl(String)
* @see #getRootUrlFromRequest()
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Hudson top page, such as "http://localhost/hudson/".
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy (e.g. when user has switched off ProxyPreserveHost, which is
* default setup or the actual url uses https) and you should use getRootUrl if
* you want to be sure you reflect user setup.
* See https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache
*
* @since 1.263
*/
public String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
StringBuilder buf = new StringBuilder();
String scheme = req.getScheme();
String forwardedScheme = req.getHeader("X-Forwarded-Proto");
if (forwardedScheme != null) {
scheme = forwardedScheme;
}
buf.append(scheme+"://");
buf.append(req.getServerName());
if(req.getServerPort()!=80)
buf.append(':').append(req.getServerPort());
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", getRootDir().getPath(),
"ITEM_ROOTDIR", item.getRootDir().getPath(),
"ITEM_FULLNAME", item.getFullName(), // legacy, deprecated
"ITEM_FULL_NAME", item.getFullName().replace(':','$')))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
public FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new Callable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Hudson would have to have crumb in it to protect
* Hudson from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes
* in Hudson.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
markupFormatter = null;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Hudson is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
this.numExecutors = n;
save();
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
public TopLevelItem getItem(String name) {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name, if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean)
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Hudson by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
for (View v : views)
v.onJobRenamed(job, oldName, newName);
save();
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
for (ItemListener l : ItemListener.all())
l.onDeleted(item);
items.remove(item.getName());
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
save();
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles(new FileFilter() {
public boolean accept(File child) {
return child.isDirectory() && Items.getConfigFile(child).exists();
}
});
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadHudson = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
// JENKINS-8043: some slaves (eg. swarm slaves) are not saved into the config file
// and will get overwritten when reloading. Make a backup copy now, and re-add them later
NodeList oldSlaves = slaves;
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
// if we are loading old data that doesn't have this field
if (slaves == null) slaves = new NodeList();
clouds.setOwner(Jenkins.this);
// JENKINS-8043: re-add the slaves which were not saved into the config file
// and are now missing, but still connected.
if (oldSlaves != null) {
ArrayList<Node> newSlaves = new ArrayList<Node>(slaves);
for (Node n: oldSlaves) {
if (n instanceof EphemeralNode) {
if(!newSlaves.contains(n)) {
newSlaves.add(n);
}
}
}
setNodes(newSlaves);
}
}
});
for (final File subdir : subdirs) {
g.requires(loadHudson).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : slaves)
// Note that not all labels are visible until the slaves have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Hudson and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
for (ItemListener l : ItemListener.all())
l.onBeforeShutdown();
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
} catch (InterruptedException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
e.printStackTrace();
} catch (ReactorException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
}
Set<Future<?>> pending = new HashSet<Future<?>>();
terminating = true;
for( Computer c : computers.values() ) {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
}
if(udpBroadcastThread!=null)
udpBroadcastThread.shutdown();
if(dnsMultiCast!=null)
dnsMultiCast.close();
interruptReloadThread();
java.util.Timer timer = Trigger.timer;
if (timer != null) {
timer.cancel();
}
// TODO: how to wait for the completion of the last job?
Trigger.timer = null;
Timer.shutdown();
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
for (Future<?> f : pending)
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
}
LogFactory.releaseAll();
theInstance = null;
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
jdks.clear();
jdks.addAll(req.bindJSONToList(JDK.class,json.get("jdks")));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
if (timeout > 0) timeout += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < timeout)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all slaves (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(MasterComputer.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return r;
}
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
/**
* Makes sure that the given name is good as a job name.
* @return trimmed name if valid; throws Failure if not
*/
private String checkJobName(String name) throws Failure {
checkGoodName(name);
name = name.trim();
projectNamingStrategy.checkName(name);
if(getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
// looks good
return name;
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
securityRealm.doLogout(req, rsp);
}
/**
* Serves jar files for JNLP slave agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@CLIMethod(name="reload-configuration")
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
executeReactor(null, loadTasks());
User.reload();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,MasterComputer.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Hudson, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Hudson for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Hudson is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Hudson is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
while (isQuietingDown
&& (overallLoad.computeTotalExecutors() > overallLoad.computeIdleExecutors())) {
Thread.sleep(5000);
}
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to shutdown Hudson",e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), MasterComputer.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), MasterComputer.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null || !ICON_SIZE.matcher(qs).matches())
throw new ServletException();
Cookie cookie = new Cookie("iconSize", qs);
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!value.equals("(Default)"))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Makes sure that the given name is good as a job name.
*/
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
checkPermission(Item.CREATE);
if(fixEmpty(value)==null)
return FormValidation.ok();
try {
checkJobName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
return MasterComputer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
rebuildDependencyGraph();
return dependencyGraph;
}
});
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/adjuncts/")
|| rest.startsWith("/error")
|| rest.startsWith("/oops")
|| rest.startsWith("/signup")
|| rest.startsWith("/tcpSlaveAgentListener")
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
|| rest.startsWith("/federatedLoginService/")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
names.add(a.getUrlName());
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*/
public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
}
/**
* Shortcut for {@code Jenkins.getInstance().lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Hudson.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM = new XStream2();
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2 = (XStream2)XSTREAM;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
try {
InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* Version number of this Hudson.
*/
public static String VERSION="?";
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Hudson is run with "mvn hudson-dev:run")
*/
public static VersionNumber getVersion() {
try {
return new VersionNumber(VERSION);
} catch (NumberFormatException e) {
try {
// for non-released version of Hudson, this looks like "1.345 (private-foobar), so try to approximate.
int idx = VERSION.indexOf(' ');
if (idx>0)
return new VersionNumber(VERSION.substring(0,idx));
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Hudson to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* Enabled by default as of 1.337. Will keep it for a while just in case we have some serious problems.
*/
public static boolean FLYWEIGHT_SUPPORT = Configuration.getBooleanConfigParameter("flyweightSupport", true);
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+");
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
static {
XSTREAM.alias("jenkins",Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk",JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS!=null;
assert ADMINISTER!=null;
}
}
| Make sure rebuildDependencyGraphAsync does not repeat work if called many times in quick succession. | core/src/main/java/jenkins/model/Jenkins.java | Make sure rebuildDependencyGraphAsync does not repeat work if called many times in quick succession. | <ide><path>ore/src/main/java/jenkins/model/Jenkins.java
<ide> import java.util.concurrent.ThreadPoolExecutor;
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.TimeoutException;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<ide> import java.util.logging.Level;
<ide> import static java.util.logging.Level.SEVERE;
<ide> import java.util.logging.LogRecord;
<ide> private List<JDK> jdks = new ArrayList<JDK>();
<ide>
<ide> private transient volatile DependencyGraph dependencyGraph;
<add> private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
<ide>
<ide> /**
<ide> * Currently active Views tab bar.
<ide> // volatile acts a as a memory barrier here and therefore guarantees
<ide> // that graph is fully build, before it's visible to other threads
<ide> dependencyGraph = graph;
<add> dependencyGraphDirty.set(false);
<ide> }
<ide>
<ide> /**
<ide> * @since 1.522
<ide> */
<ide> public Future<DependencyGraph> rebuildDependencyGraphAsync() {
<del> return MasterComputer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<DependencyGraph>() {
<add> dependencyGraphDirty.set(true);
<add> return Timer.get().submit(new java.util.concurrent.Callable<DependencyGraph>() {
<ide> @Override
<ide> public DependencyGraph call() throws Exception {
<del> rebuildDependencyGraph();
<add> if (dependencyGraphDirty.get()) {
<add> rebuildDependencyGraph();
<add> }
<ide> return dependencyGraph;
<ide> }
<ide> }); |
|
Java | lgpl-2.1 | bc16045435451becbc43ca4520ef8bf195190ea6 | 0 | deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3 | //$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.commons.jdbc;
import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.deegree.commons.i18n.Messages;
import org.deegree.commons.jdbc.jaxb.PooledConnection;
import org.deegree.commons.utils.TempFileManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Entry point for accessing JDBC connections in deegree that are defined in JDBC configuration files.
* <p>
* Configuration of JDBC connections used in deegree is based on simple string identifiers: each configured JDBC
* connection has a unique identifier. This class allows the retrieval of connections based on their identifier.
* </p>
*
* @author <a href="mailto:[email protected]">Markus Schneider</a>
* @author last edited by: $Author: schneider $
*
* @version $Revision: $, $Date: $
*/
public class ConnectionManager {
private static Logger LOG = LoggerFactory.getLogger( ConnectionManager.class );
private static Map<String, ConnectionPool> idToPools = new HashMap<String, ConnectionPool>();
static {
String lockDb = new File( TempFileManager.getBaseDir(), "lockdb" ).getAbsolutePath();
LOG.info( "Using '" + lockDb + "' for derby lock database." );
try {
Class.forName( "org.apache.derby.jdbc.EmbeddedDriver" ).newInstance();
} catch ( Exception e ) {
LOG.error( "Error loading derby JDBC driver: " + e.getMessage(), e );
}
addConnection( "LOCK_DB", "jdbc:derby:" + lockDb + ";create=true", null, null, 0, 10 );
}
/**
* Initializes the {@link ConnectionManager} by loading all JDBC pool configurations from the given directory.
*
* @param jdbcDir
*/
public static void init( File jdbcDir ) {
File[] fsConfigFiles = jdbcDir.listFiles( new FilenameFilter() {
@Override
public boolean accept( File dir, String name ) {
// TODO Auto-generated method stub
return name.toLowerCase().endsWith( ".xml" );
}
} );
for ( File fsConfigFile : fsConfigFiles ) {
String fileName = fsConfigFile.getName();
// 4 is the length of ".xml"
String fsId = fileName.substring( 0, fileName.length() - 4 );
LOG.info( "Setting up JDBC connection '" + fsId + "' from file '" + fileName + "'..." + "" );
try {
addConnection( fsConfigFile.toURI().toURL(), fsId );
} catch ( Exception e ) {
LOG.error( "Error initializing JDBC connection pool: " + e.getMessage(), e );
}
}
}
/**
*
*/
public static void destroy() {
try {
DriverManager.getConnection( "jdbc:derby:;shutdown=true" );
} catch ( SQLException e ) {
LOG.debug( "Exception caught shutting down derby databases: " + e.getMessage(), e );
}
}
/**
* Returns a connection from the connection pool with the given id.
*
* @param id
* id of the connection pool
* @return connection from the corresponding connection pool
* @throws SQLException
* if the connection pool is unknown or a SQLException occurs creating the connection
*/
public static Connection getConnection( String id )
throws SQLException {
ConnectionPool pool = idToPools.get( id );
if ( pool == null ) {
throw new SQLException( Messages.getMessage( "JDBC_UNKNOWN_CONNECTION", id ) );
}
return pool.getConnection();
}
/**
* Adds the connection pool defined in the given file.
*
* @param jdbcConfigUrl
* @param connId
* @throws JAXBException
*/
public static void addConnection( URL jdbcConfigUrl, String connId )
throws JAXBException {
synchronized ( ConnectionManager.class ) {
JAXBContext jc = JAXBContext.newInstance( "org.deegree.commons.jdbc.jaxb" );
Unmarshaller u = jc.createUnmarshaller();
addConnection( (PooledConnection) u.unmarshal( jdbcConfigUrl ), connId );
}
}
/**
* Adds a connection pool from the given pool definition.
*
* @param jaxbConn
* @param connId
*/
public static void addConnection( PooledConnection jaxbConn, String connId ) {
synchronized ( ConnectionManager.class ) {
String url = jaxbConn.getUrl();
String user = jaxbConn.getUser();
String password = jaxbConn.getPassword();
int poolMinSize = jaxbConn.getPoolMinSize().intValue();
int poolMaxSize = jaxbConn.getPoolMaxSize().intValue();
LOG.debug( Messages.getMessage( "JDBC_SETTING_UP_CONNECTION_POOL", connId, url, user, poolMinSize,
poolMaxSize ) );
if ( idToPools.containsKey( connId ) ) {
throw new IllegalArgumentException( Messages.getMessage( "JDBC_DUPLICATE_ID", connId ) );
}
ConnectionPool pool = new ConnectionPool( connId, url, user, password, poolMinSize, poolMaxSize );
idToPools.put( connId, pool );
}
}
/**
* Adds a connection pool as specified in the parameters.
*
* @param connId
* @param url
* @param user
* @param password
* @param poolMinSize
* @param poolMaxSize
*/
public static void addConnection( String connId, String url, String user, String password, int poolMinSize,
int poolMaxSize ) {
synchronized ( ConnectionManager.class ) {
LOG.debug( Messages.getMessage( "JDBC_SETTING_UP_CONNECTION_POOL", connId, url, user, poolMinSize,
poolMaxSize ) );
if ( idToPools.containsKey( connId ) ) {
throw new IllegalArgumentException( Messages.getMessage( "JDBC_DUPLICATE_ID", connId ) );
}
ConnectionPool pool = new ConnectionPool( connId, url, user, password, poolMinSize, poolMaxSize );
idToPools.put( connId, pool );
}
}
/**
* @return all currently available connection ids
*/
public static Set<String> getConnectionIds() {
return idToPools.keySet();
}
}
| deegree-core/src/main/java/org/deegree/commons/jdbc/ConnectionManager.java | //$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.commons.jdbc;
import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.deegree.commons.i18n.Messages;
import org.deegree.commons.jdbc.jaxb.PooledConnection;
import org.deegree.commons.utils.TempFileManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Entry point for accessing JDBC connections in deegree that are defined in JDBC configuration files.
* <p>
* Configuration of JDBC connections used in deegree is based on simple string identifiers: each configured JDBC
* connection has a unique identifier. This class allows the retrieval of connections based on their identifier.
* </p>
*
* @author <a href="mailto:[email protected]">Markus Schneider</a>
* @author last edited by: $Author: schneider $
*
* @version $Revision: $, $Date: $
*/
public class ConnectionManager {
private static Logger LOG = LoggerFactory.getLogger( ConnectionManager.class );
private static Map<String, ConnectionPool> idToPools = new HashMap<String, ConnectionPool>();
static {
String lockDb = new File( TempFileManager.getBaseDir(), "lockdb" ).getAbsolutePath();
LOG.info( "Using '" + lockDb + "' for derby lock database." );
try {
Class.forName( "org.apache.derby.jdbc.EmbeddedDriver" ).newInstance();
} catch ( Exception e ) {
LOG.error( "Error loading derby JDBC driver: " + e.getMessage(), e );
}
addConnection( "LOCK_DB", "jdbc:derby:" + lockDb + ";create=true", null, null, 0, 10 );
}
/**
* Initializes the {@link ConnectionManager} by loading all JDBC pool configurations from the given directory.
*
* @param jdbcDir
*/
public static void init( File jdbcDir ) {
File[] fsConfigFiles = jdbcDir.listFiles( new FilenameFilter() {
@Override
public boolean accept( File dir, String name ) {
// TODO Auto-generated method stub
return name.toLowerCase().endsWith( ".xml" );
}
} );
for ( File fsConfigFile : fsConfigFiles ) {
String fileName = fsConfigFile.getName();
// 4 is the length of ".xml"
String fsId = fileName.substring( 0, fileName.length() - 4 );
LOG.info( "Setting up JDBC connection '" + fsId + "' from file '" + fileName + "'..." + "" );
try {
addConnection( fsConfigFile.toURI().toURL(), fsId );
} catch ( Exception e ) {
LOG.error( "Error initializing JDBC connection pool: " + e.getMessage(), e );
}
}
}
/**
*
*/
public static void destroy() {
try {
DriverManager.getConnection( "jdbc:derby:;shutdown=true" );
} catch ( SQLException e ) {
LOG.debug( "Exception caught shutting down derby databases: " + e.getMessage(), e );
}
}
/**
* Returns a connection from the connection pool with the given id.
*
* @param id
* id of the connection pool
* @return connection from the corresponding connection pool
* @throws SQLException
* if the connection pool is unknown or a SQLException occurs creating the connection
*/
public static Connection getConnection( String id )
throws SQLException {
ConnectionPool pool = idToPools.get( id );
if ( pool == null ) {
throw new SQLException( Messages.getMessage( "JDBC_UNKNOWN_CONNECTION", id ) );
}
return pool.getConnection();
}
/**
* Adds the connection pool defined in the given file.
*
* @param jdbcConfigUrl
* @throws JAXBException
*/
public static void addConnection( URL jdbcConfigUrl, String connId )
throws JAXBException {
synchronized ( ConnectionManager.class ) {
JAXBContext jc = JAXBContext.newInstance( "org.deegree.commons.configuration" );
Unmarshaller u = jc.createUnmarshaller();
addConnection( (PooledConnection) u.unmarshal( jdbcConfigUrl ), connId );
}
}
/**
* Adds a connection pool from the given pool definition.
*
* @param jaxbConn
*/
public static void addConnection( PooledConnection jaxbConn, String connId ) {
synchronized ( ConnectionManager.class ) {
String url = jaxbConn.getUrl();
String user = jaxbConn.getUser();
String password = jaxbConn.getPassword();
int poolMinSize = jaxbConn.getPoolMinSize().intValue();
int poolMaxSize = jaxbConn.getPoolMaxSize().intValue();
LOG.debug( Messages.getMessage( "JDBC_SETTING_UP_CONNECTION_POOL", connId, url, user, poolMinSize,
poolMaxSize ) );
if ( idToPools.containsKey( connId ) ) {
throw new IllegalArgumentException( Messages.getMessage( "JDBC_DUPLICATE_ID", connId ) );
}
ConnectionPool pool = new ConnectionPool( connId, url, user, password, poolMinSize, poolMaxSize );
idToPools.put( connId, pool );
}
}
/**
* Adds a connection pool as specified in the parameters.
*
* @param connId
* @param type
* @param url
* @param user
* @param password
* @param poolMinSize
* @param poolMaxSize
*/
public static void addConnection( String connId, String url, String user, String password, int poolMinSize,
int poolMaxSize ) {
synchronized ( ConnectionManager.class ) {
LOG.debug( Messages.getMessage( "JDBC_SETTING_UP_CONNECTION_POOL", connId, url, user, poolMinSize,
poolMaxSize ) );
if ( idToPools.containsKey( connId ) ) {
throw new IllegalArgumentException( Messages.getMessage( "JDBC_DUPLICATE_ID", connId ) );
}
ConnectionPool pool = new ConnectionPool( connId, url, user, password, poolMinSize, poolMaxSize );
idToPools.put( connId, pool );
}
}
/**
* @return all currently available connection ids
*/
public static Set<String> getConnectionIds() {
return idToPools.keySet();
}
}
| topic: bug fix
type: minor
module: commons
description: Use proper jaxb namespace when parsing.
| deegree-core/src/main/java/org/deegree/commons/jdbc/ConnectionManager.java | topic: bug fix type: minor module: commons description: Use proper jaxb namespace when parsing. | <ide><path>eegree-core/src/main/java/org/deegree/commons/jdbc/ConnectionManager.java
<ide> * Adds the connection pool defined in the given file.
<ide> *
<ide> * @param jdbcConfigUrl
<add> * @param connId
<ide> * @throws JAXBException
<ide> */
<ide> public static void addConnection( URL jdbcConfigUrl, String connId )
<ide> throws JAXBException {
<ide> synchronized ( ConnectionManager.class ) {
<del> JAXBContext jc = JAXBContext.newInstance( "org.deegree.commons.configuration" );
<add> JAXBContext jc = JAXBContext.newInstance( "org.deegree.commons.jdbc.jaxb" );
<ide> Unmarshaller u = jc.createUnmarshaller();
<ide> addConnection( (PooledConnection) u.unmarshal( jdbcConfigUrl ), connId );
<ide> }
<ide> * Adds a connection pool from the given pool definition.
<ide> *
<ide> * @param jaxbConn
<add> * @param connId
<ide> */
<ide> public static void addConnection( PooledConnection jaxbConn, String connId ) {
<ide> synchronized ( ConnectionManager.class ) {
<ide> * Adds a connection pool as specified in the parameters.
<ide> *
<ide> * @param connId
<del> * @param type
<ide> * @param url
<ide> * @param user
<ide> * @param password |
|
Java | bsd-2-clause | 229a651478cb9d168830d278acd735d01ff4da29 | 0 | chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio | /*
* Copyright (c) 2003, jMonkeyEngine - Mojo Monkey Coding
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, nor the
* names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package jmetest.renderer;
import com.jme.app.*;
import com.jme.image.*;
import com.jme.input.*;
import com.jme.light.*;
import com.jme.math.*;
import com.jme.renderer.*;
import com.jme.scene.*;
import com.jme.scene.state.*;
import com.jme.system.*;
import com.jme.util.*;
import org.lwjgl.opengl.*;
import java.nio.*;
/**
* <code>TestRenderToTexture</code>
* @author Joshua Slack
*/
public class TestRenderToTexture extends SimpleGame {
private TriMesh t, t2;
private Camera cam;
private Node root;
private Node scene, fake;
private InputController input;
private Thread thread;
private Timer timer;
private Quaternion rotQuat;
private float angle = 0;
private Vector3f axis;
private TextureState ts;
/** Pbuffer instance */
private static Pbuffer pbuffer;
/** The shared texture */
private static int tex_handle;
/**
* Entry point for the test,
* @param args
*/
public static void main(String[] args) {
TestRenderToTexture app = new TestRenderToTexture();
app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG);
app.start();
}
/**
* Not used in this test.
* @see com.jme.app.SimpleGame#update()
*/
protected void update(float interpolation) {
if(timer.getTimePerFrame() < 1) {
angle = angle + (timer.getTimePerFrame() * 1);
if(angle > 360) {
angle = 0;
}
}
rotQuat.fromAngleAxis(angle, axis);
timer.update();
input.update(timer.getTimePerFrame());
// t.setLocalRotation(rotQuat);
t2.setLocalRotation(rotQuat);
scene.updateGeometricState(0.0f, true);
fake.updateGeometricState(0.0f, true);
}
private void initPbuffer() {
try {
pbuffer = new Pbuffer(512, 512, 32, 0, 0, 0);
pbuffer.makeCurrent();
GL.glClearColor(.1f, .1f, .1f, 1f);
display.getRenderer().getCamera().update();
GL.glBindTexture(GL.GL_TEXTURE_2D, tex_handle);
Pbuffer.releaseContext();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* clears the buffers and then draws the TriMesh.
* @see com.jme.app.SimpleGame#render()
*/
protected void render(float interpolation) {
try {
if (pbuffer.isBufferLost()) {
System.out.println("Buffer contents lost - will recreate the buffer");
Pbuffer.releaseContext();
pbuffer.destroy();
initPbuffer();
}
pbuffer.makeCurrent();
display.getRenderer().clearBuffers();
scene.unsetStates();
display.getRenderer().draw(fake);
GL.glBindTexture(GL.GL_TEXTURE_2D, tex_handle);
GL.glCopyTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_COMPRESSED_RGB, 0, 0, 512, 512, 0);
pbuffer.releaseContext();
} catch (Exception e) {
System.err.println("ouch");
e.printStackTrace();
System.exit(0);
}
scene.setRenderState(ts);
display.getRenderer().clearBuffers();
GL.glPushMatrix();
display.getRenderer().draw(root);
GL.glPopMatrix();
}
/**
* creates the displays and sets up the viewport.
* @see com.jme.app.SimpleGame#initSystem()
*/
protected void initSystem() {
try {
display = DisplaySystem.getDisplaySystem(properties.getRenderer());
display.createWindow(
properties.getWidth(),
properties.getHeight(),
properties.getDepth(),
properties.getFreq(),
properties.getFullscreen());
cam =
display.getRenderer().getCamera(
properties.getWidth(),
properties.getHeight());
} catch (JmeException e) {
e.printStackTrace();
System.exit(1);
}
if ((Pbuffer.getPbufferCaps() & Pbuffer.PBUFFER_SUPPORTED) == 0) {
System.out.println("No Pbuffer support!");
System.exit(1);
}
System.out.println("Pbuffer support detected");
ColorRGBA blackColor = new ColorRGBA(0, 0, 0, 1);
display.getRenderer().setBackgroundColor(blackColor);
cam.setFrustum(1.0f, 1000.0f, -0.55f, 0.55f, 0.4125f, -0.4125f);
Vector3f loc = new Vector3f(0.0f, 0.0f, 75.0f);
Vector3f left = new Vector3f(-1.0f, 0.0f, 0.0f);
Vector3f up = new Vector3f(0.0f, 1.0f, 0.0f);
Vector3f dir = new Vector3f(0.0f, 0f, -1.0f);
cam.setFrame(loc, left, up, dir);
display.getRenderer().setCamera(cam);
input = new FirstPersonController(this, cam, "LWJGL");
input.setKeySpeed(5f);
input.setMouseSpeed(.5f);
timer = Timer.getTimer("LWJGL");
rotQuat = new Quaternion();
axis = new Vector3f(1,1,0.5f);
display.setTitle("Render to Texture");
IntBuffer buf =
ByteBuffer
.allocateDirect(4)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
//Create the texture
GL.glGenTextures(buf);
tex_handle = buf.get(0);
GL.glBindTexture(GL.GL_TEXTURE_2D, tex_handle);
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR );
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR );
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE );
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE );
// GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_GENERATE_MIPMAP, GL.GL_TRUE);
initPbuffer();
}
/**
* builds the trimesh.
* @see com.jme.app.SimpleGame#initGame()
*/
protected void initGame() {
TextureState textImage = display.getRenderer().getTextureState();
textImage.setEnabled(true);
textImage.setTexture(
TextureManager.loadTexture(
TestRenderToTexture.class.getClassLoader().getResource("jmetest/data/font/font.png"),
Texture.MM_LINEAR,
Texture.FM_LINEAR,
true));
AlphaState as1 = display.getRenderer().getAlphaState();
as1.setBlendEnabled(true);
as1.setSrcFunction(AlphaState.SB_SRC_ALPHA);
as1.setDstFunction(AlphaState.DB_ONE);
as1.setTestEnabled(true);
as1.setTestFunction(AlphaState.TF_GREATER);
scene = new Node("3D Scene Node");
root = new Node("Root Scene Node");
fake = new Node("Fake node");
Vector3f max = new Vector3f(5,5,5);
Vector3f min = new Vector3f(-5,-5,-5);
t = new Box("Box", min,max);
t.setModelBound(new BoundingSphere());
t.updateModelBound();
t.setLocalTranslation(new Vector3f(0,0,0));
scene.attachChild(t);
root.attachChild(scene);
t2 = new Box("Box", min,max);
t2.setModelBound(new BoundingSphere());
t2.updateModelBound();
t2.setLocalTranslation(new Vector3f(0,0,0));
fake.attachChild(t2);
ZBufferState buf = display.getRenderer().getZBufferState();
buf.setEnabled(true);
buf.setFunction(ZBufferState.CF_LEQUAL);
DirectionalLight am = new DirectionalLight();
am.setDiffuse(new ColorRGBA(0.0f, 1.0f, 0.0f, 1.0f));
am.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f));
am.setDirection(new Vector3f(0, 0, 75));
LightState state = display.getRenderer().getLightState();
state.attach(am);
am.setEnabled(true);
//scene.setRenderState(state);
scene.setRenderState(buf);
cam.update();
ColorRGBA[] colors = new ColorRGBA[24];
for(int i = 0; i < 24; i++) {
colors[i] = new ColorRGBA((float)Math.random(),
(float)Math.random(),
(float)Math.random(),1);
}
t2.setColors(colors);
// TextureState ts = display.getRenderer().getTextureState();
// ts.setEnabled(true);
ts = display.getRenderer().getTextureState();
Texture tex = new Texture();
ts.setEnabled(true);
tex.setTextureId(tex_handle);
tex.setApply(Texture.AM_MODULATE);
tex.setBlendColor(new ColorRGBA(1, 1, 1, 1));
tex.setCorrection(Texture.CM_PERSPECTIVE);
tex.setFilter(GL.GL_LINEAR);
tex.setMipmapState(GL.GL_LINEAR_MIPMAP_LINEAR);
tex.setWrap(Texture.WM_CLAMP_S_CLAMP_T);
ts.setTexture(tex);
//
// ts.setTexture(
// TextureManager.loadTexture(
// TestRenderToTexture.class.getClassLoader().getResource("jmetest/data/images/Monkey.jpg"),
// Texture.MM_LINEAR,
// Texture.FM_LINEAR,
// true));
scene.setRenderState(ts);
scene.updateGeometricState(0.0f, true);
}
/**
* not used.
* @see com.jme.app.SimpleGame#reinit()
*/
protected void reinit() {
}
/**
* Not used.
* @see com.jme.app.SimpleGame#cleanup()
*/
protected void cleanup() {
}
}
| src/jmetest/renderer/TestRenderToTexture.java | /*
* Copyright (c) 2003, jMonkeyEngine - Mojo Monkey Coding
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, nor the
* names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package jmetest.renderer;
import com.jme.app.*;
import com.jme.image.*;
import com.jme.input.*;
import com.jme.light.*;
import com.jme.math.*;
import com.jme.renderer.*;
import com.jme.scene.*;
import com.jme.scene.state.*;
import com.jme.system.*;
import com.jme.util.*;
import org.lwjgl.opengl.*;
import java.nio.*;
/**
* <code>TestRenderToTexture</code>
* @author Joshua Slack
*/
public class TestRenderToTexture extends SimpleGame {
private TriMesh t, t2;
private Camera cam;
private Node root;
private Node scene, fake;
private InputController input;
private Thread thread;
private Timer timer;
private Quaternion rotQuat;
private float angle = 0;
private Vector3f axis;
private TextureState ts;
/** Pbuffer instance */
private static Pbuffer pbuffer;
/** The shared texture */
private static int tex_handle;
/**
* Entry point for the test,
* @param args
*/
public static void main(String[] args) {
TestRenderToTexture app = new TestRenderToTexture();
app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG);
app.start();
}
/**
* Not used in this test.
* @see com.jme.app.SimpleGame#update()
*/
protected void update(float interpolation) {
if(timer.getTimePerFrame() < 1) {
angle = angle + (timer.getTimePerFrame() * 1);
if(angle > 360) {
angle = 0;
}
}
rotQuat.fromAngleAxis(angle, axis);
timer.update();
input.update(timer.getTimePerFrame());
// t.setLocalRotation(rotQuat);
t2.setLocalRotation(rotQuat);
scene.updateGeometricState(0.0f, true);
fake.updateGeometricState(0.0f, true);
}
private void initPbuffer() {
try {
pbuffer = new Pbuffer(800, 600, 32, 0, 0, 0);
pbuffer.makeCurrent();
GL.glClearColor(.1f, .1f, .1f, 1f);
display.getRenderer().getCamera().update();
GL.glBindTexture(GL.GL_TEXTURE_2D, tex_handle);
Pbuffer.releaseContext();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* clears the buffers and then draws the TriMesh.
* @see com.jme.app.SimpleGame#render()
*/
protected void render(float interpolation) {
try {
if (pbuffer.isBufferLost()) {
System.out.println("Buffer contents lost - will recreate the buffer");
Pbuffer.releaseContext();
pbuffer.destroy();
initPbuffer();
}
pbuffer.makeCurrent();
display.getRenderer().clearBuffers();
scene.unsetStates();
display.getRenderer().draw(fake);
GL.glBindTexture(GL.GL_TEXTURE_2D, tex_handle);
GL.glCopyTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_COMPRESSED_RGB, 0, 0, 512, 512, 0);
pbuffer.releaseContext();
} catch (Exception e) {
System.err.println("ouch");
e.printStackTrace();
System.exit(0);
}
scene.setRenderState(ts);
display.getRenderer().clearBuffers();
GL.glPushMatrix();
display.getRenderer().draw(root);
GL.glPopMatrix();
}
/**
* creates the displays and sets up the viewport.
* @see com.jme.app.SimpleGame#initSystem()
*/
protected void initSystem() {
try {
display = DisplaySystem.getDisplaySystem(properties.getRenderer());
display.createWindow(
properties.getWidth(),
properties.getHeight(),
properties.getDepth(),
properties.getFreq(),
properties.getFullscreen());
cam =
display.getRenderer().getCamera(
properties.getWidth(),
properties.getHeight());
} catch (JmeException e) {
e.printStackTrace();
System.exit(1);
}
if ((Pbuffer.getPbufferCaps() & Pbuffer.PBUFFER_SUPPORTED) == 0) {
System.out.println("No Pbuffer support!");
System.exit(1);
}
System.out.println("Pbuffer support detected");
ColorRGBA blackColor = new ColorRGBA(0, 0, 0, 1);
display.getRenderer().setBackgroundColor(blackColor);
cam.setFrustum(1.0f, 1000.0f, -0.55f, 0.55f, 0.4125f, -0.4125f);
Vector3f loc = new Vector3f(0.0f, 0.0f, 75.0f);
Vector3f left = new Vector3f(-1.0f, 0.0f, 0.0f);
Vector3f up = new Vector3f(0.0f, 1.0f, 0.0f);
Vector3f dir = new Vector3f(0.0f, 0f, -1.0f);
cam.setFrame(loc, left, up, dir);
display.getRenderer().setCamera(cam);
input = new FirstPersonController(this, cam, "LWJGL");
input.setKeySpeed(5f);
input.setMouseSpeed(.5f);
timer = Timer.getTimer("LWJGL");
rotQuat = new Quaternion();
axis = new Vector3f(1,1,0.5f);
display.setTitle("Render to Texture");
IntBuffer buf =
ByteBuffer
.allocateDirect(4)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
//Create the texture
GL.glGenTextures(buf);
tex_handle = buf.get(0);
GL.glBindTexture(GL.GL_TEXTURE_2D, tex_handle);
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR );
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR );
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE );
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE );
// GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_GENERATE_MIPMAP, GL.GL_TRUE);
initPbuffer();
}
/**
* builds the trimesh.
* @see com.jme.app.SimpleGame#initGame()
*/
protected void initGame() {
TextureState textImage = display.getRenderer().getTextureState();
textImage.setEnabled(true);
textImage.setTexture(
TextureManager.loadTexture(
TestRenderToTexture.class.getClassLoader().getResource("jmetest/data/font/font.png"),
Texture.MM_LINEAR,
Texture.FM_LINEAR,
true));
AlphaState as1 = display.getRenderer().getAlphaState();
as1.setBlendEnabled(true);
as1.setSrcFunction(AlphaState.SB_SRC_ALPHA);
as1.setDstFunction(AlphaState.DB_ONE);
as1.setTestEnabled(true);
as1.setTestFunction(AlphaState.TF_GREATER);
scene = new Node("3D Scene Node");
root = new Node("Root Scene Node");
fake = new Node("Fake node");
Vector3f max = new Vector3f(5,5,5);
Vector3f min = new Vector3f(-5,-5,-5);
t = new Box("Box", min,max);
t.setModelBound(new BoundingSphere());
t.updateModelBound();
t.setLocalTranslation(new Vector3f(0,0,0));
scene.attachChild(t);
root.attachChild(scene);
t2 = new Box("Box", min,max);
t2.setModelBound(new BoundingSphere());
t2.updateModelBound();
t2.setLocalTranslation(new Vector3f(0,0,0));
fake.attachChild(t2);
ZBufferState buf = display.getRenderer().getZBufferState();
buf.setEnabled(true);
buf.setFunction(ZBufferState.CF_LEQUAL);
DirectionalLight am = new DirectionalLight();
am.setDiffuse(new ColorRGBA(0.0f, 1.0f, 0.0f, 1.0f));
am.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f));
am.setDirection(new Vector3f(0, 0, 75));
LightState state = display.getRenderer().getLightState();
state.attach(am);
am.setEnabled(true);
//scene.setRenderState(state);
scene.setRenderState(buf);
cam.update();
ColorRGBA[] colors = new ColorRGBA[24];
for(int i = 0; i < 24; i++) {
colors[i] = new ColorRGBA((float)Math.random(),
(float)Math.random(),
(float)Math.random(),1);
}
t2.setColors(colors);
// TextureState ts = display.getRenderer().getTextureState();
// ts.setEnabled(true);
ts = display.getRenderer().getTextureState();
Texture tex = new Texture();
ts.setEnabled(true);
tex.setTextureId(tex_handle);
tex.setApply(Texture.AM_MODULATE);
tex.setBlendColor(new ColorRGBA(1, 1, 1, 1));
tex.setCorrection(Texture.CM_PERSPECTIVE);
tex.setFilter(GL.GL_LINEAR);
tex.setMipmapState(GL.GL_LINEAR_MIPMAP_LINEAR);
tex.setWrap(Texture.WM_CLAMP_S_CLAMP_T);
ts.setTexture(tex);
//
// ts.setTexture(
// TextureManager.loadTexture(
// TestRenderToTexture.class.getClassLoader().getResource("jmetest/data/images/Monkey.jpg"),
// Texture.MM_LINEAR,
// Texture.FM_LINEAR,
// true));
scene.setRenderState(ts);
scene.updateGeometricState(0.0f, true);
}
/**
* not used.
* @see com.jme.app.SimpleGame#reinit()
*/
protected void reinit() {
}
/**
* Not used.
* @see com.jme.app.SimpleGame#cleanup()
*/
protected void cleanup() {
}
}
| no message
git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@529 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
| src/jmetest/renderer/TestRenderToTexture.java | no message | <ide><path>rc/jmetest/renderer/TestRenderToTexture.java
<ide>
<ide> private void initPbuffer() {
<ide> try {
<del> pbuffer = new Pbuffer(800, 600, 32, 0, 0, 0);
<add> pbuffer = new Pbuffer(512, 512, 32, 0, 0, 0);
<ide> pbuffer.makeCurrent();
<ide>
<ide> GL.glClearColor(.1f, .1f, .1f, 1f); |
|
Java | apache-2.0 | b2830f11d32c748840a0a78f8b4d9881caa95538 | 0 | walkap/X-android | package com.walkap.x_android;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.walkap.x_android.models.User;
public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,View.OnClickListener {
private static final String TAG = "SignInActivity";
private static final int RC_SIGN_IN = 9001;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private GoogleApiClient mGoogleApiClient;
private EditText mEmailField;
private EditText mPasswordField;
private Button mSignInButton;
private Button mSignUpButton;
private SignInButton mSignInButtonGoogle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
// Views
mEmailField = (EditText) findViewById(R.id.eT_email);
mPasswordField = (EditText) findViewById(R.id.eT_password);
mSignInButton = (Button) findViewById(R.id.sign_in_button_email);
mSignUpButton = (Button) findViewById(R.id.sign_up_button_email);
// Click listeners
mSignInButton.setOnClickListener(this);
mSignUpButton.setOnClickListener(this);
//Google Sign in
mSignInButtonGoogle = (SignInButton) findViewById(R.id.sign_in_button);
mSignInButtonGoogle.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
@Override
public void onStart() {
super.onStart();
// Check auth on Activity start
if (mAuth.getCurrentUser() != null) {
onAuthSuccess(mAuth.getCurrentUser());
}
}
//Start google scripts
private void signInGoogle(){
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign-In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign-In failed
Log.e(TAG, "Google Sign-In failed.");
}
}
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(SignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
String personId = acct.getId();
String personEmail = acct.getEmail();
String personGivenName = acct.getGivenName();
// Write new user
writeNewUser(personId, personGivenName, personEmail);
//go to main activity
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}
}
});
}
//End google scripts
//start email password scripts
private void signIn() {
Log.d(TAG, "signIn");
if (!validateForm()) {
return;
}
showProgressDialog();
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signIn:onComplete:" + task.isSuccessful());
hideProgressDialog();
if (task.isSuccessful()) {
onAuthSuccess(task.getResult().getUser());
} else {
Toast.makeText(SignInActivity.this, "Sign In Failed",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void signUp() {
Log.d(TAG, "signUp");
if (!validateForm()) {
return;
}
showProgressDialog();
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "createUser:onComplete:" + task.isSuccessful());
hideProgressDialog();
if (task.isSuccessful()) {
onAuthSuccess(task.getResult().getUser());
} else {
Toast.makeText(SignInActivity.this, "Sign Up Failed",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void onAuthSuccess(FirebaseUser user) {
String username = usernameFromEmail(user.getEmail());
// Write new user
writeNewUser(user.getUid(), username, user.getEmail());
// Go to MainActivity
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}
private String usernameFromEmail(String email) {
if (email.contains("@")) {
return email.split("@")[0];
} else {
return email;
}
}
private boolean validateForm() {
boolean result = true;
if (TextUtils.isEmpty(mEmailField.getText().toString())) {
mEmailField.setError("Required");
result = false;
} else {
mEmailField.setError(null);
}
if (TextUtils.isEmpty(mPasswordField.getText().toString())) {
mPasswordField.setError("Required");
result = false;
} else {
mPasswordField.setError(null);
}
return result;
}
//end email and password scripts
// [START basic_write]
private void writeNewUser(String userId, String name, String email) {
User user = new User(name, email);
mDatabase.child("users").child(userId).setValue(user);
}
// [END basic_write]
private ProgressDialog mProgressDialog;
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.sign_in_button_email:
signIn();
break;
case R.id.sign_up_button_email:
signUp();
break;
case R.id.sign_in_button:
signInGoogle();
break;
}
}
}
| app/src/main/java/com/walkap/x_android/SignInActivity.java | package com.walkap.x_android;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 9001;
private static final String TAG = "SignInActivity";
private SignInButton mSignInButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
// Assign fields
mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
// Set click listeners
mSignInButton.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Initialize FirebaseAuth
mFirebaseAuth = FirebaseAuth.getInstance();
}
private void handleFirebaseAuthResult(AuthResult authResult) {
if (authResult != null) {
// Welcome the user
FirebaseUser user = authResult.getUser();
Toast.makeText(this, "Welcome " + user.getEmail(), Toast.LENGTH_SHORT).show();
// Go back to the main activity
startActivity(new Intent(this, MainActivity.class));
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
default:
return;
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign-In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign-In failed
Log.e(TAG, "Google Sign-In failed.");
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(SignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}
}
});
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
} | fixed problem on double registration google/emailpassword, now it works
| app/src/main/java/com/walkap/x_android/SignInActivity.java | fixed problem on double registration google/emailpassword, now it works | <ide><path>pp/src/main/java/com/walkap/x_android/SignInActivity.java
<ide> package com.walkap.x_android;
<ide>
<add>import android.app.ProgressDialog;
<ide> import android.content.Intent;
<add>import android.os.Bundle;
<ide> import android.support.annotation.NonNull;
<ide> import android.support.v7.app.AppCompatActivity;
<del>import android.os.Bundle;
<add>import android.text.TextUtils;
<ide> import android.util.Log;
<ide> import android.view.View;
<add>import android.widget.Button;
<add>import android.widget.EditText;
<ide> import android.widget.Toast;
<ide>
<ide> import com.google.android.gms.auth.api.Auth;
<ide> import com.google.firebase.auth.FirebaseAuth;
<ide> import com.google.firebase.auth.FirebaseUser;
<ide> import com.google.firebase.auth.GoogleAuthProvider;
<del>
<del>public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,
<del> View.OnClickListener {
<del>
<del> // Firebase instance variables
<del> private FirebaseAuth mFirebaseAuth;
<add>import com.google.firebase.database.DatabaseReference;
<add>import com.google.firebase.database.FirebaseDatabase;
<add>import com.walkap.x_android.models.User;
<add>
<add>public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,View.OnClickListener {
<add>
<add> private static final String TAG = "SignInActivity";
<add> private static final int RC_SIGN_IN = 9001;
<add>
<add> private DatabaseReference mDatabase;
<add> private FirebaseAuth mAuth;
<add>
<ide> private GoogleApiClient mGoogleApiClient;
<del> private static final int RC_SIGN_IN = 9001;
<del> private static final String TAG = "SignInActivity";
<del> private SignInButton mSignInButton;
<add>
<add> private EditText mEmailField;
<add> private EditText mPasswordField;
<add> private Button mSignInButton;
<add> private Button mSignUpButton;
<add> private SignInButton mSignInButtonGoogle;
<ide>
<ide> @Override
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<ide> setContentView(R.layout.activity_sign_in);
<ide>
<del> // Assign fields
<del> mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
<del>
<del> // Set click listeners
<add> mDatabase = FirebaseDatabase.getInstance().getReference();
<add> mAuth = FirebaseAuth.getInstance();
<add>
<add> // Views
<add> mEmailField = (EditText) findViewById(R.id.eT_email);
<add> mPasswordField = (EditText) findViewById(R.id.eT_password);
<add> mSignInButton = (Button) findViewById(R.id.sign_in_button_email);
<add> mSignUpButton = (Button) findViewById(R.id.sign_up_button_email);
<add>
<add> // Click listeners
<ide> mSignInButton.setOnClickListener(this);
<add> mSignUpButton.setOnClickListener(this);
<add>
<add>
<add> //Google Sign in
<add> mSignInButtonGoogle = (SignInButton) findViewById(R.id.sign_in_button);
<add>
<add> mSignInButtonGoogle.setOnClickListener(this);
<add>
<ide>
<ide> GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
<ide> .requestIdToken(getString(R.string.default_web_client_id))
<ide> .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
<ide> .build();
<ide>
<del> // Initialize FirebaseAuth
<del> mFirebaseAuth = FirebaseAuth.getInstance();
<del>
<del> }
<del>
<del> private void handleFirebaseAuthResult(AuthResult authResult) {
<del> if (authResult != null) {
<del> // Welcome the user
<del> FirebaseUser user = authResult.getUser();
<del> Toast.makeText(this, "Welcome " + user.getEmail(), Toast.LENGTH_SHORT).show();
<del>
<del> // Go back to the main activity
<del> startActivity(new Intent(this, MainActivity.class));
<del> }
<del> }
<del>
<del> @Override
<del> public void onClick(View v) {
<del> switch (v.getId()) {
<del> case R.id.sign_in_button:
<del> signIn();
<del> break;
<del> default:
<del> return;
<del> }
<del> }
<del>
<del> private void signIn() {
<add> }
<add>
<add> @Override
<add> public void onStart() {
<add> super.onStart();
<add>
<add> // Check auth on Activity start
<add> if (mAuth.getCurrentUser() != null) {
<add> onAuthSuccess(mAuth.getCurrentUser());
<add> }
<add> }
<add>
<add> //Start google scripts
<add>
<add> private void signInGoogle(){
<ide> Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
<ide> startActivityForResult(signInIntent, RC_SIGN_IN);
<ide> }
<ide> }
<ide> }
<ide>
<del> private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
<add> private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
<ide> Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId());
<ide> AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
<del> mFirebaseAuth.signInWithCredential(credential)
<add> mAuth.signInWithCredential(credential)
<ide> .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
<ide> @Override
<ide> public void onComplete(@NonNull Task<AuthResult> task) {
<ide> Toast.makeText(SignInActivity.this, "Authentication failed.",
<ide> Toast.LENGTH_SHORT).show();
<ide> } else {
<add>
<add> String personId = acct.getId();
<add> String personEmail = acct.getEmail();
<add> String personGivenName = acct.getGivenName();
<add>
<add> // Write new user
<add> writeNewUser(personId, personGivenName, personEmail);
<add>
<add> //go to main activity
<ide> startActivity(new Intent(SignInActivity.this, MainActivity.class));
<ide> finish();
<ide> }
<ide> });
<ide> }
<ide>
<add> //End google scripts
<add>
<add>
<add> //start email password scripts
<add> private void signIn() {
<add> Log.d(TAG, "signIn");
<add> if (!validateForm()) {
<add> return;
<add> }
<add>
<add> showProgressDialog();
<add> String email = mEmailField.getText().toString();
<add> String password = mPasswordField.getText().toString();
<add>
<add> mAuth.signInWithEmailAndPassword(email, password)
<add> .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
<add> @Override
<add> public void onComplete(@NonNull Task<AuthResult> task) {
<add> Log.d(TAG, "signIn:onComplete:" + task.isSuccessful());
<add> hideProgressDialog();
<add>
<add> if (task.isSuccessful()) {
<add> onAuthSuccess(task.getResult().getUser());
<add> } else {
<add> Toast.makeText(SignInActivity.this, "Sign In Failed",
<add> Toast.LENGTH_SHORT).show();
<add> }
<add> }
<add> });
<add> }
<add>
<add> private void signUp() {
<add> Log.d(TAG, "signUp");
<add> if (!validateForm()) {
<add> return;
<add> }
<add>
<add> showProgressDialog();
<add> String email = mEmailField.getText().toString();
<add> String password = mPasswordField.getText().toString();
<add>
<add> mAuth.createUserWithEmailAndPassword(email, password)
<add> .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
<add> @Override
<add> public void onComplete(@NonNull Task<AuthResult> task) {
<add> Log.d(TAG, "createUser:onComplete:" + task.isSuccessful());
<add> hideProgressDialog();
<add>
<add> if (task.isSuccessful()) {
<add> onAuthSuccess(task.getResult().getUser());
<add> } else {
<add> Toast.makeText(SignInActivity.this, "Sign Up Failed",
<add> Toast.LENGTH_SHORT).show();
<add> }
<add> }
<add> });
<add> }
<add>
<add> private void onAuthSuccess(FirebaseUser user) {
<add> String username = usernameFromEmail(user.getEmail());
<add>
<add> // Write new user
<add> writeNewUser(user.getUid(), username, user.getEmail());
<add>
<add> // Go to MainActivity
<add> startActivity(new Intent(SignInActivity.this, MainActivity.class));
<add> finish();
<add> }
<add>
<add> private String usernameFromEmail(String email) {
<add> if (email.contains("@")) {
<add> return email.split("@")[0];
<add> } else {
<add> return email;
<add> }
<add> }
<add>
<add> private boolean validateForm() {
<add> boolean result = true;
<add> if (TextUtils.isEmpty(mEmailField.getText().toString())) {
<add> mEmailField.setError("Required");
<add> result = false;
<add> } else {
<add> mEmailField.setError(null);
<add> }
<add>
<add> if (TextUtils.isEmpty(mPasswordField.getText().toString())) {
<add> mPasswordField.setError("Required");
<add> result = false;
<add> } else {
<add> mPasswordField.setError(null);
<add> }
<add>
<add> return result;
<add> }
<add> //end email and password scripts
<add>
<add>
<add> // [START basic_write]
<add> private void writeNewUser(String userId, String name, String email) {
<add> User user = new User(name, email);
<add>
<add> mDatabase.child("users").child(userId).setValue(user);
<add> }
<add> // [END basic_write]
<add>
<add> private ProgressDialog mProgressDialog;
<add>
<add> public void showProgressDialog() {
<add> if (mProgressDialog == null) {
<add> mProgressDialog = new ProgressDialog(this);
<add> mProgressDialog.setCancelable(false);
<add> mProgressDialog.setMessage("Loading...");
<add> }
<add>
<add> mProgressDialog.show();
<add> }
<add>
<add> public void hideProgressDialog() {
<add> if (mProgressDialog != null && mProgressDialog.isShowing()) {
<add> mProgressDialog.dismiss();
<add> }
<add> }
<add>
<add> public String getUid() {
<add> return FirebaseAuth.getInstance().getCurrentUser().getUid();
<add> }
<add>
<ide> @Override
<ide> public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
<ide> // An unresolvable error has occurred and Google APIs (including Sign-In) will not
<ide> Log.d(TAG, "onConnectionFailed:" + connectionResult);
<ide> Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
<ide> }
<add>
<add> @Override
<add> public void onClick(View v) {
<add> switch (v.getId()){
<add> case R.id.sign_in_button_email:
<add> signIn();
<add> break;
<add> case R.id.sign_up_button_email:
<add> signUp();
<add> break;
<add> case R.id.sign_in_button:
<add> signInGoogle();
<add> break;
<add> }
<add> }
<ide> } |
|
JavaScript | mit | 08ff4d20ec39e2d53131a0e5bb4ec07d7501eca6 | 0 | Mithgol/rules-fe2hpt | var fs = require('fs');
var path = require('path');
var ansi = require('ansi')(process.stdout);
module.exports = function(workingDir, options){
var logFile = options.logFile;
var logOK = function(logElement){
ansi.black().bg.green().write(' OK ').reset().write(' ');
console.log(logElement);
if( logFile !== null ){
fs.appendFileSync(logFile, '[ OK ] ', { encoding: 'utf8' });
fs.appendFileSync(logFile, logElement + '\n', { encoding: 'utf8' });
}
};
var logFAIL = function(logElement){
ansi.brightWhite().bg.red().write(' FAIL ').reset().write(' ');
console.log(logElement);
if( logFile !== null ){
fs.appendFileSync(logFile, '[ FAIL ] ', { encoding: 'utf8' });
fs.appendFileSync(logFile, logElement + '\n', { encoding: 'utf8' });
}
};
var logDUPE = function(logElement){
ansi.brightCyan().bg.magenta().write(' DUPE ').reset().write(' ');
console.log(logElement);
if( logFile !== null ){
fs.appendFileSync(logFile, '[ DUPE ] ', { encoding: 'utf8' });
fs.appendFileSync(logFile, logElement + '\n', { encoding: 'utf8' });
}
};
var logSKIP = function(logElement){
ansi.brightGreen().bg.blue().write(' SKIP ').reset().write(' ');
console.log(logElement);
if( logFile !== null ){
fs.appendFileSync(logFile, '[ SKIP ] ', { encoding: 'utf8' });
fs.appendFileSync(logFile, logElement + '\n', { encoding: 'utf8' });
}
};
var usedNames = [];
var filenames = fs.readdirSync(workingDir);
filenames.forEach(function(nextFilename){
var fileLines = (function(fileDir, fileName){
try {
return fs.readFileSync(
path.join(fileDir, fileName),
{ encoding: 'utf8' }
).split(/[\r\n]+/);
} catch(e) {
if( options.rusMode ){
logFAIL([
'Файл ',
fileName,
' не может быть прочитан.'
].join(''));
} else {
logFAIL([
'File ',
fileName,
' cannot be read.'
].join(''));
}
return null;
}
})(workingDir, nextFilename);
if( fileLines === null ) return;
var firstLineParts = /^\s*[Aa][Rr][Ee][Aa]\s*:\s*(\S+)\s*$/.exec(
fileLines[0]
);
if( firstLineParts === null ){
if( options.rusMode ){
logSKIP([
'Файл ',
nextFilename,
' не выглядит как рулесы. Пропущен.'
].join(''));
} else {
logSKIP([
'File ',
nextFilename,
' does not seem like a rules file. Skipped.'
].join(''));
}
return;
}
var newName = firstLineParts[1].toUpperCase().replace(
/\./g, '_'
) + '.rul';
if( usedNames.indexOf(newName) > -1 ){
if( options.rusMode ){
logDUPE([
'Имя ',
newName,
' было использовано ранее. Файл ',
nextFilename,
' не может быть переименован.'
].join(''));
} else {
logDUPE([
'The name ',
newName,
' was used already. File ',
nextFilename,
' cannot be renamed.'
].join(''));
}
return;
}
var renamedFine = (function(fileDir, fileName, fileNewName){
try {
fs.renameSync(
path.join(fileDir, fileName),
path.join(fileDir, fileNewName)
);
return true;
} catch(e) {
if( options.rusMode ){
logFAIL([
'Файл ',
fileName,
' не может быть переименован в ',
fileNewName
].join(''));
} else {
logFAIL([
'File ',
fileName,
' cannot be renamed to ',
fileNewName
].join(''));
}
return false;
}
})(workingDir, nextFilename, newName);
if( renamedFine ){
if( options.rusMode ){
logOK([
'Файл ',
nextFilename,
' переименован в ',
newName
].join(''));
} else {
logOK([
'File ',
nextFilename,
' is renamed to ',
newName
].join(''));
}
}
});
}; | fe2h-api.js | var fs = require('fs');
var path = require('path');
var ansi = require('ansi')(process.stdout);
var logOK = function(logElement){
ansi.black().bg.green().write(' OK ').reset().write(' ');
console.log(logElement);
};
var logFAIL = function(logElement){
ansi.brightWhite().bg.red().write(' FAIL ').reset().write(' ');
console.log(logElement);
};
var logDUPE = function(logElement){
ansi.brightCyan().bg.magenta().write(' DUPE ').reset().write(' ');
console.log(logElement);
};
var logSKIP = function(logElement){
ansi.brightGreen().bg.blue().write(' SKIP ').reset().write(' ');
console.log(logElement);
};
module.exports = function(workingDir, options){
var usedNames = [];
var filenames = fs.readdirSync(workingDir);
filenames.forEach(function(nextFilename){
var fileLines = (function(fileDir, fileName){
try {
return fs.readFileSync(
path.join(fileDir, fileName),
{ encoding: 'utf8' }
).split(/[\r\n]+/);
} catch(e) {
if( options.rusMode ){
logFAIL([
'Файл ',
fileName,
' не может быть прочитан.'
].join(''));
} else {
logFAIL([
'File ',
fileName,
' cannot be read.'
].join(''));
}
return null;
}
})(workingDir, nextFilename);
if( fileLines === null ) return;
var firstLineParts = /^\s*[Aa][Rr][Ee][Aa]\s*:\s*(\S+)\s*$/.exec(
fileLines[0]
);
if( firstLineParts === null ){
if( options.rusMode ){
logSKIP([
'Файл ',
nextFilename,
' не выглядит как рулесы. Пропущен.'
].join(''));
} else {
logSKIP([
'File ',
nextFilename,
' does not seem like a rules file. Skipped.'
].join(''));
}
return;
}
var newName = firstLineParts[1].toUpperCase().replace(
/\./g, '_'
) + '.rul';
if( usedNames.indexOf(newName) > -1 ){
if( options.rusMode ){
logDUPE([
'Имя ',
newName,
' было использовано ранее. Файл ',
nextFilename,
' не может быть переименован.'
].join(''));
} else {
logDUPE([
'The name ',
newName,
' was used already. File ',
nextFilename,
' cannot be renamed.'
].join(''));
}
return;
}
var renamedFine = (function(fileDir, fileName, fileNewName){
try {
fs.renameSync(
path.join(fileDir, fileName),
path.join(fileDir, fileNewName)
);
return true;
} catch(e) {
if( options.rusMode ){
logFAIL([
'Файл ',
fileName,
' не может быть переименован в ',
fileNewName
].join(''));
} else {
logFAIL([
'File ',
fileName,
' cannot be renamed to ',
fileNewName
].join(''));
}
return false;
}
})(workingDir, nextFilename, newName);
if( renamedFine ){
if( options.rusMode ){
logOK([
'Файл ',
nextFilename,
' переименован в ',
newName
].join(''));
} else {
logOK([
'File ',
nextFilename,
' is renamed to ',
newName
].join(''));
}
}
});
}; | log to console and additionally to a file (if its name's been given)
| fe2h-api.js | log to console and additionally to a file (if its name's been given) | <ide><path>e2h-api.js
<ide> var path = require('path');
<ide> var ansi = require('ansi')(process.stdout);
<ide>
<del>var logOK = function(logElement){
<del> ansi.black().bg.green().write(' OK ').reset().write(' ');
<del> console.log(logElement);
<del>};
<add>module.exports = function(workingDir, options){
<add> var logFile = options.logFile;
<ide>
<del>var logFAIL = function(logElement){
<del> ansi.brightWhite().bg.red().write(' FAIL ').reset().write(' ');
<del> console.log(logElement);
<del>};
<add> var logOK = function(logElement){
<add> ansi.black().bg.green().write(' OK ').reset().write(' ');
<add> console.log(logElement);
<add> if( logFile !== null ){
<add> fs.appendFileSync(logFile, '[ OK ] ', { encoding: 'utf8' });
<add> fs.appendFileSync(logFile, logElement + '\n', { encoding: 'utf8' });
<add> }
<add> };
<ide>
<del>var logDUPE = function(logElement){
<del> ansi.brightCyan().bg.magenta().write(' DUPE ').reset().write(' ');
<del> console.log(logElement);
<del>};
<add> var logFAIL = function(logElement){
<add> ansi.brightWhite().bg.red().write(' FAIL ').reset().write(' ');
<add> console.log(logElement);
<add> if( logFile !== null ){
<add> fs.appendFileSync(logFile, '[ FAIL ] ', { encoding: 'utf8' });
<add> fs.appendFileSync(logFile, logElement + '\n', { encoding: 'utf8' });
<add> }
<add> };
<ide>
<del>var logSKIP = function(logElement){
<del> ansi.brightGreen().bg.blue().write(' SKIP ').reset().write(' ');
<del> console.log(logElement);
<del>};
<add> var logDUPE = function(logElement){
<add> ansi.brightCyan().bg.magenta().write(' DUPE ').reset().write(' ');
<add> console.log(logElement);
<add> if( logFile !== null ){
<add> fs.appendFileSync(logFile, '[ DUPE ] ', { encoding: 'utf8' });
<add> fs.appendFileSync(logFile, logElement + '\n', { encoding: 'utf8' });
<add> }
<add> };
<ide>
<del>module.exports = function(workingDir, options){
<add> var logSKIP = function(logElement){
<add> ansi.brightGreen().bg.blue().write(' SKIP ').reset().write(' ');
<add> console.log(logElement);
<add> if( logFile !== null ){
<add> fs.appendFileSync(logFile, '[ SKIP ] ', { encoding: 'utf8' });
<add> fs.appendFileSync(logFile, logElement + '\n', { encoding: 'utf8' });
<add> }
<add> };
<add>
<ide> var usedNames = [];
<ide> var filenames = fs.readdirSync(workingDir);
<ide> filenames.forEach(function(nextFilename){ |
|
Java | apache-2.0 | 1f8fb58ab5ec45d9dddcf6a5f34f2dfb946cc881 | 0 | MKLab-ITI/simmo-socialmedia-abstractions,MKLab-ITI/mklab-socialmedia-abstractions,socialsensor/socialmedia-abstractions | package eu.socialsensor.framework.streams;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import org.apache.log4j.Logger;
import eu.socialsensor.framework.common.domain.Feed;
import eu.socialsensor.framework.common.domain.Item;
import eu.socialsensor.framework.common.domain.StreamUser.Category;
import eu.socialsensor.framework.monitors.FeedsMonitor;
import eu.socialsensor.framework.retrievers.Retriever;
import eu.socialsensor.framework.subscribers.socialmedia.Subscriber;
/**
* Class handles the stream of information regarding a social network.
* It is responsible for its configuration, its wrapper's initialization
* and its retrieval process.
* @author manosetro
* @email [email protected]
* @author ailiakop
* @email [email protected]
*
*/
public abstract class Stream implements Runnable {
protected static final String KEY = "Key";
protected static final String SECRET = "Secret";
protected static final String ACCESS_TOKEN = "AccessToken";
protected static final String ACCESS_TOKEN_SECRET = "AccessTokenSecret";
protected static final String CLIENT_ID = "ClientId";
protected static final String MAX_RESULTS = "maxResults";
protected static final String MAX_REQUESTS = "maxRequests";
protected FeedsMonitor monitor;
protected BlockingQueue<Feed> feedsQueue;
protected Retriever retriever = null;
protected Subscriber subscriber = null;
protected StreamHandler handler;
private Logger logger = Logger.getLogger(Stream.class);
protected boolean isSubscriber = false;
private Map<String, Set<String>> usersToLists;
private Map<String,Category> usersToCategory;
/**
* Open a stream for updates delivery
* @param config
* Stream configuration parameters
* @throws StreamException
* In any case of error during stream open
*/
public abstract void open(StreamConfiguration config) throws StreamException;
/**
* Close a stream
* @throws StreamException
* In any case of error during stream close
*/
public void close() throws StreamException{
if(monitor != null)
monitor.stopMonitor();
if(retriever !=null)
retriever.stop();
if(subscriber != null)
subscriber.stop();
logger.info("Close Stream : "+this.getClass().getName());
}
/**
* Set the handler that is responsible for the handling
* of the retrieved items
* @param handler
*/
public void setHandler(StreamHandler handler){
this.handler = handler;
}
/**
* Sets the feeds monitor for the stream
* @return
*/
public boolean setMonitor(){
if(retriever == null)
return false;
monitor = new FeedsMonitor(retriever);
return true;
}
public void setUserLists(Map<String, Set<String>> usersToLists) {
this.usersToLists = usersToLists;
}
public void setUserCategories(Map<String, Category> usersToCategory) {
this.usersToCategory = usersToCategory;
}
public void setAsSubscriber(){
this.isSubscriber = true;
}
public synchronized void stream(List<Feed> feeds) throws StreamException {
if(subscriber != null){
subscriber.subscribe(feeds);
}
}
/**
* Searches with the wrapper of the stream for a particular
* set of feeds (feeds can be keywordsFeeds, userFeeds or locationFeeds)
* @param feeds
* @return the total number of retrieved items for the stream
* @throws StreamException
*/
public synchronized Integer poll(List<Feed> feeds) throws StreamException {
Integer totalRetrievedItems = 0;
if(retriever != null) {
if(feeds == null)
return totalRetrievedItems;
for(Feed feed : feeds){
totalRetrievedItems += retriever.retrieve(feed);
}
logger.info("Retrieved items for "+this.getClass().getName()+ " are : "+totalRetrievedItems);
}
return totalRetrievedItems;
}
/**
* Store a set of items in the selected databases
* @param items
*/
public synchronized void store(List<Item>items) {
for(Item item : items) {
store(item);
}
}
/**
* Store an item in the selected databases
* @param item
*/
public synchronized void store(Item item) {
if(handler == null) {
logger.error("NULL Handler!");
return;
}
if(usersToLists != null && getUserList(item) != null)
item.setList(getUserList(item));
if(usersToCategory != null && getUserCategory(item) != null)
item.setCategory(getUserCategory(item));
handler.update(item);
}
private String[] getUserList(Item item) {
Set<String> lists = new HashSet<String>();
if(usersToLists == null){
logger.error("User list is null");
return null;
}
if(item.getUserId() == null){
logger.error("User in item is null");
return null;
}
Set<String> userLists = usersToLists.get(item.getUserId());
if(userLists != null) {
lists.addAll(userLists);
}
for(String mention : item.getMentions()) {
userLists = usersToLists.get(mention);
if(userLists != null) {
lists.addAll(userLists);
}
}
String refUserId = item.getReferencedUserId();
if(refUserId != null) {
userLists = usersToLists.get(refUserId);
if(userLists != null) {
lists.addAll(userLists);
}
}
if(lists.size() > 0) {
logger.info(lists.size() + " associated lists found for " + item.getId());
return lists.toArray(new String[lists.size()]);
}
else {
logger.info("any associated list found for " + item.getId());
return null;
}
}
private Category getUserCategory(Item item){
if(usersToCategory == null){
logger.error("User categories is null");
return null;
}
if(item.getUserId() == null){
logger.error("User in item is null");
return null;
}
return usersToCategory.get(item.getUserId());
}
/**
* Deletes an item from the selected databases
* @param item
*/
public void delete(Item item){
handler.delete(item);
}
/**
* Adds a feed to the stream for future searching
* @param feed
* @return
*/
public boolean addFeed(Feed feed) {
if(feedsQueue == null)
return false;
return feedsQueue.offer(feed);
}
@Override
public void run() {
while(true) {
try {
Feed feed = feedsQueue.take();
monitor.addFeed(feed);
monitor.startMonitor(feed);
} catch (InterruptedException e) {
return;
}
}
}
}
| src/main/java/eu/socialsensor/framework/streams/Stream.java | package eu.socialsensor.framework.streams;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import org.apache.log4j.Logger;
import eu.socialsensor.framework.common.domain.Feed;
import eu.socialsensor.framework.common.domain.Item;
import eu.socialsensor.framework.common.domain.StreamUser.Category;
import eu.socialsensor.framework.monitors.FeedsMonitor;
import eu.socialsensor.framework.retrievers.Retriever;
import eu.socialsensor.framework.subscribers.socialmedia.Subscriber;
/**
* Class handles the stream of information regarding a social network.
* It is responsible for its configuration, its wrapper's initialization
* and its retrieval process.
* @author manosetro
* @email [email protected]
* @author ailiakop
* @email [email protected]
*
*/
public abstract class Stream implements Runnable {
protected static final String KEY = "Key";
protected static final String SECRET = "Secret";
protected static final String ACCESS_TOKEN = "AccessToken";
protected static final String ACCESS_TOKEN_SECRET = "AccessTokenSecret";
protected static final String CLIENT_ID = "ClientId";
protected static final String MAX_RESULTS = "maxResults";
protected static final String MAX_REQUESTS = "maxRequests";
protected FeedsMonitor monitor;
protected BlockingQueue<Feed> feedsQueue;
protected Retriever retriever = null;
protected Subscriber subscriber = null;
protected StreamHandler handler;
private Logger logger = Logger.getLogger(Stream.class);
protected boolean isSubscriber = false;
private Map<String, Set<String>> usersToLists;
private Map<String,Category> usersToCategory;
/**
* Open a stream for updates delivery
* @param config
* Stream configuration parameters
* @throws StreamException
* In any case of error during stream open
*/
public abstract void open(StreamConfiguration config) throws StreamException;
/**
* Close a stream
* @throws StreamException
* In any case of error during stream close
*/
public void close() throws StreamException{
if(monitor != null)
monitor.stopMonitor();
if(retriever !=null)
retriever.stop();
if(subscriber != null)
subscriber.stop();
logger.info("Close Stream : "+this.getClass().getName());
}
/**
* Set the handler that is responsible for the handling
* of the retrieved items
* @param handler
*/
public void setHandler(StreamHandler handler){
this.handler = handler;
}
/**
* Sets the feeds monitor for the stream
* @return
*/
public boolean setMonitor(){
if(retriever == null)
return false;
monitor = new FeedsMonitor(retriever);
return true;
}
public void setUserLists(Map<String, Set<String>> usersToLists) {
this.usersToLists = usersToLists;
}
public void setUserCategories(Map<String, Category> usersToCategory) {
this.usersToCategory = usersToCategory;
}
public void setAsSubscriber(){
this.isSubscriber = true;
}
public synchronized void stream(List<Feed> feeds) throws StreamException {
if(subscriber != null){
subscriber.subscribe(feeds);
}
}
/**
* Searches with the wrapper of the stream for a particular
* set of feeds (feeds can be keywordsFeeds, userFeeds or locationFeeds)
* @param feeds
* @return the total number of retrieved items for the stream
* @throws StreamException
*/
public synchronized Integer poll(List<Feed> feeds) throws StreamException {
Integer totalRetrievedItems = 0;
if(retriever != null) {
if(feeds == null)
return totalRetrievedItems;
for(Feed feed : feeds){
totalRetrievedItems += retriever.retrieve(feed);
}
logger.info("Retrieved items for "+this.getClass().getName()+ " are : "+totalRetrievedItems);
}
return totalRetrievedItems;
}
/**
* Store a set of items in the selected databases
* @param items
*/
public synchronized void store(List<Item>items) {
for(Item item : items) {
store(item);
}
}
/**
* Store an item in the selected databases
* @param item
*/
public synchronized void store(Item item) {
if(handler == null) {
logger.error("NULL Handler!");
return;
}
if(usersToLists != null && getUserList(item) != null)
item.setList(getUserList(item));
if(usersToCategory != null && getUserCategory(item) != null)
item.setCategory(getUserCategory(item));
handler.update(item);
}
private String[] getUserList(Item item) {
Set<String> lists = new HashSet<String>();
if(usersToLists == null){
logger.error("User list is null");
return null;
}
if(item.getUserId() == null){
logger.error("User in item is null");
return null;
}
Set<String> userLists = usersToLists.get(item.getUserId());
if(userLists != null) {
lists.addAll(userLists);
}
for(String mention : item.getMentions()) {
userLists = usersToLists.get(mention);
if(userLists != null) {
lists.addAll(userLists);
}
}
String refUserId = item.getReferencedUserId();
userLists = usersToLists.get(refUserId);
if(userLists != null) {
lists.addAll(userLists);
}
if(lists.size() > 0)
return lists.toArray(new String[lists.size()]);
else
return null;
}
private Category getUserCategory(Item item){
if(usersToCategory == null){
logger.error("User categories is null");
return null;
}
if(item.getUserId() == null){
logger.error("User in item is null");
return null;
}
return usersToCategory.get(item.getUserId());
}
/**
* Deletes an item from the selected databases
* @param item
*/
public void delete(Item item){
handler.delete(item);
}
/**
* Adds a feed to the stream for future searching
* @param feed
* @return
*/
public boolean addFeed(Feed feed) {
if(feedsQueue == null)
return false;
return feedsQueue.offer(feed);
}
@Override
public void run() {
while(true) {
try {
Feed feed = feedsQueue.take();
monitor.addFeed(feed);
monitor.startMonitor(feed);
} catch (InterruptedException e) {
return;
}
}
}
}
| Add logs in Stream.getUserList method | src/main/java/eu/socialsensor/framework/streams/Stream.java | Add logs in Stream.getUserList method | <ide><path>rc/main/java/eu/socialsensor/framework/streams/Stream.java
<ide> }
<ide>
<ide> String refUserId = item.getReferencedUserId();
<del> userLists = usersToLists.get(refUserId);
<del> if(userLists != null) {
<del> lists.addAll(userLists);
<del> }
<del>
<del> if(lists.size() > 0)
<add> if(refUserId != null) {
<add> userLists = usersToLists.get(refUserId);
<add> if(userLists != null) {
<add> lists.addAll(userLists);
<add> }
<add> }
<add>
<add> if(lists.size() > 0) {
<add> logger.info(lists.size() + " associated lists found for " + item.getId());
<ide> return lists.toArray(new String[lists.size()]);
<del> else
<del> return null;
<add> }
<add> else {
<add> logger.info("any associated list found for " + item.getId());
<add> return null;
<add> }
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | 0f78983e63f72b212c5f10a93b9c885c5eaaf01f | 0 | sktoo/timetabling-system-,maciej-zygmunt/unitime,nikeshmhr/unitime,zuzanamullerova/unitime,nikeshmhr/unitime,rafati/unitime,sktoo/timetabling-system-,UniTime/unitime,rafati/unitime,maciej-zygmunt/unitime,rafati/unitime,nikeshmhr/unitime,UniTime/unitime,zuzanamullerova/unitime,zuzanamullerova/unitime,sktoo/timetabling-system-,maciej-zygmunt/unitime,UniTime/unitime | /*
* UniTime 3.5 (University Timetabling Application)
* Copyright (C) 2014, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.gwt.mobile.client;
import org.unitime.timetable.gwt.client.Client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.RootPanel;
import com.googlecode.mgwt.ui.client.MGWT;
import com.googlecode.mgwt.ui.client.MGWTSettings;
/**
* @author Tomas Muller
*/
public class MobileClient extends Client {
@Override
public void onModuleLoadDeferred() {
MGWTSettings settings = new MGWTSettings();
settings.setViewPort(new Viewport());
settings.setFullscreen(true);
settings.setPreventScrolling(false);
settings.setIconUrl("images/unitime-phone.png");
settings.setFixIOS71BodyBug(true);
MGWT.applySettings(settings);
super.onModuleLoadDeferred();
// load components
for (final MobileComponents c: MobileComponents.values()) {
final RootPanel p = RootPanel.get(c.id());
if (p != null) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
initComponentAsync(p, c);
}
});
}
if (p == null && c.isMultiple()) {
NodeList<Element> x = getElementsByName(c.id());
if (x != null && x.getLength() > 0)
for (int i = 0; i < x.getLength(); i++) {
Element e = x.getItem(i);
e.setId(DOM.createUniqueId());
final RootPanel q = RootPanel.get(e.getId());
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
initComponentAsync(q, c);
}
});
}
}
}
}
public void initComponentAsync(final RootPanel panel, final MobileComponents comp) {
GWT.runAsync(new RunAsyncCallback() {
public void onSuccess() {
comp.insert(panel);
}
public void onFailure(Throwable reason) {
}
});
}
public static class Viewport extends MGWTSettings.ViewPort {
@Override
public String getContent() {
return "minimum-scale=0.25,maximum-scale=1.0,width=device-width,user-scalable=yes";
}
}
}
| JavaSource/org/unitime/timetable/gwt/mobile/client/MobileClient.java | /*
* UniTime 3.5 (University Timetabling Application)
* Copyright (C) 2014, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.gwt.mobile.client;
import org.unitime.timetable.gwt.client.Client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.RootPanel;
import com.googlecode.mgwt.ui.client.MGWT;
import com.googlecode.mgwt.ui.client.MGWTSettings;
import com.googlecode.mgwt.ui.client.MGWTSettings.ViewPort;
/**
* @author Tomas Muller
*/
public class MobileClient extends Client {
@Override
public void onModuleLoadDeferred() {
ViewPort viewPort = new MGWTSettings.ViewPort();
viewPort.setWidthToDeviceWidth();
viewPort.setUserScaleAble(true).setMinimumScale(0.25).setInitialScale(1.0).setMaximumScale(1.0);
MGWTSettings settings = new MGWTSettings();
settings.setViewPort(viewPort);
settings.setFullscreen(true);
settings.setPreventScrolling(false);
settings.setIconUrl("images/unitime-phone.png");
settings.setFixIOS71BodyBug(true);
MGWT.applySettings(settings);
super.onModuleLoadDeferred();
// load components
for (final MobileComponents c: MobileComponents.values()) {
final RootPanel p = RootPanel.get(c.id());
if (p != null) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
initComponentAsync(p, c);
}
});
}
if (p == null && c.isMultiple()) {
NodeList<Element> x = getElementsByName(c.id());
if (x != null && x.getLength() > 0)
for (int i = 0; i < x.getLength(); i++) {
Element e = x.getItem(i);
e.setId(DOM.createUniqueId());
final RootPanel q = RootPanel.get(e.getId());
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
initComponentAsync(q, c);
}
});
}
}
}
}
public void initComponentAsync(final RootPanel panel, final MobileComponents comp) {
GWT.runAsync(new RunAsyncCallback() {
public void onSuccess() {
comp.insert(panel);
}
public void onFailure(Throwable reason) {
}
});
}
}
| UniTime Mobile: few changes to the MGWT settings
- avoid setting initial-scale in the viewport meta tag (as the combination initial-scale=1.0,width=device-with seems to be the cause of locked scrolling in mobile Safari, landscape mode)
| JavaSource/org/unitime/timetable/gwt/mobile/client/MobileClient.java | UniTime Mobile: few changes to the MGWT settings - avoid setting initial-scale in the viewport meta tag (as the combination initial-scale=1.0,width=device-with seems to be the cause of locked scrolling in mobile Safari, landscape mode) | <ide><path>avaSource/org/unitime/timetable/gwt/mobile/client/MobileClient.java
<ide> import com.google.gwt.user.client.ui.RootPanel;
<ide> import com.googlecode.mgwt.ui.client.MGWT;
<ide> import com.googlecode.mgwt.ui.client.MGWTSettings;
<del>import com.googlecode.mgwt.ui.client.MGWTSettings.ViewPort;
<ide>
<ide> /**
<ide> * @author Tomas Muller
<ide>
<ide> @Override
<ide> public void onModuleLoadDeferred() {
<del> ViewPort viewPort = new MGWTSettings.ViewPort();
<del> viewPort.setWidthToDeviceWidth();
<del> viewPort.setUserScaleAble(true).setMinimumScale(0.25).setInitialScale(1.0).setMaximumScale(1.0);
<del>
<ide> MGWTSettings settings = new MGWTSettings();
<del> settings.setViewPort(viewPort);
<add> settings.setViewPort(new Viewport());
<ide> settings.setFullscreen(true);
<ide> settings.setPreventScrolling(false);
<ide> settings.setIconUrl("images/unitime-phone.png");
<ide> }
<ide> });
<ide> }
<add>
<add> public static class Viewport extends MGWTSettings.ViewPort {
<add> @Override
<add> public String getContent() {
<add> return "minimum-scale=0.25,maximum-scale=1.0,width=device-width,user-scalable=yes";
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | 28ec0d408af584eb82ec1547154a9eca1e8b7a5e | 0 | raphw/byte-buddy,raphw/byte-buddy,mches/byte-buddy,CodingFabian/byte-buddy,raphw/byte-buddy,DALDEI/byte-buddy | package net.bytebuddy.agent.builder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.modifier.*;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassInjector;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.dynamic.scaffold.inline.MethodNameTransformer;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import net.bytebuddy.implementation.ExceptionMethod;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.LoadedTypeInitializer;
import net.bytebuddy.implementation.MethodCall;
import net.bytebuddy.implementation.auxiliary.AuxiliaryType;
import net.bytebuddy.implementation.bytecode.*;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
import net.bytebuddy.implementation.bytecode.collection.ArrayFactory;
import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
import net.bytebuddy.implementation.bytecode.constant.NullConstant;
import net.bytebuddy.implementation.bytecode.constant.TextConstant;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import net.bytebuddy.implementation.bytecode.member.MethodReturn;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.JavaConstant;
import net.bytebuddy.utility.JavaModule;
import net.bytebuddy.utility.JavaType;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import java.io.*;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import static net.bytebuddy.matcher.ElementMatchers.*;
/**
* <p>
* An agent builder provides a convenience API for defining a
* <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html">Java agent</a>. By default,
* this transformation is applied by rebasing the type if not specified otherwise by setting a
* {@link TypeStrategy}.
* </p>
* <p>
* When defining several {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s, the agent builder always
* applies the transformers that were supplied with the last applicable matcher. Therefore, more general transformers
* should be defined first.
* </p>
*/
public interface AgentBuilder {
/**
* Defines the given {@link net.bytebuddy.ByteBuddy} instance to be used by the created agent.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @return A new instance of this agent builder which makes use of the given {@code byteBuddy} instance.
*/
AgentBuilder with(ByteBuddy byteBuddy);
/**
* Defines the given {@link net.bytebuddy.agent.builder.AgentBuilder.Listener} to be notified by the created agent.
* The given listener is notified after any other listener that is already registered. If a listener is registered
* twice, it is also notified twice.
*
* @param listener The listener to be notified.
* @return A new instance of this agent builder which creates an agent that informs the given listener about
* events.
*/
AgentBuilder with(Listener listener);
/**
* Defines the use of the given type locator for locating a {@link TypeDescription} for an instrumented type.
*
* @param typeLocator The type locator to use.
* @return A new instance of this agent builder which uses the given type locator for looking up class files.
*/
AgentBuilder with(TypeLocator typeLocator);
/**
* Defines the use of the given location strategy for locating binary data to given class names.
*
* @param locationStrategy The location strategy to use.
* @return A new instance of this agent builder which uses the given location strategy for looking up class files.
*/
AgentBuilder with(LocationStrategy locationStrategy);
/**
* Defines how types should be transformed, e.g. if they should be rebased or redefined by the created agent.
*
* @param typeStrategy The type strategy to use.
* @return A new instance of this agent builder which uses the given type strategy.
*/
AgentBuilder with(TypeStrategy typeStrategy);
/**
* Assures that critical actions are performed using the supplied access control context.
*
* @param accessControlContext The access control context to be used for performing security critical action.
* @return A new instance of this agent builder which uses the given access control context for performing critical actions.
*/
AgentBuilder with(AccessControlContext accessControlContext);
/**
* Defines a given initialization strategy to be applied to generated types. An initialization strategy is responsible
* for setting up a type after it was loaded. This initialization must be performed after the transformation because
* a Java agent is only invoked before loading a type. By default, the initialization logic is added to a class's type
* initializer which queries a global object for any objects that are to be injected into the generated type.
*
* @param initializationStrategy The initialization strategy to use.
* @return A new instance of this agent builder that applies the given initialization strategy.
*/
AgentBuilder with(InitializationStrategy initializationStrategy);
/**
* Specifies a strategy for modifying types that were already loaded prior to the installation of this transformer.
*
* @param redefinitionStrategy The redefinition strategy to apply.
* @return A new instance of this agent builder that applies the given redefinition strategy.
*/
AgentBuilder with(RedefinitionStrategy redefinitionStrategy);
/**
* <p>
* Enables or disables management of the JVM's {@code LambdaMetafactory} which is responsible for creating classes that
* implement lambda expressions. Without this feature enabled, classes that are represented by lambda expressions are
* not instrumented by the JVM such that Java agents have no effect on them when a lambda expression's class is loaded
* for the first time.
* </p>
* <p>
* When activating this feature, Byte Buddy instruments the {@code LambdaMetafactory} and takes over the responsibility
* of creating classes that represent lambda expressions. In doing so, Byte Buddy has the opportunity to apply the built
* class file transformer. If the current VM does not support lambda expressions, activating this feature has no effect.
* </p>
* <p>
* <b>Important</b>: If this feature is active, it is important to release the built class file transformer when
* deactivating it. Normally, it is sufficient to call {@link Instrumentation#removeTransformer(ClassFileTransformer)}.
* When this feature is enabled, it is however also required to invoke
* {@link LambdaInstrumentationStrategy#release(ClassFileTransformer, Instrumentation)}. Otherwise, the executing VMs class
* loader retains a reference to the class file transformer what can cause a memory leak.
* </p>
*
* @param lambdaInstrumentationStrategy {@code true} if this feature should be enabled.
* @return A new instance of this agent builder where this feature is explicitly enabled or disabled.
*/
AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy);
/**
* Specifies a strategy to be used for resolving {@link TypeDescription} for any type handled by the created transformer.
*
* @param descriptionStrategy The description strategy to use.
* @return A new instance of this agent builder that applies the given description strategy.
*/
AgentBuilder with(DescriptionStrategy descriptionStrategy);
/**
* Specifies an installation strategy that this agent builder applies upon installing an agent.
*
* @param installationStrategy The installation strategy to be used.
* @return A new agent builder that applies the supplied installation strategy.
*/
AgentBuilder with(InstallationStrategy installationStrategy);
/**
* Enables class injection of auxiliary classes into the bootstrap class loader.
*
* @param instrumentation The instrumentation instance that is used for appending jar files to the
* bootstrap class path.
* @param folder The folder in which jar files of the injected classes are to be stored.
* @return An agent builder with bootstrap class loader class injection enabled.
*/
AgentBuilder enableBootstrapInjection(Instrumentation instrumentation, File folder);
/**
* Enables the use of the given native method prefix for instrumented methods. Note that this prefix is also
* applied when preserving non-native methods. The use of this prefix is also registered when installing the
* final agent with an {@link java.lang.instrument.Instrumentation}.
*
* @param prefix The prefix to be used.
* @return A new instance of this agent builder which uses the given native method prefix.
*/
AgentBuilder enableNativeMethodPrefix(String prefix);
/**
* Disables the use of a native method prefix for instrumented methods.
*
* @return A new instance of this agent builder which does not use a native method prefix.
*/
AgentBuilder disableNativeMethodPrefix();
/**
* Disables injection of auxiliary classes into the bootstrap class path.
*
* @return A new instance of this agent builder which does not apply bootstrap class loader injection.
*/
AgentBuilder disableBootstrapInjection();
/**
* <p>
* Disables all implicit changes on a class file that Byte Buddy would apply for certain instrumentations. When
* using this option, it is no longer possible to rebase a method, i.e. intercepted methods are fully replaced. Furthermore,
* it is no longer possible to implicitly apply loaded type initializers for explicitly initializing the generated type.
* </p>
* <p>
* This is equivalent to setting {@link InitializationStrategy.NoOp} and {@link TypeStrategy.Default#REDEFINE_DECLARED_ONLY}
* as well as configuring the underlying {@link ByteBuddy} instance to use a {@link net.bytebuddy.implementation.Implementation.Context.Disabled}.
* </p>
*
* @return A new instance of this agent builder that does not apply any implicit changes to the received class file.
*/
AgentBuilder disableClassFormatChanges();
/**
* Assures that all modules of the supplied types are read by the module of any instrumented type. If the current VM does not support
* the Java module system, calling this method has no effect and this instance is returned.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param type The types for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type);
/**
* Assures that all supplied modules are read by the module of any instrumented type.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param module The modules for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module);
/**
* Assures that all supplied modules are read by the module of any instrumented type.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param modules The modules for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules);
/**
* Assures that all modules of the supplied types are read by the module of any instrumented type and vice versa.
* If the current VM does not support the Java module system, calling this method has no effect and this instance is returned.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param type The types for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type);
/**
* Assures that all supplied modules are read by the module of any instrumented type and vice versa.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param module The modules for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module);
/**
* Assures that all supplied modules are read by the module of any instrumented type and vice versa.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param modules The modules for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, this matcher is always executed first whereas the following matchers are
* executed in the order of their execution. If any matcher indicates that a type is to be matched, none of the following matchers is still queried.
* This behavior can be changed by {@link Identified.Extendable#asDecorator()} where subsequent type matchers are also applied.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it is
* also recommended, to exclude class loaders such as for example the bootstrap class loader by using
* {@link AgentBuilder#type(ElementMatcher, ElementMatcher)} instead.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being loaded that
* decides if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should
* be applied for that type.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code typeMatcher}
* indicates a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, this matcher is always executed first whereas the following matchers are
* executed in the order of their execution. If any matcher indicates that a type is to be matched, none of the following matchers is still queried.
* This behavior can be changed by {@link Identified.Extendable#asDecorator()} where subsequent type matchers are also applied.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being
* loaded that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for
* that type.
* @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the
* {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher
* is always applied first where the type matcher is not applied in case that this
* matcher does not indicate a match.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given
* {@code typeMatcher} and {@code classLoaderMatcher} indicate a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, this matcher is always executed first whereas the following matchers are
* executed in the order of their execution. If any matcher indicates that a type is to be matched, none of the following matchers is still queried.
* This behavior can be changed by {@link Identified.Extendable#asDecorator()} where subsequent type matchers are also applied.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being
* loaded that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for
* that type.
* @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the
* {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher
* is always applied second where the type matcher is not applied in case that this
* matcher does not indicate a match.
* @param moduleMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the {@link JavaModule}
* of the type being loaded. This matcher is always applied first where the class loader and
* type matchers are not applied in case that this matcher does not indicate a match. On a JVM
* that does not support the Java modules system, this matcher is not applied.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given
* {@code typeMatcher} and {@code classLoaderMatcher} indicate a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, this matcher is always executed first whereas the following matchers are
* executed in the order of their execution. If any matcher indicates that a type is to be matched, none of the following matchers is still queried.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param matcher A matcher that decides if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be
* applied for a type that is being loaded.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code matcher}
* indicates a match.
*/
Identified.Narrowable type(RawMatcher matcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher from instrumentation and considers types by all {@link ClassLoader}s.
* By default, Byte Buddy does not instrument synthetic types or types that are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher and is loaded by a class loader matching the second matcher.
* By default, Byte Buddy does not instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that
* are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @param classLoaderMatcher A matcher that identifies a class loader that identifies classes that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher and is loaded by a class loader matching the second matcher.
* By default, Byte Buddy does not instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that
* are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @param classLoaderMatcher A matcher that identifies a class loader that identifies classes that should not be instrumented.
* @param moduleMatcher A matcher that identifies a module that identifies classes that should not be instrumented. On a JVM
* that does not support the Java modules system, this matcher is not applied.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* <p>
* Excludes any type that is matched by the raw matcher provided to this method. By default, Byte Buddy does not
* instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param rawMatcher A raw matcher that identifies types that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(RawMatcher rawMatcher);
/**
* Creates a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of this
* agent builder.
*
* @return A class file transformer that implements the configuration of this agent builder.
*/
ClassFileTransformer makeRaw();
/**
* <p>
* Creates and installs a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of
* this agent builder with a given {@link java.lang.instrument.Instrumentation}. If retransformation is enabled,
* the installation also causes all loaded types to be retransformed.
* </p>
* <p>
* If installing the created class file transformer causes an exception to be thrown, the consequences of this
* exception are determined by the {@link InstallationStrategy} of this builder.
* </p>
*
* @param instrumentation The instrumentation on which this agent builder's configuration is to be installed.
* @return The installed class file transformer.
*/
ClassFileTransformer installOn(Instrumentation instrumentation);
/**
* Creates and installs a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of
* this agent builder with the Byte Buddy-agent which must be installed prior to calling this method.
*
* @return The installed class file transformer.
* @see AgentBuilder#installOn(Instrumentation)
*/
ClassFileTransformer installOnByteBuddyAgent();
/**
* An abstraction for extending a matcher.
*
* @param <T> The type that is produced by chaining a matcher.
*/
interface Matchable<T extends Matchable<T>> {
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched. When matching a
* type, class loaders are not considered.
*
* @param typeMatcher A matcher for the type being matched.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @param moduleMatcher A matcher for the type's module. On a JVM that does not support modules, the Java module is represented by {@code null}.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param rawMatcher A raw matcher for the type being matched.
* @return A chained matcher.
*/
T and(RawMatcher rawMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched. When matching a
* type, the class loader is not considered.
*
* @param typeMatcher A matcher for the type being matched.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @param moduleMatcher A matcher for the type's module. On a JVM that does not support modules, the Java module is represented by {@code null}.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param rawMatcher A raw matcher for the type being matched.
* @return A chained matcher.
*/
T or(RawMatcher rawMatcher);
/**
* An abstract base implementation of a matchable.
*
* @param <S> The type that is produced by chaining a matcher.
*/
abstract class AbstractBase<S extends Matchable<S>> implements Matchable<S> {
@Override
public S and(ElementMatcher<? super TypeDescription> typeMatcher) {
return and(typeMatcher, any());
}
@Override
public S and(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return and(typeMatcher, classLoaderMatcher, any());
}
@Override
public S and(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return and(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, moduleMatcher));
}
@Override
public S or(ElementMatcher<? super TypeDescription> typeMatcher) {
return or(typeMatcher, any());
}
@Override
public S or(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return or(typeMatcher, classLoaderMatcher, any());
}
@Override
public S or(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return or(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, moduleMatcher));
}
}
}
/**
* Allows to further specify ignored types.
*/
interface Ignored extends Matchable<Ignored>, AgentBuilder {
/* this is merely a unionizing interface that does not declare methods */
}
/**
* Describes an {@link net.bytebuddy.agent.builder.AgentBuilder} which was handed a matcher for identifying
* types to instrumented in order to supply one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*/
interface Identified {
/**
* Applies the given transformer for the already supplied matcher.
*
* @param transformer The transformer to apply.
* @return A new instance of this agent builder with the transformer being applied when the previously supplied matcher
* identified a type for instrumentation which also allows for the registration of subsequent transformers.
*/
Extendable transform(Transformer transformer);
/**
* Allows to specify a type matcher for a type to instrument.
*/
interface Narrowable extends Matchable<Narrowable>, Identified {
/* this is merely a unionizing interface that does not declare methods */
}
/**
* This interface is used to allow for optionally providing several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} to applied when a matcher identifies a type
* to be instrumented. Any subsequent transformers are applied in the order they are registered.
*/
interface Extendable extends AgentBuilder, Identified {
/**
* <p>
* Applies the specified transformation as a decorative transformation. For a decorative transformation, the supplied
* transformer is prepended to any previous transformation that also matches the instrumented type, i.e. both transformations
* are supplied. This procedure is repeated until a transformer is reached that matches the instrumented type but is not
* defined as decorating after which no further transformations are considered. If all matching transformations are declared
* as decorating, all matching transformers are applied.
* </p>
* <p>
* <b>Note</b>: A decorating transformer is applied <b>after</b> previously registered transformers.
* </p>
*
* @return A new instance of this agent builder with the specified transformation being applied as a decorator.
*/
AgentBuilder asDecorator();
}
}
/**
* A matcher that allows to determine if a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}
* should be applied during the execution of a {@link java.lang.instrument.ClassFileTransformer} that was
* generated by an {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface RawMatcher {
/**
* Decides if the given {@code typeDescription} should be instrumented with the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*
* @param typeDescription A description of the type to be instrumented.
* @param classLoader The class loader of the instrumented type. Might be {@code null} if this class
* loader represents the bootstrap class loader.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param classBeingRedefined The class being redefined which is only not {@code null} if a retransformation
* is applied.
* @param protectionDomain The protection domain of the type being transformed.
* @return {@code true} if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should
* be applied for the given {@code typeDescription}.
*/
boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain);
/**
* A conjunction of two raw matchers.
*/
class Conjunction implements RawMatcher {
/**
* The left matcher which is applied first.
*/
private final RawMatcher left;
/**
* The right matcher which is applied second.
*/
private final RawMatcher right;
/**
* Creates a new conjunction of two raw matchers.
*
* @param left The left matcher which is applied first.
* @param right The right matcher which is applied second.
*/
protected Conjunction(RawMatcher left, RawMatcher right) {
this.left = left;
this.right = right;
}
@Override
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return left.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
&& right.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Conjunction that = (Conjunction) object;
return left.equals(that.left) && right.equals(that.right);
}
@Override
public int hashCode() {
int result = left.hashCode();
result = 31 * result + right.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.RawMatcher.Conjunction{" +
"left=" + left +
", right=" + right +
'}';
}
}
/**
* A disjunction of two raw matchers.
*/
class Disjunction implements RawMatcher {
/**
* The left matcher which is applied first.
*/
private final RawMatcher left;
/**
* The right matcher which is applied second.
*/
private final RawMatcher right;
/**
* Creates a new disjunction of two raw matchers.
*
* @param left The left matcher which is applied first.
* @param right The right matcher which is applied second.
*/
protected Disjunction(RawMatcher left, RawMatcher right) {
this.left = left;
this.right = right;
}
@Override
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return left.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
|| right.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Disjunction that = (Disjunction) object;
return left.equals(that.left) && right.equals(that.right);
}
@Override
public int hashCode() {
int result = left.hashCode();
result = 31 * result + right.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.RawMatcher.Disjunction{" +
"left=" + left +
", right=" + right +
'}';
}
}
/**
* A raw matcher implementation that checks a {@link TypeDescription}
* and its {@link java.lang.ClassLoader} against two suitable matchers in order to determine if the matched
* type should be instrumented.
*/
class ForElementMatchers implements RawMatcher {
/**
* The type matcher to apply to a {@link TypeDescription}.
*/
private final ElementMatcher<? super TypeDescription> typeMatcher;
/**
* The class loader matcher to apply to a {@link java.lang.ClassLoader}.
*/
private final ElementMatcher<? super ClassLoader> classLoaderMatcher;
/**
* A module matcher to apply to a {@code java.lang.reflect.Module}.
*/
private final ElementMatcher<? super JavaModule> moduleMatcher;
/**
* Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the
* supplied {@link TypeDescription} and its {@link java.lang.ClassLoader} against two matcher in order
* to decided if an instrumentation should be conducted.
*
* @param typeMatcher The type matcher to apply to a {@link TypeDescription}.
* @param classLoaderMatcher The class loader matcher to apply to a {@link java.lang.ClassLoader}.
* @param moduleMatcher A module matcher to apply to a {@code java.lang.reflect.Module}.
*/
public ForElementMatchers(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
this.typeMatcher = typeMatcher;
this.classLoaderMatcher = classLoaderMatcher;
this.moduleMatcher = moduleMatcher;
}
@Override
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return moduleMatcher.matches(module) && classLoaderMatcher.matches(classLoader) && typeMatcher.matches(typeDescription);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& classLoaderMatcher.equals(((ForElementMatchers) other).classLoaderMatcher)
&& moduleMatcher.equals(((ForElementMatchers) other).moduleMatcher)
&& typeMatcher.equals(((ForElementMatchers) other).typeMatcher);
}
@Override
public int hashCode() {
int result = typeMatcher.hashCode();
result = 31 * result + classLoaderMatcher.hashCode();
result = 31 * result + moduleMatcher.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.RawMatcher.ForElementMatchers{" +
"typeMatcher=" + typeMatcher +
", classLoaderMatcher=" + classLoaderMatcher +
", moduleMatcher=" + moduleMatcher +
'}';
}
}
}
/**
* A type strategy is responsible for creating a type builder for a type that is being instrumented.
*/
interface TypeStrategy {
/**
* Creates a type builder for a given type.
*
* @param typeDescription The type being instrumented.
* @param byteBuddy The Byte Buddy configuration.
* @param classFileLocator The class file locator to use.
* @param methodNameTransformer The method name transformer to use.
* @return A type builder for the given arguments.
*/
DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer);
/**
* Default implementations of type strategies.
*/
enum Default implements TypeStrategy {
/**
* A definition handler that performs a rebasing for all types.
*/
REBASE {
@Override
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer) {
return byteBuddy.rebase(typeDescription, classFileLocator, methodNameTransformer);
}
},
/**
* <p>
* A definition handler that performs a redefinition for all types.
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
REDEFINE {
@Override
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer) {
return byteBuddy.redefine(typeDescription, classFileLocator);
}
},
/**
* <p>
* A definition handler that performs a redefinition for all types and ignores all methods that were not declared by the instrumented type.
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
REDEFINE_DECLARED_ONLY {
@Override
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer) {
return byteBuddy.redefine(typeDescription, classFileLocator).ignoreAlso(not(isDeclaredBy(typeDescription)));
}
};
@Override
public String toString() {
return "AgentBuilder.TypeStrategy.Default." + name();
}
}
}
/**
* A transformer allows to apply modifications to a {@link net.bytebuddy.dynamic.DynamicType}. Such a modification
* is then applied to any instrumented type that was matched by the preceding matcher.
*/
interface Transformer {
/**
* Allows for a transformation of a {@link net.bytebuddy.dynamic.DynamicType.Builder}.
*
* @param builder The dynamic builder to transform.
* @param typeDescription The description of the type currently being instrumented.
* @param classLoader The class loader of the instrumented class. Might be {@code null} to
* represent the bootstrap class loader.
* @return A transformed version of the supplied {@code builder}.
*/
DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader);
/**
* A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} that does
* not modify the supplied dynamic type.
*/
enum NoOp implements Transformer {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader) {
return builder;
}
@Override
public String toString() {
return "AgentBuilder.Transformer.NoOp." + name();
}
}
/**
* A compound transformer that allows to group several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s as a single transformer.
*/
class Compound implements Transformer {
/**
* The transformers to apply in their application order.
*/
private final Transformer[] transformer;
/**
* Creates a new compound transformer.
*
* @param transformer The transformers to apply in their application order.
*/
public Compound(Transformer... transformer) {
this.transformer = transformer;
}
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader) {
for (Transformer transformer : this.transformer) {
builder = transformer.transform(builder, typeDescription, classLoader);
}
return builder;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& Arrays.equals(transformer, ((Compound) other).transformer);
}
@Override
public int hashCode() {
return Arrays.hashCode(transformer);
}
@Override
public String toString() {
return "AgentBuilder.Transformer.Compound{" +
"transformer=" + Arrays.toString(transformer) +
'}';
}
}
}
/**
* A type locator allows to specify how {@link TypeDescription}s are resolved by an {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface TypeLocator {
/**
* Creates a type pool for a given class file locator.
*
* @param classFileLocator The class file locator to use.
* @param classLoader The class loader for which the class file locator was created.
* @return A type pool for the supplied class file locator.
*/
TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader);
/**
* A default implementation of a {@link TypeLocator} that is using a {@link net.bytebuddy.pool.TypePool.Default} with a
* {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple}.
*/
enum Default implements TypeLocator {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
Default(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
@Override
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.LazyFacade(new TypePool.Default(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode));
}
@Override
public String toString() {
return "AgentBuilder.TypeLocator.Default." + name();
}
}
/**
* An implementation of a {@link TypeLocator} that is using a {@link net.bytebuddy.pool.TypePool.Default} with a
* {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple}. Additionally, this type locator falls back to class
* loadings for non-locatable class files.
*/
enum ClassLoading implements TypeLocator {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
ClassLoading(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
@Override
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.LazyFacade(TypePool.ClassLoading.of(classLoader, new TypePool.Default(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode)));
}
@Override
public String toString() {
return "AgentBuilder.TypeLocator.ClassLoading." + name();
}
}
/**
* A type locator that uses type pools but allows for the configuration of a custom cache provider by class loader. Note that a
* {@link TypePool} can grow in size and that a static reference is kept to this pool by Byte Buddy's registration of a
* {@link ClassFileTransformer} what can cause a memory leak if the supplied caches are not cleared on a regular basis. Also note
* that a cache provider can be accessed concurrently by multiple {@link ClassLoader}s.
*/
abstract class WithTypePoolCache implements TypeLocator {
/**
* The reader mode to use for parsing a class file.
*/
protected final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator that creates {@link TypePool}s but provides a custom {@link net.bytebuddy.pool.TypePool.CacheProvider}.
*
* @param readerMode The reader mode to use for parsing a class file.
*/
protected WithTypePoolCache(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
@Override
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.LazyFacade(new TypePool.Default(locate(classLoader), classFileLocator, readerMode));
}
/**
* Locates a cache provider for a given class loader.
*
* @param classLoader The class loader for which to locate a cache. This class loader might be {@code null} to represent the bootstrap loader.
* @return The cache provider to use.
*/
protected abstract TypePool.CacheProvider locate(ClassLoader classLoader);
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
WithTypePoolCache that = (WithTypePoolCache) object;
return readerMode == that.readerMode;
}
@Override
public int hashCode() {
return readerMode.hashCode();
}
/**
* An implementation of a type locator {@link WithTypePoolCache} (note documentation of the linked class) that is based on a
* {@link ConcurrentMap}. It is the responsibility of the type locator's user to avoid the type locator from leaking memory.
*/
public static class Simple extends WithTypePoolCache {
/**
* The concurrent map that is used for storing a cache provider per class loader.
*/
private final ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders;
/**
* Creates a new type locator that caches a cache provider per class loader in a concurrent map. The type
* locator uses a fast {@link net.bytebuddy.pool.TypePool.Default.ReaderMode}.
*
* @param cacheProviders The concurrent map that is used for storing a cache provider per class loader.
*/
public Simple(ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders) {
this(TypePool.Default.ReaderMode.FAST, cacheProviders);
}
/**
* Creates a new type locator that caches a cache provider per class loader in a concurrent map.
*
* @param readerMode The reader mode to use for parsing a class file.
* @param cacheProviders The concurrent map that is used for storing a cache provider per class loader.
*/
public Simple(TypePool.Default.ReaderMode readerMode, ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders) {
super(readerMode);
this.cacheProviders = cacheProviders;
}
@Override
protected TypePool.CacheProvider locate(ClassLoader classLoader) {
classLoader = classLoader == null ? BootstrapClassLoaderMarker.INSTANCE : classLoader;
TypePool.CacheProvider cacheProvider = cacheProviders.get(classLoader);
while (cacheProvider == null) {
cacheProviders.putIfAbsent(classLoader, TypePool.CacheProvider.Simple.withObjectType());
cacheProvider = cacheProviders.get(classLoader);
}
return cacheProvider;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
if (!super.equals(object)) return false;
Simple simple = (Simple) object;
return cacheProviders.equals(simple.cacheProviders);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + cacheProviders.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.TypeLocator.WithTypePoolCache.Simple{" +
"cacheProviders=" + cacheProviders +
'}';
}
/**
* A marker for the bootstrap class loader which is represented by {@code null}.
*/
private static class BootstrapClassLoaderMarker extends ClassLoader {
/**
* A static reference to the a singleton instance of the marker to preserve reference equality.
*/
protected static final ClassLoader INSTANCE = AccessController.doPrivileged(new CreationAction());
@Override
protected Class<?> loadClass(String name, boolean resolve) {
throw new UnsupportedOperationException("This loader is only a non-null marker and is not supposed to be used");
}
/**
* A simple action for creating a bootstrap class loader marker.
*/
private static class CreationAction implements PrivilegedAction<ClassLoader> {
@Override
public ClassLoader run() {
return new BootstrapClassLoaderMarker();
}
}
}
}
}
}
/**
* A listener that is informed about events that occur during an instrumentation process.
*/
interface Listener {
/**
* Invoked right before a successful transformation is applied.
*
* @param typeDescription The type that is being transformed.
* @param classLoader The class loader which is loading this type.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param dynamicType The dynamic type that was created.
*/
void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType);
/**
* Invoked when a type is not transformed but ignored.
*
* @param typeDescription The type being ignored for transformation.
* @param classLoader The class loader which is loading this type.
* @param module The ignored type's module or {@code null} if the current VM does not support modules.
*/
void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module);
/**
* Invoked when an error has occurred during transformation.
*
* @param typeName The type name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param throwable The occurred error.
*/
void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable);
/**
* Invoked after a class was attempted to be loaded, independently of its treatment.
*
* @param typeName The binary name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
*/
void onComplete(String typeName, ClassLoader classLoader, JavaModule module);
/**
* A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Listener}.
*/
enum NoOp implements Listener {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
/* do nothing */
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
/* do nothing */
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable) {
/* do nothing */
}
@Override
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module) {
/* do nothing */
}
@Override
public String toString() {
return "AgentBuilder.Listener.NoOp." + name();
}
}
/**
* An adapter for a listener wher all methods are implemented as non-operational.
*/
abstract class Adapter implements Listener {
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
/* do nothing */
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
/* do nothing */
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable) {
/* do nothing */
}
@Override
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module) {
/* do nothing */
}
}
/**
* A listener that writes events to a {@link PrintStream}. This listener prints a line per event, including the event type and
* the name of the type in question.
*/
class StreamWriting implements Listener {
/**
* The prefix that is appended to all written messages.
*/
protected static final String PREFIX = "[Byte Buddy]";
/**
* The print stream written to.
*/
private final PrintStream printStream;
/**
* Creates a new stream writing listener.
*
* @param printStream The print stream written to.
*/
public StreamWriting(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Creates a new stream writing listener that writes to {@link System#out}.
*
* @return A listener writing events to the standard output stream.
*/
public static Listener toSystemOut() {
return new StreamWriting(System.out);
}
/**
* Creates a new stream writing listener that writes to {@link System#err}.
*
* @return A listener writing events to the standad error stream.
*/
public static Listener toSystemError() {
return new StreamWriting(System.err);
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
printStream.println(PREFIX + " TRANSFORM " + typeDescription.getName() + "[" + classLoader + ", " + module + "]");
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
printStream.println(PREFIX + " IGNORE " + typeDescription.getName() + "[" + classLoader + ", " + module + "]");
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable) {
printStream.println(PREFIX + " ERROR " + typeName + "[" + classLoader + ", " + module + "]");
throwable.printStackTrace(printStream);
}
@Override
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module) {
printStream.println(PREFIX + " COMPLETE " + typeName + "[" + classLoader + ", " + module + "]");
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& printStream.equals(((StreamWriting) other).printStream);
}
@Override
public int hashCode() {
return printStream.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Listener.StreamWriting{" +
"printStream=" + printStream +
'}';
}
}
/**
* A listener that adds read-edges to any module of an instrumented class upon its transformation.
*/
class ModuleReadEdgeCompleting extends Listener.Adapter {
/**
* The instrumentation instance used for adding read edges.
*/
private final Instrumentation instrumentation;
/**
* {@code true} if the listener should also add a read-edge from the supplied modules to the instrumented type's module.
*/
private final boolean addTargetEdge;
/**
* The modules to add as a read edge to any transformed class's module.
*/
private final Set<? extends JavaModule> modules;
/**
* Creates a new module read-edge completing listener.
*
* @param instrumentation The instrumentation instance used for adding read edges.
* @param addTargetEdge {@code true} if the listener should also add a read-edge from the supplied modules
* to the instrumented type's module.
* @param modules The modules to add as a read edge to any transformed class's module.
*/
public ModuleReadEdgeCompleting(Instrumentation instrumentation, boolean addTargetEdge, Set<? extends JavaModule> modules) {
this.instrumentation = instrumentation;
this.addTargetEdge = addTargetEdge;
this.modules = modules;
}
/**
* Resolves a listener that adds module edges from and to the instrumented type's module.
*
* @param instrumentation The instrumentation instance used for adding read edges.
* @param addTargetEdge {@code true} if the listener should also add a read-edge from the supplied
* modules to the instrumented type's module.
* @param type The types for which to extract the modules.
* @return An appropriate listener.
*/
protected static Listener of(Instrumentation instrumentation, boolean addTargetEdge, Class<?>... type) {
Set<JavaModule> modules = new HashSet<JavaModule>();
for (Class<?> aType : type) {
JavaModule module = JavaModule.ofType(aType);
if (module.isNamed()) {
modules.add(module);
}
}
return modules.isEmpty()
? Listener.NoOp.INSTANCE
: new Listener.ModuleReadEdgeCompleting(instrumentation, addTargetEdge, modules);
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
if (module != null && module.isNamed()) {
for (JavaModule target : modules) {
if (!module.canRead(target)) {
module.addReads(instrumentation, target);
}
if (addTargetEdge && !target.canRead(module)) {
target.addReads(instrumentation, module);
}
}
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ModuleReadEdgeCompleting that = (ModuleReadEdgeCompleting) object;
return instrumentation.equals(that.instrumentation)
&& addTargetEdge == that.addTargetEdge
&& modules.equals(that.modules);
}
@Override
public int hashCode() {
int result = instrumentation.hashCode();
result = 31 * result + modules.hashCode();
result = 31 * result + (addTargetEdge ? 1 : 0);
return result;
}
@Override
public String toString() {
return "AgentBuilder.Listener.ModuleReadEdgeCompleting{" +
"instrumentation=" + instrumentation +
", addTargetEdge=" + addTargetEdge +
", modules=" + modules +
'}';
}
}
/**
* A compound listener that allows to group several listeners in one instance.
*/
class Compound implements Listener {
/**
* The listeners that are represented by this compound listener in their application order.
*/
private final List<? extends Listener> listeners;
/**
* Creates a new compound listener.
*
* @param listener The listeners to apply in their application order.
*/
public Compound(Listener... listener) {
this(Arrays.asList(listener));
}
/**
* Creates a new compound listener.
*
* @param listeners The listeners to apply in their application order.
*/
public Compound(List<? extends Listener> listeners) {
this.listeners = listeners;
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
for (Listener listener : listeners) {
listener.onTransformation(typeDescription, classLoader, module, dynamicType);
}
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
for (Listener listener : listeners) {
listener.onIgnored(typeDescription, classLoader, module);
}
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable) {
for (Listener listener : listeners) {
listener.onError(typeName, classLoader, module, throwable);
}
}
@Override
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module) {
for (Listener listener : listeners) {
listener.onComplete(typeName, classLoader, module);
}
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& listeners.equals(((Compound) other).listeners);
}
@Override
public int hashCode() {
return listeners.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Listener.Compound{" +
"listeners=" + listeners +
'}';
}
}
}
/**
* An initialization strategy which determines the handling of {@link net.bytebuddy.implementation.LoadedTypeInitializer}s
* and the loading of auxiliary types.
*/
interface InitializationStrategy {
/**
* Creates a new dispatcher for injecting this initialization strategy during a transformation process.
*
* @return The dispatcher to be used.
*/
Dispatcher dispatcher();
/**
* A dispatcher for changing a class file to adapt a self-initialization strategy.
*/
interface Dispatcher {
/**
* Transforms the instrumented type to implement an appropriate initialization strategy.
*
* @param builder The builder which should implement the initialization strategy.
* @return The given {@code builder} with the initialization strategy applied.
*/
DynamicType.Builder<?> apply(DynamicType.Builder<?> builder);
/**
* Registers a dynamic type for initialization and/or begins the initialization process.
*
* @param dynamicType The dynamic type that is created.
* @param classLoader The class loader of the dynamic type.
* @param injectorFactory The injector factory
*/
void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory);
/**
* A factory for creating a {@link ClassInjector} only if it is required.
*/
interface InjectorFactory {
/**
* Resolves the class injector for this factory.
*
* @return The class injector for this factory.
*/
ClassInjector resolve();
}
}
/**
* A non-initializing initialization strategy.
*/
enum NoOp implements InitializationStrategy, Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Dispatcher dispatcher() {
return this;
}
@Override
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder;
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
/* do nothing */
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.NoOp." + name();
}
}
/**
* An initialization strategy that adds a code block to an instrumented type's type initializer which
* then calls a specific class that is responsible for the explicit initialization.
*/
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE", justification = "Avoiding synchronization without security concerns")
enum SelfInjection implements InitializationStrategy {
/**
* A form of self-injection where auxiliary types that are annotated by
* {@link net.bytebuddy.implementation.auxiliary.AuxiliaryType.SignatureRelevant} of the instrumented type are loaded lazily and
* any other auxiliary type is loaded eagerly.
*/
SPLIT {
@Override
public InitializationStrategy.Dispatcher dispatcher() {
return new SelfInjection.Dispatcher.Split(new Random().nextInt());
}
},
/**
* A form of self-injection where any auxiliary type is loaded lazily.
*/
LAZY {
@Override
public InitializationStrategy.Dispatcher dispatcher() {
return new SelfInjection.Dispatcher.Lazy(new Random().nextInt());
}
},
/**
* A form of self-injection where any auxiliary type is loaded eagerly.
*/
EAGER {
@Override
public InitializationStrategy.Dispatcher dispatcher() {
return new SelfInjection.Dispatcher.Eager(new Random().nextInt());
}
};
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection." + name();
}
/**
* A dispatcher for a self-initialization strategy.
*/
protected abstract static class Dispatcher implements InitializationStrategy.Dispatcher {
/**
* A random identification for the applied self-initialization.
*/
protected final int identification;
/**
* Creates a new dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(int identification) {
this.identification = identification;
}
@Override
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder.initializer(NexusAccessor.INSTANCE.identifiedBy(identification));
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& identification == ((Dispatcher) other).identification;
}
@Override
public int hashCode() {
return identification;
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#SPLIT} strategy.
*/
protected static class Split extends Dispatcher {
/**
* Creates a new split dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Split(int identification) {
super(identification);
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
LoadedTypeInitializer loadedTypeInitializer;
if (!auxiliaryTypes.isEmpty()) {
TypeDescription instrumentedType = dynamicType.getTypeDescription();
ClassInjector classInjector = injectorFactory.resolve();
Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
Map<TypeDescription, byte[]> dependentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) {
(auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class)
? dependentTypes
: independentTypes).remove(auxiliaryType);
}
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
if (!independentTypes.isEmpty()) {
for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
Map<TypeDescription, LoadedTypeInitializer> lazyInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>(loadedTypeInitializers);
loadedTypeInitializers.keySet().removeAll(independentTypes.keySet());
loadedTypeInitializer = lazyInitializers.size() > 1 // there exist auxiliary types that need lazy loading
? new InjectingInitializer(instrumentedType, dependentTypes, lazyInitializers, classInjector)
: lazyInitializers.get(instrumentedType);
} else {
loadedTypeInitializer = dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription());
}
if (loadedTypeInitializer.isAlive()) {
NexusAccessor.INSTANCE.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.Split{identification=" + identification + "}";
}
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#LAZY} strategy.
*/
protected static class Lazy extends Dispatcher {
/**
* Creates a new lazy dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Lazy(int identification) {
super(identification);
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
LoadedTypeInitializer loadedTypeInitializer = auxiliaryTypes.isEmpty()
? dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription())
: new InjectingInitializer(dynamicType.getTypeDescription(), auxiliaryTypes, dynamicType.getLoadedTypeInitializers(), injectorFactory.resolve());
if (loadedTypeInitializer.isAlive()) {
NexusAccessor.INSTANCE.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.Lazy{identification=" + identification + "}";
}
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#EAGER} strategy.
*/
protected static class Eager extends Dispatcher {
/**
* Creates a new eager dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Eager(int identification) {
super(identification);
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
if (!auxiliaryTypes.isEmpty()) {
for (Map.Entry<TypeDescription, Class<?>> entry : injectorFactory.resolve().inject(auxiliaryTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
LoadedTypeInitializer loadedTypeInitializer = loadedTypeInitializers.get(dynamicType.getTypeDescription());
if (loadedTypeInitializer.isAlive()) {
NexusAccessor.INSTANCE.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.Eager{identification=" + identification + "}";
}
}
/**
* A type initializer that injects all auxiliary types of the instrumented type.
*/
protected static class InjectingInitializer implements LoadedTypeInitializer {
/**
* The instrumented type.
*/
private final TypeDescription instrumentedType;
/**
* The auxiliary types mapped to their class file representation.
*/
private final Map<TypeDescription, byte[]> rawAuxiliaryTypes;
/**
* The instrumented types and auxiliary types mapped to their loaded type initializers.
* The instrumented types and auxiliary types mapped to their loaded type initializers.
*/
private final Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers;
/**
* The class injector to use.
*/
private final ClassInjector classInjector;
/**
* Creates a new injection initializer.
*
* @param instrumentedType The instrumented type.
* @param rawAuxiliaryTypes The auxiliary types mapped to their class file representation.
* @param loadedTypeInitializers The instrumented types and auxiliary types mapped to their loaded type initializers.
* @param classInjector The class injector to use.
*/
protected InjectingInitializer(TypeDescription instrumentedType,
Map<TypeDescription, byte[]> rawAuxiliaryTypes,
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers,
ClassInjector classInjector) {
this.instrumentedType = instrumentedType;
this.rawAuxiliaryTypes = rawAuxiliaryTypes;
this.loadedTypeInitializers = loadedTypeInitializers;
this.classInjector = classInjector;
}
@Override
public void onLoad(Class<?> type) {
for (Map.Entry<TypeDescription, Class<?>> auxiliary : classInjector.inject(rawAuxiliaryTypes).entrySet()) {
loadedTypeInitializers.get(auxiliary.getKey()).onLoad(auxiliary.getValue());
}
loadedTypeInitializers.get(instrumentedType).onLoad(type);
}
@Override
public boolean isAlive() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InjectingInitializer that = (InjectingInitializer) o;
return classInjector.equals(that.classInjector)
&& instrumentedType.equals(that.instrumentedType)
&& rawAuxiliaryTypes.equals(that.rawAuxiliaryTypes)
&& loadedTypeInitializers.equals(that.loadedTypeInitializers);
}
@Override
public int hashCode() {
int result = instrumentedType.hashCode();
result = 31 * result + rawAuxiliaryTypes.hashCode();
result = 31 * result + loadedTypeInitializers.hashCode();
result = 31 * result + classInjector.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.InjectingInitializer{" +
"instrumentedType=" + instrumentedType +
", rawAuxiliaryTypes=" + rawAuxiliaryTypes +
", loadedTypeInitializers=" + loadedTypeInitializers +
", classInjector=" + classInjector +
'}';
}
}
}
/**
* An accessor for making sure that the accessed {@link net.bytebuddy.agent.builder.Nexus} is the class that is loaded by the system class loader.
*/
protected enum NexusAccessor {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The dispatcher for registering type initializers in the {@link Nexus}.
*/
private final Dispatcher dispatcher;
/**
* The {@link ClassLoader#getSystemClassLoader()} method.
*/
private final MethodDescription.InDefinedShape getSystemClassLoader;
/**
* The {@link java.lang.ClassLoader#loadClass(String)} method.
*/
private final MethodDescription.InDefinedShape loadClass;
/**
* The {@link Integer#valueOf(int)} method.
*/
private final MethodDescription.InDefinedShape valueOf;
/**
* The {@link java.lang.Class#getDeclaredMethod(String, Class[])} method.
*/
private final MethodDescription getDeclaredMethod;
/**
* The {@link java.lang.reflect.Method#invoke(Object, Object...)} method.
*/
private final MethodDescription invokeMethod;
/**
* Creates the singleton accessor.
*/
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Explicit delegation of the exception")
NexusAccessor() {
Dispatcher dispatcher;
try {
TypeDescription nexusType = new TypeDescription.ForLoadedType(Nexus.class);
dispatcher = new Dispatcher.Available(ClassInjector.UsingReflection.ofSystemClassLoader()
.inject(Collections.singletonMap(nexusType, ClassFileLocator.ForClassLoader.read(Nexus.class).resolve()))
.get(nexusType)
.getDeclaredMethod("register", String.class, ClassLoader.class, int.class, Object.class));
} catch (Exception exception) {
try {
dispatcher = new Dispatcher.Available(ClassLoader.getSystemClassLoader()
.loadClass(Nexus.class.getName())
.getDeclaredMethod("register", String.class, ClassLoader.class, int.class, Object.class));
} catch (Exception ignored) {
dispatcher = new Dispatcher.Unavailable(exception);
}
}
this.dispatcher = dispatcher;
getSystemClassLoader = new TypeDescription.ForLoadedType(ClassLoader.class).getDeclaredMethods()
.filter(named("getSystemClassLoader").and(takesArguments(0))).getOnly();
loadClass = new TypeDescription.ForLoadedType(ClassLoader.class).getDeclaredMethods()
.filter(named("loadClass").and(takesArguments(String.class))).getOnly();
getDeclaredMethod = new TypeDescription.ForLoadedType(Class.class).getDeclaredMethods()
.filter(named("getDeclaredMethod").and(takesArguments(String.class, Class[].class))).getOnly();
invokeMethod = new TypeDescription.ForLoadedType(Method.class).getDeclaredMethods()
.filter(named("invoke").and(takesArguments(Object.class, Object[].class))).getOnly();
valueOf = new TypeDescription.ForLoadedType(Integer.class).getDeclaredMethods()
.filter(named("valueOf").and(takesArguments(int.class))).getOnly();
}
/**
* Registers a type initializer with the class loader's nexus.
*
* @param name The name of a type for which a loaded type initializer is registered.
* @param classLoader The class loader for which a loaded type initializer is registered.
* @param identification An identification for the initializer to run.
* @param typeInitializer The loaded type initializer to be registered.
*/
public void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer) {
dispatcher.register(name, classLoader, identification, typeInitializer);
}
/**
* Creates a byte code appender for injecting a self-initializing type initializer block into the generated class.
*
* @param identification The identification of the initialization.
* @return An appropriate byte code appender.
*/
public ByteCodeAppender identifiedBy(int identification) {
return new InitializationAppender(identification);
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor." + name();
}
/**
* A dispatcher for registering type initializers in the {@link Nexus}.
*/
protected interface Dispatcher {
/**
* Registers a type initializer with the class loader's nexus.
*
* @param name The name of a type for which a loaded type initializer is registered.
* @param classLoader The class loader for which a loaded type initializer is registered.
* @param identification An identification for the initializer to run.
* @param typeInitializer The loaded type initializer to be registered.
*/
void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer);
/**
* An enabled dispatcher for registering a type initializer in a {@link Nexus}.
*/
class Available implements Dispatcher {
/**
* Indicates that a static method is invoked by reflection.
*/
private static final Object STATIC_METHOD = null;
/**
* The method for registering a type initializer in the system class loader's {@link Nexus}.
*/
private final Method registration;
/**
* Creates a new dispatcher.
*
* @param registration The method for registering a type initializer in the system class loader's {@link Nexus}.
*/
protected Available(Method registration) {
this.registration = registration;
}
@Override
public void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer) {
try {
registration.invoke(STATIC_METHOD, name, classLoader, identification, typeInitializer);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot register type initializer for " + name, exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Cannot register type initializer for " + name, exception.getCause());
}
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& registration.equals(((Available) other).registration);
}
@Override
public int hashCode() {
return registration.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor.Dispatcher.Available{" +
"registration=" + registration +
'}';
}
}
/**
* A disabled dispatcher where a {@link Nexus} is not available.
*/
class Unavailable implements Dispatcher {
/**
* The exception that was raised during the dispatcher initialization.
*/
private final Exception exception;
/**
* Creates a new disabled dispatcher.
*
* @param exception The exception that was raised during the dispatcher initialization.
*/
protected Unavailable(Exception exception) {
this.exception = exception;
}
@Override
public void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer) {
throw new IllegalStateException("Could not locate registration method", exception);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& exception.equals(((Unavailable) other).exception);
}
@Override
public int hashCode() {
return exception.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor.Dispatcher.Unavailable{" +
"exception=" + exception +
'}';
}
}
}
/**
* A byte code appender for invoking a Nexus for initializing the instrumented type.
*/
protected static class InitializationAppender implements ByteCodeAppender {
/**
* The identification for the self-initialization to execute.
*/
private final int identification;
/**
* Creates a new initialization appender.
*
* @param identification The identification for the self-initialization to execute.
*/
protected InitializationAppender(int identification) {
this.identification = identification;
}
@Override
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
return new ByteCodeAppender.Simple(new StackManipulation.Compound(
MethodInvocation.invoke(NexusAccessor.INSTANCE.getSystemClassLoader),
new TextConstant(Nexus.class.getName()),
MethodInvocation.invoke(NexusAccessor.INSTANCE.loadClass),
new TextConstant("initialize"),
ArrayFactory.forType(new TypeDescription.Generic.OfNonGenericType.ForLoadedType(Class.class))
.withValues(Arrays.asList(
ClassConstant.of(TypeDescription.CLASS),
ClassConstant.of(new TypeDescription.ForLoadedType(int.class)))),
MethodInvocation.invoke(NexusAccessor.INSTANCE.getDeclaredMethod),
NullConstant.INSTANCE,
ArrayFactory.forType(TypeDescription.Generic.OBJECT)
.withValues(Arrays.asList(
ClassConstant.of(instrumentedMethod.getDeclaringType().asErasure()),
new StackManipulation.Compound(
IntegerConstant.forValue(identification),
MethodInvocation.invoke(INSTANCE.valueOf)))),
MethodInvocation.invoke(NexusAccessor.INSTANCE.invokeMethod),
Removal.SINGLE
)).apply(methodVisitor, implementationContext, instrumentedMethod);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
InitializationAppender that = (InitializationAppender) other;
return identification == that.identification;
}
@Override
public int hashCode() {
return identification;
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor.InitializationAppender{" +
"identification=" + identification +
'}';
}
}
}
}
/**
* An initialization strategy that loads auxiliary types before loading the instrumented type. This strategy skips all types
* that are a subtype of the instrumented type which would cause a premature loading of the instrumented type and abort
* the instrumentation process.
*/
enum Minimal implements InitializationStrategy, Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Dispatcher dispatcher() {
return this;
}
@Override
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder;
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) {
if (!auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class)) {
independentTypes.remove(auxiliaryType);
}
}
if (!independentTypes.isEmpty()) {
ClassInjector classInjector = injectorFactory.resolve();
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.Minimal." + name();
}
}
}
/**
* A description strategy is responsible for resolving a {@link TypeDescription} when transforming or retransforming/-defining a type.
*/
interface DescriptionStrategy {
/**
* Describes the given type.
*
* @param typeName The binary name of the type to describe.
* @param typeBeingRedefined The type that is being redefined, if a redefinition is applied or {@code null} if no redefined type is available.
* @param typePool The type pool to use for locating a type if required.
* @return An appropriate type description.
*/
TypeDescription apply(String typeName, Class<?> typeBeingRedefined, TypePool typePool);
/**
* Describes the given type.
*
* @param type The loaded type to be described.
* @param typeLocator The type locator to use.
* @param locationStrategy The location strategy to use.
* @return An appropriate type description.
*/
TypeDescription apply(Class<?> type, TypeLocator typeLocator, LocationStrategy locationStrategy);
/**
* Default implementations of a {@link DescriptionStrategy}.
*/
enum Default implements DescriptionStrategy {
/**
* A description type strategy represents a type as a {@link net.bytebuddy.description.type.TypeDescription.ForLoadedType} if a
* retransformation or redefinition is applied on a type. Using a loaded type typically results in better performance as no
* I/O is required for resolving type descriptions. However, any interaction with the type is carried out via the Java reflection
* API. Using the reflection API triggers eager loading of any type that is part of a method or field signature. If any of these
* types are missing from the class path, this eager loading will cause a {@link NoClassDefFoundError}. Some Java code declares
* optional dependencies to other classes which are only realized if the optional dependency is present. Such code relies on the
* Java reflection API not being used for types using optional dependencies.
*/
HYBRID {
@Override
public TypeDescription apply(String typeName, Class<?> typeBeingRedefined, TypePool typePool) {
return typeBeingRedefined == null
? typePool.describe(typeName).resolve()
: new TypeDescription.ForLoadedType(typeBeingRedefined);
}
@Override
public TypeDescription apply(Class<?> type, TypeLocator typeLocator, LocationStrategy locationStrategy) {
return new TypeDescription.ForLoadedType(type);
}
},
/**
* <p>
* A description strategy that always describes Java types using a {@link TypePool}. This requires that any type - even if it is already
* loaded and a {@link Class} instance is available - is processed as a non-loaded type description. Doing so can cause overhead as processing
* loaded types is supported very efficiently by a JVM.
* </p>
* <p>
* Avoiding the usage of loaded types can improve robustness as this approach does not rely on the Java reflection API which triggers eager
* validation of this loaded type which can fail an application if optional types are used by any types field or method signatures. Also, it
* is possible to guarantee debugging meta data to be available also for retransformed or redefined types if a {@link TypeStrategy} specifies
* the extraction of such meta data.
* </p>
*/
POOL_ONLY {
@Override
public TypeDescription apply(String typeName, Class<?> typeBeingRedefined, TypePool typePool) {
return typePool.describe(typeName).resolve();
}
@Override
public TypeDescription apply(Class<?> type, TypeLocator typeLocator, LocationStrategy locationStrategy) {
return apply(TypeDescription.ForLoadedType.getName(type), type, typeLocator.typePool(locationStrategy.classFileLocator(type.getClassLoader(), JavaModule.ofType(type)), type.getClassLoader()));
}
};
@Override
public String toString() {
return "AgentBuilder.DescriptionStrategy.Default." + name();
}
}
}
/**
* An installation strategy determines the reaction to a raised exception after the registration of a {@link ClassFileTransformer}.
*/
interface InstallationStrategy {
/**
* Handles an error that occured after registering a class file transformer during installation.
*
* @param instrumentation The instrumentation onto which the class file transformer was registered.
* @param classFileTransformer The class file transformer that was registered.
* @param throwable The error that occurred.
* @return The class file transformer to return when an error occurred.
*/
ClassFileTransformer onError(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, Throwable throwable);
/**
* Default implementations of installation strategies.
*/
enum Default implements InstallationStrategy {
/**
* An installation strategy that unregisters the transformer and propagates the exception. Using this strategy does not guarantee
* that the registered transformer was not applied to any class, nor does it attempt to revert previous transformations. It only
* guarantees that the class file transformer is unregistered and does no longer apply after this method returns.
*/
ESCALATING {
@Override
public ClassFileTransformer onError(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, Throwable throwable) {
instrumentation.removeTransformer(classFileTransformer);
throw new IllegalStateException("Could not install class file transformer", throwable);
}
},
/**
* An installation strategy that retains the class file transformer and suppresses the error.
*/
SUPPRESSING {
@Override
public ClassFileTransformer onError(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, Throwable throwable) {
return classFileTransformer;
}
};
@Override
public String toString() {
return "AgentBuilder.InstallationStrategy.Default." + name();
}
}
}
/**
* A strategy for creating a {@link ClassFileLocator} when instrumenting a type.
*/
interface LocationStrategy {
/**
* Creates a class file locator for a given class loader and module combination.
*
* @param classLoader The class loader that is loading an instrumented type. Might be {@code null} to represent the bootstrap class loader.
* @param module The type's module or {@code null} if Java modules are not supported on the current VM.
* @return The class file locator to use.
*/
ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module);
/**
* A location strategy that locates class files by querying an instrumented type's {@link ClassLoader}.
*/
enum ForClassLoader implements LocationStrategy {
/**
* A location strategy that keeps a strong reference to the class loader the created class file locator represents.
*/
STRONG {
@Override
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.ForClassLoader.of(classLoader);
}
},
/**
* A location strategy that keeps a weak reference to the class loader the created class file locator represents.
* As a consequence, any returned class file locator stops working once the represented class loader is garbage collected.
*/
WEAK {
@Override
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.ForClassLoader.WeaklyReferenced.of(classLoader);
}
};
@Override
public String toString() {
return "AgentBuilder.LocationStrategy.ForClassLoader." + name();
}
}
}
/**
* A redefinition strategy regulates how already loaded classes are modified by a built agent.
*/
enum RedefinitionStrategy {
/**
* Disables redefinition such that already loaded classes are not affected by the agent.
*/
DISABLED {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
return false;
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
throw new IllegalStateException("A disabled redefinition strategy cannot create a collector");
}
},
/**
* <p>
* Applies a <b>redefinition</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is <b>not</b>
* registered for applying retransformations.
* </p>
* <p>
* Using this strategy, a redefinition is applied as a single transformation request. This means that a single illegal
* redefinition of a class causes the entire redefinition attempt to fail.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
REDEFINITION {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
if (!instrumentation.isRedefineClassesSupported()) {
throw new IllegalArgumentException("Cannot redefine classes: " + instrumentation);
}
return false;
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
return new Collector.ForRedefinition.Cumulative(transformation);
}
},
/**
* <p>
* Applies a <b>redefinition</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is <b>not</b>
* registered for applying retransformations.
* </p>
* <p>
* Using this strategy, a redefinition is applied in single class chunks. This means that a single illegal
* redefinition of a class does not cause the failure of any other redefinition. Chunking the redefinition does
* however imply a performance penalty. If at least one redefinition has failed, applying this strategy still causes an
* exception to be thrown as a result of the application.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
REDEFINITION_CHUNKED {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
return REDEFINITION.isRetransforming(instrumentation);
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
return new Collector.ForRedefinition.Chunked(transformation);
}
},
/**
* <p>
* Applies a <b>retransformation</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is registered
* for applying retransformations.
* </p>
* <p>
* Using this strategy, a retransformation is applied as a single transformation request. This means that a single illegal
* retransformation of a class causes the entire retransformation attempt to fail.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
RETRANSFORMATION {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
if (!instrumentation.isRetransformClassesSupported()) {
throw new IllegalArgumentException("Cannot retransform classes: " + instrumentation);
}
return true;
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
return new Collector.ForRetransformation.Cumulative(transformation);
}
},
/**
* <p>
* Applies a <b>retransformation</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is registered
* for applying retransformations.
* </p>
* <p>
* Using this strategy, a retransformation is applied in single class chunks. This means that a single illegal
* retransformation of a class does not cause the failure of any other redefinition. Chunking the retransformation does
* however imply a performance penalty. If at least one retransformation has failed, applying this strategy still causes an
* exception to be thrown as a result of the application.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
RETRANSFORMATION_CHUNKED {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
return RETRANSFORMATION.isRetransforming(instrumentation);
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
return new Collector.ForRetransformation.Chunked(transformation);
}
};
/**
* Indicates if this strategy requires a class file transformer to be registered with a hint to apply the
* transformer for retransformation.
*
* @param instrumentation The instrumentation instance used.
* @return {@code true} if a class file transformer must be registered with a hint for retransformation.
*/
protected abstract boolean isRetransforming(Instrumentation instrumentation);
/**
* Indicates that this redefinition strategy applies a modification of already loaded classes.
*
* @return {@code true} if this redefinition strategy applies a modification of already loaded classes.
*/
protected boolean isEnabled() {
return this != DISABLED;
}
/**
* Creates a collector instance that is responsible for collecting loaded classes for potential retransformation.
*
* @param transformation The transformation that is registered for the agent.
* @return A new collector for collecting already loaded classes for transformation.
*/
protected abstract Collector makeCollector(Default.Transformation transformation);
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy." + name();
}
/**
* A collector is responsible for collecting classes that are to be considered for modification.
*/
protected interface Collector {
/**
* Considers a loaded class for modification.
*
* @param typeDescription The type description of the type that is to be considered.
* @param type The loaded representation of the type that is to be considered.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @return {@code true} if the class is considered to be redefined.
*/
boolean consider(TypeDescription typeDescription, Class<?> type, RawMatcher ignoredTypeMatcher);
/**
* Applies this collector.
*
* @param instrumentation The instrumentation instance to apply the transformation for.
* @param typeLocator The type locator to use.
* @param locationStrategy The location strategy to use.
* @param listener the listener to notify.
* @throws UnmodifiableClassException If a class is not modifiable.
* @throws ClassNotFoundException If a class could not be found.
*/
void apply(Instrumentation instrumentation,
TypeLocator typeLocator,
LocationStrategy locationStrategy,
Listener listener) throws UnmodifiableClassException, ClassNotFoundException;
/**
* A collector that applies a <b>redefinition</b> of already loaded classes.
*/
abstract class ForRedefinition implements Collector {
/**
* The transformation of the built agent.
*/
protected final Default.Transformation transformation;
/**
* A list of already collected redefinitions.
*/
protected final List<Entry> entries;
/**
* Creates a new collector for a redefinition.
*
* @param transformation The transformation of the built agent.
*/
protected ForRedefinition(Default.Transformation transformation) {
this.transformation = transformation;
entries = new ArrayList<Entry>();
}
@Override
public boolean consider(TypeDescription typeDescription, Class<?> type, RawMatcher ignoredTypeMatcher) {
return transformation.resolve(typeDescription,
type.getClassLoader(),
JavaModule.ofType(type),
type,
type.getProtectionDomain(),
ignoredTypeMatcher).getSort().isAlive() && entries.add(new Entry(type));
}
@Override
public void apply(Instrumentation instrumentation,
TypeLocator typeLocator,
LocationStrategy locationStrategy,
Listener listener) throws UnmodifiableClassException, ClassNotFoundException {
List<ClassDefinition> classDefinitions = new ArrayList<ClassDefinition>(entries.size());
for (Entry entry : entries) {
try {
classDefinitions.add(entry.resolve(locationStrategy));
} catch (Throwable throwable) {
JavaModule module = JavaModule.ofType(entry.getType());
try {
listener.onError(TypeDescription.ForLoadedType.getName(entry.getType()), entry.getType().getClassLoader(), module, throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(entry.getType()), entry.getType().getClassLoader(), module);
}
}
}
doApply(instrumentation, classDefinitions);
}
/**
* Applies a redefinition.
*
* @param instrumentation The instrumentation instance to use.
* @param classDefinitions The class definitions to apply.
* @throws UnmodifiableClassException If a class is not modifiable.
* @throws ClassNotFoundException If a class could not be found.
*/
protected abstract void doApply(Instrumentation instrumentation, List<ClassDefinition> classDefinitions) throws UnmodifiableClassException, ClassNotFoundException;
/**
* A collector that applies a redefinition and applies all redefinitions as a single transformation request.
*/
protected static class Cumulative extends ForRedefinition {
/**
* Creates a new cumulative redefinition collector.
*
* @param transformation The transformation of the built agent.
*/
protected Cumulative(Default.Transformation transformation) {
super(transformation);
}
@Override
protected void doApply(Instrumentation instrumentation, List<ClassDefinition> classDefinitions) throws UnmodifiableClassException, ClassNotFoundException {
if (!classDefinitions.isEmpty()) {
instrumentation.redefineClasses(classDefinitions.toArray(new ClassDefinition[classDefinitions.size()]));
}
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRedefinition.Cumulative{" +
"transformation=" + transformation +
", entries=" + entries +
'}';
}
}
/**
* A collector that applies a redefinition and applies all redefinitions as a separate transformation request per class.
*/
protected static class Chunked extends ForRedefinition {
/**
* Creates a new chunked redefinition collector.
*
* @param transformation The transformation of the built agent.
*/
protected Chunked(Default.Transformation transformation) {
super(transformation);
}
@Override
protected void doApply(Instrumentation instrumentation, List<ClassDefinition> classDefinitions) throws UnmodifiableClassException, ClassNotFoundException {
Map<Class<?>, Exception> exceptions = new HashMap<Class<?>, Exception>();
for (ClassDefinition classDefinition : classDefinitions) {
try {
instrumentation.redefineClasses(classDefinition);
} catch (Exception exception) {
exceptions.put(classDefinition.getDefinitionClass(), exception);
}
}
if (!exceptions.isEmpty()) {
throw new IllegalStateException("Could not retransform at least one class: " + exceptions);
}
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRedefinition.Chunked{" +
"transformation=" + transformation +
", entries=" + entries +
'}';
}
}
/**
* An entry describing a type redefinition.
*/
protected static class Entry {
/**
* The type to be redefined.
*/
private final Class<?> type;
/**
* Creates a new entry for a given type.
*
* @param type The type to be redefined.
*/
protected Entry(Class<?> type) {
this.type = type;
}
/**
* Returns the type that is being redefined.
*
* @return The type that is being redefined.
*/
public Class<?> getType() {
return type;
}
/**
* Resolves the entry to a class definition.
*
* @param locationStrategy A strategy for creating a class file locator.
* @return A class definition representing the redefined class.
* @throws IOException If an IO exception occurs.
*/
protected ClassDefinition resolve(LocationStrategy locationStrategy) throws IOException {
return new ClassDefinition(type, locationStrategy.classFileLocator(type.getClassLoader(), JavaModule.ofType(type)).locate(TypeDescription.ForLoadedType.getName(type)).resolve());
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Entry entry = (Entry) other;
return type.equals(entry.type);
}
@Override
public int hashCode() {
return type.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRedefinition.Entry{" +
"type=" + type +
'}';
}
}
}
/**
* A collector that applies a <b>retransformation</b> of already loaded classes.
*/
abstract class ForRetransformation implements Collector {
/**
* The transformation defined by the built agent.
*/
protected final Default.Transformation transformation;
/**
* The types that were collected for retransformation.
*/
protected final List<Class<?>> types;
/**
* Creates a new collector for a retransformation.
*
* @param transformation The transformation defined by the built agent.
*/
protected ForRetransformation(Default.Transformation transformation) {
this.transformation = transformation;
types = new ArrayList<Class<?>>();
}
@Override
public boolean consider(TypeDescription typeDescription, Class<?> type, RawMatcher ignoredTypeMatcher) {
return transformation.resolve(typeDescription,
type.getClassLoader(),
JavaModule.ofType(type),
type,
type.getProtectionDomain(),
ignoredTypeMatcher).getSort().isAlive() && types.add(type);
}
/**
* A collector that applies a retransformation and applies all redefinitions as a single transformation request.
*/
protected static class Cumulative extends ForRetransformation {
/**
* Creates a new cumulative retransformation collector.
*
* @param transformation The transformation of the built agent.
*/
protected Cumulative(Default.Transformation transformation) {
super(transformation);
}
@Override
public void apply(Instrumentation instrumentation,
TypeLocator typeLocator,
LocationStrategy locationStrategy,
Listener listener) throws UnmodifiableClassException {
if (!types.isEmpty()) {
instrumentation.retransformClasses(types.toArray(new Class<?>[types.size()]));
}
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRetransformation.Cumulative{" +
"transformation=" + transformation +
", types=" + types +
'}';
}
}
/**
* A collector that applies a retransformation and applies all redefinitions as a chunked transformation request.
*/
protected static class Chunked extends ForRetransformation {
/**
* Creates a new chunked retransformation collector.
*
* @param transformation The transformation of the built agent.
*/
protected Chunked(Default.Transformation transformation) {
super(transformation);
}
@Override
public void apply(Instrumentation instrumentation,
TypeLocator typeLocator,
LocationStrategy locationStrategy,
Listener listener) throws UnmodifiableClassException {
Map<Class<?>, Exception> exceptions = new HashMap<Class<?>, Exception>();
for (Class<?> type : types) {
try {
instrumentation.retransformClasses(type);
} catch (Exception exception) {
exceptions.put(type, exception);
}
}
if (!exceptions.isEmpty()) {
throw new IllegalStateException("Could not retransform at least one class: " + exceptions);
}
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRetransformation.Chunked{" +
"transformation=" + transformation +
", types=" + types +
'}';
}
}
}
}
}
/**
* Implements the instrumentation of the {@code LambdaMetafactory} if this feature is enabled.
*/
enum LambdaInstrumentationStrategy implements Callable<Class<?>> {
/**
* A strategy that enables instrumentation of the {@code LambdaMetafactory} if such a factory exists on the current VM.
* Classes representing lambda expressions that are created by Byte Buddy are fully compatible to those created by
* the JVM and can be serialized or deserialized to one another. The classes do however show a few differences:
* <ul>
* <li>Byte Buddy's classes are public with a public executing transformer. Doing so, it is not necessary to instantiate a
* non-capturing lambda expression by reflection. This is done because Byte Buddy is not necessarily capable
* of using reflection due to an active security manager.</li>
* <li>Byte Buddy's classes are not marked as synthetic as an agent builder does not instrument synthetic classes
* by default.</li>
* </ul>
*/
ENABLED {
@Override
protected void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
if (LambdaFactory.register(classFileTransformer, new LambdaInstanceFactory(byteBuddy), this)) {
Class<?> lambdaMetaFactory;
try {
lambdaMetaFactory = Class.forName("java.lang.invoke.LambdaMetafactory");
} catch (ClassNotFoundException ignored) {
return;
}
byteBuddy.with(Implementation.Context.Disabled.Factory.INSTANCE)
.redefine(lambdaMetaFactory)
.visit(new AsmVisitorWrapper.ForDeclaredMethods()
.method(named("metafactory"), MetaFactoryRedirection.INSTANCE)
.method(named("altMetafactory"), AlternativeMetaFactoryRedirection.INSTANCE))
.make()
.load(lambdaMetaFactory.getClassLoader(), ClassReloadingStrategy.of(instrumentation));
}
}
@Override
public Class<?> call() throws Exception {
TypeDescription lambdaFactory = new TypeDescription.ForLoadedType(LambdaFactory.class);
return ClassInjector.UsingReflection.ofSystemClassLoader()
.inject(Collections.singletonMap(lambdaFactory, ClassFileLocator.ForClassLoader.read(LambdaFactory.class).resolve()))
.get(lambdaFactory);
}
},
/**
* A strategy that does not instrument the {@code LambdaMetafactory}.
*/
DISABLED {
@Override
protected void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
/* do nothing */
}
@Override
public Class<?> call() throws Exception {
throw new IllegalStateException("Cannot inject LambdaFactory from disabled instrumentation strategy");
}
};
/**
* Indicates that an original implementation can be ignored when redefining a method.
*/
protected static final MethodVisitor IGNORE_ORIGINAL = null;
/**
* Releases the supplied class file transformer when it was built with {@link AgentBuilder#with(LambdaInstrumentationStrategy)} enabled.
* Subsequently, the class file transformer is no longer applied when a class that represents a lambda expression is created.
*
* @param classFileTransformer The class file transformer to release.
* @param instrumentation The instrumentation instance that is used to potentially rollback the instrumentation of the {@code LambdaMetafactory}.
*/
public static void release(ClassFileTransformer classFileTransformer, Instrumentation instrumentation) {
if (LambdaFactory.release(classFileTransformer)) {
try {
ClassReloadingStrategy.of(instrumentation).reset(Class.forName("java.lang.invoke.LambdaMetafactory"));
} catch (Exception exception) {
throw new IllegalStateException("Could not release lambda transformer", exception);
}
}
}
/**
* Returns an enabled lambda instrumentation strategy for {@code true}.
*
* @param enabled If lambda instrumentation should be enabled.
* @return {@code true} if the returned strategy should be enabled.
*/
public static LambdaInstrumentationStrategy of(boolean enabled) {
return enabled
? ENABLED
: DISABLED;
}
/**
* Applies a transformation to lambda instances if applicable.
*
* @param byteBuddy The Byte Buddy instance to use.
* @param instrumentation The instrumentation instance for applying a redefinition.
* @param classFileTransformer The class file transformer to apply.
*/
protected abstract void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer);
/**
* Indicates if this strategy enables instrumentation of the {@code LambdaMetafactory}.
*
* @return {@code true} if this strategy is enabled.
*/
public boolean isEnabled() {
return this == ENABLED;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy." + name();
}
/**
* A factory that creates instances that represent lambda expressions.
*/
protected static class LambdaInstanceFactory {
/**
* The name of a factory for a lambda expression.
*/
private static final String LAMBDA_FACTORY = "get$Lambda";
/**
* A prefix for a field that represents a property of a lambda expression.
*/
private static final String FIELD_PREFIX = "arg$";
/**
* The infix to use for naming classes that represent lambda expression. The additional prefix
* is necessary because the subsequent counter is not sufficient to keep names unique compared
* to the original factory.
*/
private static final String LAMBDA_TYPE_INFIX = "$$Lambda$ByteBuddy$";
/**
* A type-safe constant to express that a class is not already loaded when applying a class file transformer.
*/
private static final Class<?> NOT_PREVIOUSLY_DEFINED = null;
/**
* A counter for naming lambda expressions randomly.
*/
private static final AtomicInteger LAMBDA_NAME_COUNTER = new AtomicInteger();
/**
* The Byte Buddy instance to use for creating lambda objects.
*/
private final ByteBuddy byteBuddy;
/**
* Creates a new lambda instance factory.
*
* @param byteBuddy The Byte Buddy instance to use for creating lambda objects.
*/
protected LambdaInstanceFactory(ByteBuddy byteBuddy) {
this.byteBuddy = byteBuddy;
}
/**
* Applies this lambda meta factory.
*
* @param targetTypeLookup A lookup context representing the creating class of this lambda expression.
* @param lambdaMethodName The name of the lambda expression's represented method.
* @param factoryMethodType The type of the lambda expression's represented method.
* @param lambdaMethodType The type of the lambda expression's factory method.
* @param targetMethodHandle A handle representing the target of the lambda expression's method.
* @param specializedLambdaMethodType A specialization of the type of the lambda expression's represented method.
* @param serializable {@code true} if the lambda expression should be serializable.
* @param markerInterfaces A list of interfaces for the lambda expression to represent.
* @param additionalBridges A list of additional bridge methods to be implemented by the lambda expression.
* @param classFileTransformers A collection of class file transformers to apply when creating the class.
* @return A binary representation of the transformed class file.
*/
public byte[] make(Object targetTypeLookup,
String lambdaMethodName,
Object factoryMethodType,
Object lambdaMethodType,
Object targetMethodHandle,
Object specializedLambdaMethodType,
boolean serializable,
List<Class<?>> markerInterfaces,
List<?> additionalBridges,
Collection<? extends ClassFileTransformer> classFileTransformers) {
JavaConstant.MethodType factoryMethod = JavaConstant.MethodType.ofLoaded(factoryMethodType);
JavaConstant.MethodType lambdaMethod = JavaConstant.MethodType.ofLoaded(lambdaMethodType);
JavaConstant.MethodHandle targetMethod = JavaConstant.MethodHandle.ofLoaded(targetMethodHandle, targetTypeLookup);
JavaConstant.MethodType specializedLambdaMethod = JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType);
Class<?> targetType = JavaConstant.MethodHandle.lookupType(targetTypeLookup);
String lambdaClassName = targetType.getName() + LAMBDA_TYPE_INFIX + LAMBDA_NAME_COUNTER.incrementAndGet();
DynamicType.Builder<?> builder = byteBuddy
.subclass(factoryMethod.getReturnType(), ConstructorStrategy.Default.NO_CONSTRUCTORS)
.modifiers(TypeManifestation.FINAL, Visibility.PUBLIC)
.implement(markerInterfaces)
.name(lambdaClassName)
.defineConstructor(Visibility.PUBLIC)
.withParameters(factoryMethod.getParameterTypes())
.intercept(ConstructorImplementation.INSTANCE)
.method(named(lambdaMethodName)
.and(takesArguments(lambdaMethod.getParameterTypes()))
.and(returns(lambdaMethod.getReturnType())))
.intercept(new LambdaMethodImplementation(targetMethod, specializedLambdaMethod));
int index = 0;
for (TypeDescription capturedType : factoryMethod.getParameterTypes()) {
builder = builder.defineField(FIELD_PREFIX + ++index, capturedType, Visibility.PRIVATE, FieldManifestation.FINAL);
}
if (!factoryMethod.getParameterTypes().isEmpty()) {
builder = builder.defineMethod(LAMBDA_FACTORY, factoryMethod.getReturnType(), Visibility.PRIVATE, Ownership.STATIC)
.withParameters(factoryMethod.getParameterTypes())
.intercept(FactoryImplementation.INSTANCE);
}
if (serializable) {
if (!markerInterfaces.contains(Serializable.class)) {
builder = builder.implement(Serializable.class);
}
builder = builder.defineMethod("writeReplace", Object.class, Visibility.PRIVATE)
.intercept(new SerializationImplementation(new TypeDescription.ForLoadedType(targetType),
factoryMethod.getReturnType(),
lambdaMethodName,
lambdaMethod,
targetMethod,
JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType)));
} else if (factoryMethod.getReturnType().isAssignableTo(Serializable.class)) {
builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE)
.withParameters(ObjectInputStream.class)
.throwing(NotSerializableException.class)
.intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda"))
.defineMethod("writeObject", void.class, Visibility.PRIVATE)
.withParameters(ObjectOutputStream.class)
.throwing(NotSerializableException.class)
.intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda"));
}
for (Object additionalBridgeType : additionalBridges) {
JavaConstant.MethodType additionalBridge = JavaConstant.MethodType.ofLoaded(additionalBridgeType);
builder = builder.defineMethod(lambdaMethodName, additionalBridge.getReturnType(), MethodManifestation.BRIDGE, Visibility.PUBLIC)
.withParameters(additionalBridge.getParameterTypes())
.intercept(new BridgeMethodImplementation(lambdaMethodName, lambdaMethod));
}
byte[] classFile = builder.make().getBytes();
for (ClassFileTransformer classFileTransformer : classFileTransformers) {
try {
byte[] transformedClassFile = classFileTransformer.transform(targetType.getClassLoader(),
lambdaClassName.replace('.', '/'),
NOT_PREVIOUSLY_DEFINED,
targetType.getProtectionDomain(),
classFile);
classFile = transformedClassFile == null
? classFile
: transformedClassFile;
} catch (Throwable ignored) {
/* do nothing */
}
}
return classFile;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& byteBuddy.equals(((LambdaInstanceFactory) other).byteBuddy);
}
@Override
public int hashCode() {
return byteBuddy.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory{" +
"byteBuddy=" + byteBuddy +
'}';
}
/**
* Implements a lambda class's executing transformer.
*/
@SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "An enumeration does not serialize fields")
protected enum ConstructorImplementation implements Implementation {
/**
* The singleton instance.
*/
INSTANCE;
/**
* A reference to the {@link Object} class's default executing transformer.
*/
private final MethodDescription.InDefinedShape objectConstructor;
/**
* Creates a new executing transformer implementation.
*/
ConstructorImplementation() {
objectConstructor = TypeDescription.OBJECT.getDeclaredMethods().filter(isConstructor()).getOnly();
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.getInstrumentedType().getDeclaredFields());
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.ConstructorImplementation." + name();
}
/**
* An appender to implement the executing transformer.
*/
protected static class Appender implements ByteCodeAppender {
/**
* The fields that are declared by the instrumented type.
*/
private final List<FieldDescription.InDefinedShape> declaredFields;
/**
* Creates a new appender.
*
* @param declaredFields The fields that are declared by the instrumented type.
*/
protected Appender(List<FieldDescription.InDefinedShape> declaredFields) {
this.declaredFields = declaredFields;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
List<StackManipulation> fieldAssignments = new ArrayList<StackManipulation>(declaredFields.size() * 3);
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
fieldAssignments.add(MethodVariableAccess.REFERENCE.loadOffset(0));
fieldAssignments.add(MethodVariableAccess.of(parameterDescription.getType()).loadOffset(parameterDescription.getOffset()));
fieldAssignments.add(FieldAccess.forField(declaredFields.get(parameterDescription.getIndex())).putter());
}
return new Size(new StackManipulation.Compound(
MethodVariableAccess.REFERENCE.loadOffset(0),
MethodInvocation.invoke(INSTANCE.objectConstructor),
new StackManipulation.Compound(fieldAssignments),
MethodReturn.VOID
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& declaredFields.equals(((Appender) other).declaredFields);
}
@Override
public int hashCode() {
return declaredFields.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.ConstructorImplementation.Appender{" +
"declaredFields=" + declaredFields +
'}';
}
}
}
/**
* An implementation of a instance factory for a lambda expression's class.
*/
protected enum FactoryImplementation implements Implementation {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.getInstrumentedType());
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.FactoryImplementation." + name();
}
/**
* An appender for a lambda expression factory.
*/
protected static class Appender implements ByteCodeAppender {
/**
* The instrumented type.
*/
private final TypeDescription instrumentedType;
/**
* Creates a new appender.
*
* @param instrumentedType The instrumented type.
*/
protected Appender(TypeDescription instrumentedType) {
this.instrumentedType = instrumentedType;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
return new Size(new StackManipulation.Compound(
TypeCreation.of(instrumentedType),
Duplication.SINGLE,
MethodVariableAccess.allArgumentsOf(instrumentedMethod),
MethodInvocation.invoke(instrumentedType.getDeclaredMethods().filter(isConstructor()).getOnly()),
MethodReturn.REFERENCE
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& instrumentedType.equals(((Appender) other).instrumentedType);
}
@Override
public int hashCode() {
return instrumentedType.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.FactoryImplementation.Appender{" +
"instrumentedType=" + instrumentedType +
'}';
}
}
}
/**
* Implements a lambda expression's functional method.
*/
protected static class LambdaMethodImplementation implements Implementation {
/**
* The handle of the target method of the lambda expression.
*/
private final JavaConstant.MethodHandle targetMethod;
/**
* The specialized type of the lambda method.
*/
private final JavaConstant.MethodType specializedLambdaMethod;
/**
* Creates a implementation of a lambda expression's functional method.
*
* @param targetMethod The target method of the lambda expression.
* @param specializedLambdaMethod The specialized type of the lambda method.
*/
protected LambdaMethodImplementation(JavaConstant.MethodHandle targetMethod, JavaConstant.MethodType specializedLambdaMethod) {
this.targetMethod = targetMethod;
this.specializedLambdaMethod = specializedLambdaMethod;
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(targetMethod.getOwnerType()
.getDeclaredMethods()
.filter(named(targetMethod.getName())
.and(returns(targetMethod.getReturnType()))
.and(takesArguments(targetMethod.getParameterTypes())))
.getOnly(),
specializedLambdaMethod,
implementationTarget.getInstrumentedType().getDeclaredFields());
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
LambdaMethodImplementation that = (LambdaMethodImplementation) other;
return targetMethod.equals(that.targetMethod)
&& specializedLambdaMethod.equals(that.specializedLambdaMethod);
}
@Override
public int hashCode() {
int result = targetMethod.hashCode();
result = 31 * result + specializedLambdaMethod.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.LambdaMethodImplementation{" +
"targetMethod=" + targetMethod +
", specializedLambdaMethod=" + specializedLambdaMethod +
'}';
}
/**
* An appender for a lambda expression's functional method.
*/
protected static class Appender implements ByteCodeAppender {
/**
* The target method of the lambda expression.
*/
private final MethodDescription targetMethod;
/**
* The specialized type of the lambda method.
*/
private final JavaConstant.MethodType specializedLambdaMethod;
/**
* The instrumented type's declared fields.
*/
private final List<FieldDescription.InDefinedShape> declaredFields;
/**
* Creates an appender of a lambda expression's functional method.
*
* @param targetMethod The target method of the lambda expression.
* @param specializedLambdaMethod The specialized type of the lambda method.
* @param declaredFields The instrumented type's declared fields.
*/
protected Appender(MethodDescription targetMethod,
JavaConstant.MethodType specializedLambdaMethod,
List<FieldDescription.InDefinedShape> declaredFields) {
this.targetMethod = targetMethod;
this.specializedLambdaMethod = specializedLambdaMethod;
this.declaredFields = declaredFields;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
List<StackManipulation> fieldAccess = new ArrayList<StackManipulation>(declaredFields.size() * 2);
for (FieldDescription.InDefinedShape fieldDescription : declaredFields) {
fieldAccess.add(MethodVariableAccess.REFERENCE.loadOffset(0));
fieldAccess.add(FieldAccess.forField(fieldDescription).getter());
}
List<StackManipulation> parameterAccess = new ArrayList<StackManipulation>(instrumentedMethod.getParameters().size() * 2);
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
parameterAccess.add(MethodVariableAccess.of(parameterDescription.getType()).loadOffset(parameterDescription.getOffset()));
parameterAccess.add(Assigner.DEFAULT.assign(parameterDescription.getType(),
specializedLambdaMethod.getParameterTypes().get(parameterDescription.getIndex()).asGenericType(),
Assigner.Typing.DYNAMIC));
}
return new Size(new StackManipulation.Compound(
new StackManipulation.Compound(fieldAccess),
new StackManipulation.Compound(parameterAccess),
MethodInvocation.invoke(targetMethod),
MethodReturn.returning(targetMethod.getReturnType().asErasure())
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Appender appender = (Appender) other;
return targetMethod.equals(appender.targetMethod)
&& declaredFields.equals(appender.declaredFields)
&& specializedLambdaMethod.equals(appender.specializedLambdaMethod);
}
@Override
public int hashCode() {
int result = targetMethod.hashCode();
result = 31 * result + declaredFields.hashCode();
result = 31 * result + specializedLambdaMethod.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.LambdaMethodImplementation.Appender{" +
"targetMethod=" + targetMethod +
", specializedLambdaMethod=" + specializedLambdaMethod +
", declaredFields=" + declaredFields +
'}';
}
}
}
/**
* Implements the {@code writeReplace} method for serializable lambda expressions.
*/
protected static class SerializationImplementation implements Implementation {
/**
* The lambda expression's declaring type.
*/
private final TypeDescription targetType;
/**
* The lambda expression's functional type.
*/
private final TypeDescription lambdaType;
/**
* The lambda expression's functional method name.
*/
private final String lambdaMethodName;
/**
* The method type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType lambdaMethod;
/**
* A handle that references the lambda expressions invocation target.
*/
private final JavaConstant.MethodHandle targetMethod;
/**
* The specialized method type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType specializedMethod;
/**
* Creates a new implementation for a serializable's lambda expression's {@code writeReplace} method.
*
* @param targetType The lambda expression's declaring type.
* @param lambdaType The lambda expression's functional type.
* @param lambdaMethodName The lambda expression's functional method name.
* @param lambdaMethod The method type of the lambda expression's functional method.
* @param targetMethod A handle that references the lambda expressions invocation target.
* @param specializedMethod The specialized method type of the lambda expression's functional method.
*/
protected SerializationImplementation(TypeDescription targetType,
TypeDescription lambdaType,
String lambdaMethodName,
JavaConstant.MethodType lambdaMethod,
JavaConstant.MethodHandle targetMethod,
JavaConstant.MethodType specializedMethod) {
this.targetType = targetType;
this.lambdaType = lambdaType;
this.lambdaMethodName = lambdaMethodName;
this.lambdaMethod = lambdaMethod;
this.targetMethod = targetMethod;
this.specializedMethod = specializedMethod;
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
TypeDescription serializedLambda;
try {
serializedLambda = new TypeDescription.ForLoadedType(Class.forName("java.lang.invoke.SerializedLambda"));
} catch (ClassNotFoundException exception) {
throw new IllegalStateException("Cannot find class for lambda serialization", exception);
}
List<StackManipulation> lambdaArguments = new ArrayList<StackManipulation>(implementationTarget.getInstrumentedType().getDeclaredFields().size());
for (FieldDescription.InDefinedShape fieldDescription : implementationTarget.getInstrumentedType().getDeclaredFields()) {
lambdaArguments.add(new StackManipulation.Compound(MethodVariableAccess.REFERENCE.loadOffset(0),
FieldAccess.forField(fieldDescription).getter(),
Assigner.DEFAULT.assign(fieldDescription.getType(), TypeDescription.Generic.OBJECT, Assigner.Typing.STATIC)));
}
return new ByteCodeAppender.Simple(new StackManipulation.Compound(
TypeCreation.of(serializedLambda),
Duplication.SINGLE,
ClassConstant.of(targetType),
new TextConstant(lambdaType.getInternalName()),
new TextConstant(lambdaMethodName),
new TextConstant(lambdaMethod.getDescriptor()),
IntegerConstant.forValue(targetMethod.getHandleType().getIdentifier()),
new TextConstant(targetMethod.getOwnerType().getInternalName()),
new TextConstant(targetMethod.getName()),
new TextConstant(targetMethod.getDescriptor()),
new TextConstant(specializedMethod.getDescriptor()),
ArrayFactory.forType(TypeDescription.Generic.OBJECT).withValues(lambdaArguments),
MethodInvocation.invoke(serializedLambda.getDeclaredMethods().filter(isConstructor()).getOnly()),
MethodReturn.REFERENCE
));
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
SerializationImplementation that = (SerializationImplementation) other;
return targetType.equals(that.targetType)
&& lambdaType.equals(that.lambdaType)
&& lambdaMethodName.equals(that.lambdaMethodName)
&& lambdaMethod.equals(that.lambdaMethod)
&& targetMethod.equals(that.targetMethod)
&& specializedMethod.equals(that.specializedMethod);
}
@Override
public int hashCode() {
int result = targetType.hashCode();
result = 31 * result + lambdaType.hashCode();
result = 31 * result + lambdaMethodName.hashCode();
result = 31 * result + lambdaMethod.hashCode();
result = 31 * result + targetMethod.hashCode();
result = 31 * result + specializedMethod.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.SerializationImplementation{" +
"targetType=" + targetType +
", lambdaType=" + lambdaType +
", lambdaMethodName='" + lambdaMethodName + '\'' +
", lambdaMethod=" + lambdaMethod +
", targetMethod=" + targetMethod +
", specializedMethod=" + specializedMethod +
'}';
}
}
/**
* Implements an explicit bridge method for a lambda expression.
*/
protected static class BridgeMethodImplementation implements Implementation {
/**
* The name of the lambda expression's functional method.
*/
private final String lambdaMethodName;
/**
* The actual type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType lambdaMethod;
/**
* Creates a new bridge method implementation for a lambda expression.
*
* @param lambdaMethodName The name of the lambda expression's functional method.
* @param lambdaMethod The actual type of the lambda expression's functional method.
*/
protected BridgeMethodImplementation(String lambdaMethodName, JavaConstant.MethodType lambdaMethod) {
this.lambdaMethodName = lambdaMethodName;
this.lambdaMethod = lambdaMethod;
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.invokeSuper(new MethodDescription.SignatureToken(lambdaMethodName,
lambdaMethod.getReturnType(),
lambdaMethod.getParameterTypes())));
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
BridgeMethodImplementation that = (BridgeMethodImplementation) other;
return lambdaMethodName.equals(that.lambdaMethodName) && lambdaMethod.equals(that.lambdaMethod);
}
@Override
public int hashCode() {
int result = lambdaMethodName.hashCode();
result = 31 * result + lambdaMethod.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.BridgeMethodImplementation{" +
"lambdaMethodName='" + lambdaMethodName + '\'' +
", lambdaMethod=" + lambdaMethod +
'}';
}
/**
* An appender for implementing a bridge method for a lambda expression.
*/
protected static class Appender implements ByteCodeAppender {
/**
* The invocation of the bridge's target method.
*/
private final SpecialMethodInvocation bridgeTargetInvocation;
/**
* Creates a new appender for invoking a lambda expression's bridge method target.
*
* @param bridgeTargetInvocation The invocation of the bridge's target method.
*/
protected Appender(SpecialMethodInvocation bridgeTargetInvocation) {
this.bridgeTargetInvocation = bridgeTargetInvocation;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
return new Compound(new Simple(
MethodVariableAccess.allArgumentsOf(instrumentedMethod)
.asBridgeOf(bridgeTargetInvocation.getMethodDescription())
.prependThisReference(),
bridgeTargetInvocation,
bridgeTargetInvocation.getMethodDescription().getReturnType().asErasure().isAssignableTo(instrumentedMethod.getReturnType().asErasure())
? StackManipulation.Trivial.INSTANCE
: TypeCasting.to(instrumentedMethod.getReceiverType().asErasure()),
MethodReturn.returning(instrumentedMethod.getReturnType().asErasure())
)).apply(methodVisitor, implementationContext, instrumentedMethod);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& bridgeTargetInvocation.equals(((Appender) other).bridgeTargetInvocation);
}
@Override
public int hashCode() {
return bridgeTargetInvocation.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.BridgeMethodImplementation.Appender{" +
"bridgeTargetInvocation=" + bridgeTargetInvocation +
'}';
}
}
}
}
/**
* Implements the regular lambda meta factory. The implementation represents the following code:
* <blockquote><pre>
* public static CallSite metafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* MethodType samMethodType,
* MethodHandle implMethod,
* MethodType instantiatedMethodType) throws Exception {
* Unsafe unsafe = Unsafe.getUnsafe();
* {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(),
* (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make",
* Object.class,
* String.class,
* Object.class,
* Object.class,
* Object.class,
* Object.class,
* boolean.class,
* List.class,
* List.class).invoke(null,
* caller,
* invokedName,
* invokedType,
* samMethodType,
* implMethod,
* instantiatedMethodType,
* false,
* Collections.emptyList(),
* Collections.emptyList()),
* null);
* unsafe.ensureClassInitialized(lambdaClass);
* return invokedType.parameterCount() == 0
* ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance()))
* : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType));
* </pre></blockquote>
*/
protected enum MetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription.InDefinedShape methodDescription,
MethodVisitor methodVisitor,
ClassFileVersion classFileVersion,
int writerFlags,
int readerFlags) {
methodVisitor.visitCode();
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "sun/misc/Unsafe", "getUnsafe", "()Lsun/misc/Unsafe;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false);
methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false);
methodVisitor.visitLdcInsn("make");
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 4);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 5);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B");
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "ensureClassInitialized", "(Ljava/lang/Class;)V", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false);
Label conditionalDefault = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNE, conditionalDefault);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
Label conditionalAlternative = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, conditionalAlternative);
methodVisitor.visitLabel(conditionalDefault);
methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{"sun/misc/Unsafe", "java/lang/Class"}, 0, null);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitLdcInsn("get$Lambda");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
methodVisitor.visitLabel(conditionalAlternative);
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"});
methodVisitor.visitInsn(Opcodes.ARETURN);
methodVisitor.visitMaxs(8, 8);
methodVisitor.visitEnd();
return IGNORE_ORIGINAL;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.MetaFactoryRedirection." + name();
}
}
/**
* Implements the alternative lambda meta factory. The implementation represents the following code:
* <blockquote><pre>
* public static CallSite altMetafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* Object... args) throws Exception {
* int flags = (Integer) args[3];
* int argIndex = 4;
* {@code Class<?>[]} markerInterface;
* if ((flags {@code &} FLAG_MARKERS) != 0) {
* int markerCount = (Integer) args[argIndex++];
* markerInterface = new {@code Class<?>}[markerCount];
* System.arraycopy(args, argIndex, markerInterface, 0, markerCount);
* argIndex += markerCount;
* } else {
* markerInterface = new {@code Class<?>}[0];
* }
* MethodType[] additionalBridge;
* if ((flags {@code &} FLAG_BRIDGES) != 0) {
* int bridgeCount = (Integer) args[argIndex++];
* additionalBridge = new MethodType[bridgeCount];
* System.arraycopy(args, argIndex, additionalBridge, 0, bridgeCount);
* // argIndex += bridgeCount;
* } else {
* additionalBridge = new MethodType[0];
* }
* Unsafe unsafe = Unsafe.getUnsafe();
* {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(),
* (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make",
* Object.class,
* String.class,
* Object.class,
* Object.class,
* Object.class,
* Object.class,
* boolean.class,
* List.class,
* List.class).invoke(null,
* caller,
* invokedName,
* invokedType,
* args[0],
* args[1],
* args[2],
* (flags {@code &} FLAG_SERIALIZABLE) != 0,
* Arrays.asList(markerInterface),
* Arrays.asList(additionalBridge)),
* null);
* unsafe.ensureClassInitialized(lambdaClass);
* return invokedType.parameterCount() == 0
* ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance()))
* : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType));
* }
* </pre></blockquote>
*/
protected enum AlternativeMetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription.InDefinedShape methodDescription,
MethodVisitor methodVisitor,
ClassFileVersion classFileVersion,
int writerFlags,
int readerFlags) {
methodVisitor.visitCode();
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 4);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 5);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitInsn(Opcodes.IAND);
Label markerInterfaceLoop = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, markerInterfaceLoop);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitIincInsn(5, 1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitInsn(Opcodes.IADD);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 5);
Label markerInterfaceExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, markerInterfaceExit);
methodVisitor.visitLabel(markerInterfaceLoop);
methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{Opcodes.INTEGER, Opcodes.INTEGER}, 0, null);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitLabel(markerInterfaceExit);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/Class;"}, 0, null);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitInsn(Opcodes.IAND);
Label additionalBridgesLoop = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, additionalBridgesLoop);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitIincInsn(5, 1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 8);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 8);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 8);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false);
Label additionalBridgesExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, additionalBridgesExit);
methodVisitor.visitLabel(additionalBridgesLoop);
methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitLabel(additionalBridgesExit);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/invoke/MethodType;"}, 0, null);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "sun/misc/Unsafe", "getUnsafe", "()Lsun/misc/Unsafe;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false);
methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false);
methodVisitor.visitLdcInsn("make");
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.IAND);
Label callSiteConditional = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, callSiteConditional);
methodVisitor.visitInsn(Opcodes.ICONST_1);
Label callSiteAlternative = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteAlternative);
methodVisitor.visitLabel(callSiteConditional);
methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", "sun/misc/Unsafe"}, 7, new Object[]{"sun/misc/Unsafe", "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER});
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLabel(callSiteAlternative);
methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", "sun/misc/Unsafe"}, 8, new Object[]{"sun/misc/Unsafe", "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER});
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B");
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 9);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "ensureClassInitialized", "(Ljava/lang/Class;)V", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false);
Label callSiteJump = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNE, callSiteJump);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
Label callSiteExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteExit);
methodVisitor.visitLabel(callSiteJump);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"java/lang/Class"}, 0, null);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitLdcInsn("get$Lambda");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
methodVisitor.visitLabel(callSiteExit);
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"});
methodVisitor.visitInsn(Opcodes.ARETURN);
methodVisitor.visitMaxs(9, 10);
methodVisitor.visitEnd();
return IGNORE_ORIGINAL;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.AlternativeMetaFactoryRedirection." + name();
}
}
}
/**
* <p>
* The default implementation of an {@link net.bytebuddy.agent.builder.AgentBuilder}.
* </p>
* <p>
* By default, Byte Buddy ignores any types loaded by the bootstrap class loader and
* any synthetic type. Self-injection and rebasing is enabled. In order to avoid class format changes, set
* {@link AgentBuilder#disableBootstrapInjection()}). All types are parsed without their debugging information ({@link TypeLocator.Default#FAST}).
* </p>
*/
class Default implements AgentBuilder {
/**
* The name of the Byte Buddy {@code net.bytebuddy.agent.Installer} class.
*/
private static final String INSTALLER_TYPE = "net.bytebuddy.agent.Installer";
/**
* The name of the {@code net.bytebuddy.agent.Installer} field containing an installed {@link Instrumentation}.
*/
private static final String INSTRUMENTATION_FIELD = "instrumentation";
/**
* Indicator for access to a static member via reflection to make the code more readable.
*/
private static final Object STATIC_FIELD = null;
/**
* The value that is to be returned from a {@link java.lang.instrument.ClassFileTransformer} to indicate
* that no class file transformation is to be applied.
*/
private static final byte[] NO_TRANSFORMATION = null;
/**
* The {@link net.bytebuddy.ByteBuddy} instance to be used.
*/
private final ByteBuddy byteBuddy;
/**
* The type locator to use.
*/
private final TypeLocator typeLocator;
/**
* The definition handler to use.
*/
private final TypeStrategy typeStrategy;
/**
* The location strategy to use.
*/
private final LocationStrategy locationStrategy;
/**
* The listener to notify on transformations.
*/
private final Listener listener;
/**
* The native method strategy to use.
*/
private final NativeMethodStrategy nativeMethodStrategy;
/**
* The access control context to use for loading classes.
*/
private final AccessControlContext accessControlContext;
/**
* The initialization strategy to use for creating classes.
*/
private final InitializationStrategy initializationStrategy;
/**
* The redefinition strategy to apply.
*/
private final RedefinitionStrategy redefinitionStrategy;
/**
* The injection strategy for injecting classes into the bootstrap class loader.
*/
private final BootstrapInjectionStrategy bootstrapInjectionStrategy;
/**
* A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the instrumentation
* of classes that represent lambda expressions.
*/
private final LambdaInstrumentationStrategy lambdaInstrumentationStrategy;
/**
* The description strategy for resolving type descriptions for types.
*/
private final DescriptionStrategy descriptionStrategy;
/**
* The installation strategy to use.
*/
private final InstallationStrategy installationStrategy;
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoredTypeMatcher;
/**
* The transformation object for handling type transformations.
*/
private final Transformation transformation;
/**
* Creates a new default agent builder that uses a default {@link net.bytebuddy.ByteBuddy} instance for creating classes.
*
* @see Default#Default(ByteBuddy)
*/
public Default() {
this(new ByteBuddy());
}
/**
* Creates a new agent builder with default settings. By default, Byte Buddy ignores any types loaded by the bootstrap class loader, any
* type within a {@code net.bytebuddy} package and any synthetic type. Self-injection and rebasing is enabled. In order to avoid class format
* changes, set {@link AgentBuilder#disableBootstrapInjection()}). All types are parsed without their debugging information
* ({@link TypeLocator.Default#FAST}).
*
* @param byteBuddy The Byte Buddy instance to be used.
*/
public Default(ByteBuddy byteBuddy) {
this(byteBuddy,
TypeLocator.Default.FAST,
TypeStrategy.Default.REBASE,
LocationStrategy.ForClassLoader.STRONG,
Listener.NoOp.INSTANCE,
NativeMethodStrategy.Disabled.INSTANCE,
AccessController.getContext(),
InitializationStrategy.SelfInjection.SPLIT,
RedefinitionStrategy.DISABLED,
BootstrapInjectionStrategy.Disabled.INSTANCE,
LambdaInstrumentationStrategy.DISABLED,
DescriptionStrategy.Default.HYBRID,
InstallationStrategy.Default.ESCALATING,
new RawMatcher.Disjunction(new RawMatcher.ForElementMatchers(any(), isBootstrapClassLoader(), any()), new RawMatcher.ForElementMatchers(nameStartsWith("net.bytebuddy.").<TypeDescription>or(isSynthetic()), any(), any())),
Transformation.Ignored.INSTANCE);
}
/**
* Creates a new default agent builder.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param typeLocator The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to notify on transformations.
* @param nativeMethodStrategy The native method strategy to apply.
* @param accessControlContext The access control context to use for loading classes.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param redefinitionStrategy The redefinition strategy to apply.
* @param bootstrapInjectionStrategy The injection strategy for injecting classes into the bootstrap class loader.
* @param lambdaInstrumentationStrategy A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the
* instrumentation of classes that represent lambda expressions.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param installationStrategy The installation strategy to use.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @param transformation The transformation object for handling type transformations.
*/
protected Default(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
RedefinitionStrategy redefinitionStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
InstallationStrategy installationStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation) {
this.byteBuddy = byteBuddy;
this.typeLocator = typeLocator;
this.typeStrategy = typeStrategy;
this.locationStrategy = locationStrategy;
this.listener = listener;
this.nativeMethodStrategy = nativeMethodStrategy;
this.accessControlContext = accessControlContext;
this.initializationStrategy = initializationStrategy;
this.redefinitionStrategy = redefinitionStrategy;
this.bootstrapInjectionStrategy = bootstrapInjectionStrategy;
this.lambdaInstrumentationStrategy = lambdaInstrumentationStrategy;
this.descriptionStrategy = descriptionStrategy;
this.installationStrategy = installationStrategy;
this.ignoredTypeMatcher = ignoredTypeMatcher;
this.transformation = transformation;
}
@Override
public AgentBuilder with(ByteBuddy byteBuddy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(Listener listener) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
new Listener.Compound(this.listener, listener),
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(TypeStrategy typeStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(TypeLocator typeLocator) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(LocationStrategy locationStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder enableNativeMethodPrefix(String prefix) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
NativeMethodStrategy.ForPrefix.of(prefix),
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder disableNativeMethodPrefix() {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
NativeMethodStrategy.Disabled.INSTANCE,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(AccessControlContext accessControlContext) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(RedefinitionStrategy redefinitionStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(InitializationStrategy initializationStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(DescriptionStrategy descriptionStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(InstallationStrategy installationStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder enableBootstrapInjection(Instrumentation instrumentation, File folder) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
new BootstrapInjectionStrategy.Enabled(folder, instrumentation),
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder disableBootstrapInjection() {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
BootstrapInjectionStrategy.Disabled.INSTANCE,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder disableClassFormatChanges() {
return new Default(byteBuddy.with(Implementation.Context.Disabled.Factory.INSTANCE),
typeLocator,
TypeStrategy.Default.REDEFINE_DECLARED_ONLY,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
InitializationStrategy.NoOp.INSTANCE,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type) {
return JavaModule.isSupported()
? with(Listener.ModuleReadEdgeCompleting.of(instrumentation, false, type))
: this;
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module) {
return assureReadEdgeTo(instrumentation, Arrays.asList(module));
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return with(new Listener.ModuleReadEdgeCompleting(instrumentation, false, new HashSet<JavaModule>(modules)));
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type) {
return JavaModule.isSupported()
? with(Listener.ModuleReadEdgeCompleting.of(instrumentation, true, type))
: this;
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module) {
return assureReadEdgeFromAndTo(instrumentation, Arrays.asList(module));
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return with(new Listener.ModuleReadEdgeCompleting(instrumentation, true, new HashSet<JavaModule>(modules)));
}
@Override
public Identified.Narrowable type(RawMatcher matcher) {
return new Transforming(matcher, Transformer.NoOp.INSTANCE, false);
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher) {
return type(typeMatcher, any());
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return type(typeMatcher, classLoaderMatcher, any());
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return type(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, not(supportsModules()).or(moduleMatcher)));
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher) {
return ignore(typeMatcher, any());
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return ignore(typeMatcher, classLoaderMatcher, any());
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return ignore(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, not(supportsModules()).or(moduleMatcher)));
}
@Override
public Ignored ignore(RawMatcher rawMatcher) {
return new Ignoring(rawMatcher);
}
@Override
public ClassFileTransformer makeRaw() {
return ExecutingTransformer.FACTORY.make(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
bootstrapInjectionStrategy,
descriptionStrategy,
ignoredTypeMatcher, transformation);
}
@Override
public ClassFileTransformer installOn(Instrumentation instrumentation) {
ClassFileTransformer classFileTransformer = makeRaw();
instrumentation.addTransformer(classFileTransformer, redefinitionStrategy.isRetransforming(instrumentation));
try {
if (nativeMethodStrategy.isEnabled(instrumentation)) {
instrumentation.setNativeMethodPrefix(classFileTransformer, nativeMethodStrategy.getPrefix());
}
lambdaInstrumentationStrategy.apply(byteBuddy, instrumentation, classFileTransformer);
if (redefinitionStrategy.isEnabled()) {
RedefinitionStrategy.Collector collector = redefinitionStrategy.makeCollector(transformation);
for (Class<?> type : instrumentation.getAllLoadedClasses()) {
TypeDescription typeDescription = descriptionStrategy.apply(type, typeLocator, locationStrategy);
JavaModule module = JavaModule.ofType(type);
try {
if (!instrumentation.isModifiableClass(type) || !collector.consider(typeDescription, type, ignoredTypeMatcher)) {
try {
try {
listener.onIgnored(typeDescription, type.getClassLoader(), module);
} finally {
listener.onComplete(typeDescription.getName(), type.getClassLoader(), module);
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
}
} catch (Throwable throwable) {
try {
try {
listener.onError(typeDescription.getName(), type.getClassLoader(), module, throwable);
} finally {
listener.onComplete(typeDescription.getName(), type.getClassLoader(), module);
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
}
}
collector.apply(instrumentation, typeLocator, locationStrategy, listener);
}
return classFileTransformer;
} catch (Throwable throwable) {
return installationStrategy.onError(instrumentation, classFileTransformer, throwable);
}
}
@Override
public ClassFileTransformer installOnByteBuddyAgent() {
try {
Instrumentation instrumentation = (Instrumentation) ClassLoader.getSystemClassLoader()
.loadClass(INSTALLER_TYPE)
.getDeclaredField(INSTRUMENTATION_FIELD)
.get(STATIC_FIELD);
if (instrumentation == null) {
throw new IllegalStateException("The Byte Buddy agent is not installed");
}
return installOn(instrumentation);
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("The Byte Buddy agent is not installed or not accessible", exception);
}
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Default aDefault = (Default) other;
return typeLocator.equals(aDefault.typeLocator)
&& byteBuddy.equals(aDefault.byteBuddy)
&& listener.equals(aDefault.listener)
&& nativeMethodStrategy.equals(aDefault.nativeMethodStrategy)
&& typeStrategy.equals(aDefault.typeStrategy)
&& locationStrategy.equals(aDefault.locationStrategy)
&& accessControlContext.equals(aDefault.accessControlContext)
&& initializationStrategy == aDefault.initializationStrategy
&& redefinitionStrategy == aDefault.redefinitionStrategy
&& bootstrapInjectionStrategy.equals(aDefault.bootstrapInjectionStrategy)
&& lambdaInstrumentationStrategy.equals(aDefault.lambdaInstrumentationStrategy)
&& descriptionStrategy.equals(aDefault.descriptionStrategy)
&& installationStrategy.equals(aDefault.installationStrategy)
&& ignoredTypeMatcher.equals(aDefault.ignoredTypeMatcher)
&& transformation.equals(aDefault.transformation);
}
@Override
public int hashCode() {
int result = byteBuddy.hashCode();
result = 31 * result + typeLocator.hashCode();
result = 31 * result + listener.hashCode();
result = 31 * result + typeStrategy.hashCode();
result = 31 * result + locationStrategy.hashCode();
result = 31 * result + nativeMethodStrategy.hashCode();
result = 31 * result + accessControlContext.hashCode();
result = 31 * result + initializationStrategy.hashCode();
result = 31 * result + redefinitionStrategy.hashCode();
result = 31 * result + bootstrapInjectionStrategy.hashCode();
result = 31 * result + lambdaInstrumentationStrategy.hashCode();
result = 31 * result + descriptionStrategy.hashCode();
result = 31 * result + installationStrategy.hashCode();
result = 31 * result + ignoredTypeMatcher.hashCode();
result = 31 * result + transformation.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default{" +
"byteBuddy=" + byteBuddy +
", typeLocator=" + typeLocator +
", typeStrategy=" + typeStrategy +
", locationStrategy=" + locationStrategy +
", listener=" + listener +
", nativeMethodStrategy=" + nativeMethodStrategy +
", accessControlContext=" + accessControlContext +
", initializationStrategy=" + initializationStrategy +
", redefinitionStrategy=" + redefinitionStrategy +
", bootstrapInjectionStrategy=" + bootstrapInjectionStrategy +
", lambdaInstrumentationStrategy=" + lambdaInstrumentationStrategy +
", descriptionStrategy=" + descriptionStrategy +
", installationStrategy=" + installationStrategy +
", ignoredTypeMatcher=" + ignoredTypeMatcher +
", transformation=" + transformation +
'}';
}
/**
* An injection strategy for injecting classes into the bootstrap class loader.
*/
protected interface BootstrapInjectionStrategy {
/**
* Creates an injector for the bootstrap class loader.
*
* @param protectionDomain The protection domain to be used.
* @return A class injector for the bootstrap class loader.
*/
ClassInjector make(ProtectionDomain protectionDomain);
/**
* A disabled bootstrap injection strategy.
*/
enum Disabled implements BootstrapInjectionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ClassInjector make(ProtectionDomain protectionDomain) {
throw new IllegalStateException("Injecting classes into the bootstrap class loader was not enabled");
}
@Override
public String toString() {
return "AgentBuilder.Default.BootstrapInjectionStrategy.Disabled." + name();
}
}
/**
* An enabled bootstrap injection strategy.
*/
class Enabled implements BootstrapInjectionStrategy {
/**
* The folder in which jar files are to be saved.
*/
private final File folder;
/**
* The instrumentation to use for appending jar files.
*/
private final Instrumentation instrumentation;
/**
* Creates a new enabled bootstrap class loader injection strategy.
*
* @param folder The folder in which jar files are to be saved.
* @param instrumentation The instrumentation to use for appending jar files.
*/
public Enabled(File folder, Instrumentation instrumentation) {
this.folder = folder;
this.instrumentation = instrumentation;
}
@Override
public ClassInjector make(ProtectionDomain protectionDomain) {
return ClassInjector.UsingInstrumentation.of(folder, ClassInjector.UsingInstrumentation.Target.BOOTSTRAP, instrumentation);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Enabled enabled = (Enabled) other;
return folder.equals(enabled.folder) && instrumentation.equals(enabled.instrumentation);
}
@Override
public int hashCode() {
int result = folder.hashCode();
result = 31 * result + instrumentation.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.BootstrapInjectionStrategy.Enabled{" +
"folder=" + folder +
", instrumentation=" + instrumentation +
'}';
}
}
}
/**
* A strategy for determining if a native method name prefix should be used when rebasing methods.
*/
protected interface NativeMethodStrategy {
/**
* Determines if this strategy enables name prefixing for native methods.
*
* @param instrumentation The instrumentation used.
* @return {@code true} if this strategy indicates that a native method prefix should be used.
*/
boolean isEnabled(Instrumentation instrumentation);
/**
* Resolves the method name transformer for this strategy.
*
* @return A method name transformer for this strategy.
*/
MethodNameTransformer resolve();
/**
* Returns the method prefix if the strategy is enabled. This method must only be called if this strategy enables prefixing.
*
* @return The method prefix.
*/
String getPrefix();
/**
* A native method strategy that suffixes method names with a random suffix and disables native method rebasement.
*/
enum Disabled implements NativeMethodStrategy {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public MethodNameTransformer resolve() {
return MethodNameTransformer.Suffixing.withRandomSuffix();
}
@Override
public boolean isEnabled(Instrumentation instrumentation) {
return false;
}
@Override
public String getPrefix() {
throw new IllegalStateException("A disabled native method strategy does not define a method name prefix");
}
@Override
public String toString() {
return "AgentBuilder.Default.NativeMethodStrategy.Disabled." + name();
}
}
/**
* A native method strategy that prefixes method names with a fixed value for supporting rebasing of native methods.
*/
class ForPrefix implements NativeMethodStrategy {
/**
* The method name prefix.
*/
private final String prefix;
/**
* Creates a new name prefixing native method strategy.
*
* @param prefix The method name prefix.
*/
protected ForPrefix(String prefix) {
this.prefix = prefix;
}
/**
* Creates a new native method strategy for prefixing method names.
*
* @param prefix The method name prefix.
* @return An appropriate native method strategy.
*/
protected static NativeMethodStrategy of(String prefix) {
if (prefix.length() == 0) {
throw new IllegalArgumentException("A method name prefix must not be the empty string");
}
return new ForPrefix(prefix);
}
@Override
public MethodNameTransformer resolve() {
return new MethodNameTransformer.Prefixing(prefix);
}
@Override
public boolean isEnabled(Instrumentation instrumentation) {
if (!instrumentation.isNativeMethodPrefixSupported()) {
throw new IllegalArgumentException("A prefix for native methods is not supported: " + instrumentation);
}
return true;
}
@Override
public String getPrefix() {
return prefix;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass()) && prefix.equals(((ForPrefix) other).prefix);
}
@Override
public int hashCode() {
return prefix.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Default.NativeMethodStrategy.ForPrefix{" +
"prefix='" + prefix + '\'' +
'}';
}
}
}
/**
* A transformation serves as a handler for modifying a class.
*/
protected interface Transformation {
/**
* Resolves an attempted transformation to a specific transformation.
*
* @param typeDescription A description of the type that is to be transformed.
* @param classLoader The class loader of the type being transformed.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param classBeingRedefined In case of a type redefinition, the loaded type being transformed or {@code null} if that is not the case.
* @param protectionDomain The protection domain of the type being transformed.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @return A resolution for the given type.
*/
Resolution resolve(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
RawMatcher ignoredTypeMatcher);
/**
* A resolution to a transformation.
*/
interface Resolution {
/**
* Returns the sort of this resolution.
*
* @return The sort of this resolution.
*/
Sort getSort();
/**
* Resolves this resolution as a decorator of the supplied resolution.
*
* @param resolution The resolution for which this resolution should serve as a decorator.
* @return A resolution where this resolution is applied as a decorator if this resolution is alive.
*/
Resolution asDecoratorOf(Resolution resolution);
/**
* Resolves this resolution as a decorator of the supplied resolution.
*
* @param resolution The resolution for which this resolution should serve as a decorator.
* @return A resolution where this resolution is applied as a decorator if this resolution is alive.
*/
Resolution prepend(Decoratable resolution);
/**
* Transforms a type or returns {@code null} if a type is not to be transformed.
*
* @param initializationStrategy The initialization strategy to use.
* @param classFileLocator The class file locator to use.
* @param typeStrategy The definition handler to use.
* @param byteBuddy The Byte Buddy instance to use.
* @param methodNameTransformer The method name transformer to be used.
* @param bootstrapInjectionStrategy The bootstrap injection strategy to be used.
* @param accessControlContext The access control context to be used.
* @param listener The listener to be invoked to inform about an applied or non-applied transformation.
* @return The class file of the transformed class or {@code null} if no transformation is attempted.
*/
byte[] apply(InitializationStrategy initializationStrategy,
ClassFileLocator classFileLocator,
TypeStrategy typeStrategy,
ByteBuddy byteBuddy,
NativeMethodStrategy methodNameTransformer,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
AccessControlContext accessControlContext,
Listener listener);
/**
* Describes a specific sort of a {@link Resolution}.
*/
enum Sort {
/**
* A terminal resolution. After discovering such a resolution, no further transformers are considered.
*/
TERMINAL(true),
/**
* A resolution that can serve as a decorator for another resolution. After discovering such a resolution
* further transformations are considered where the represented resolution is prepended if applicable.
*/
DECORATOR(true),
/**
* A non-resolved resolution.
*/
UNDEFINED(false);
/**
* Indicates if this sort represents an active resolution.
*/
private final boolean alive;
/**
* Creates a new resolution sort.
*
* @param alive Indicates if this sort represents an active resolution.
*/
Sort(boolean alive) {
this.alive = alive;
}
/**
* Returns {@code true} if this resolution is alive.
*
* @return {@code true} if this resolution is alive.
*/
protected boolean isAlive() {
return alive;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Resolution.Sort." + name();
}
}
/**
* A resolution that can be decorated by a transformer.
*/
interface Decoratable extends Resolution {
/**
* Appends the supplied transformer to this resolution.
*
* @param transformer The transformer to append to the transformer that is represented bz this instance.
* @return A new resolution with the supplied transformer appended to this transformer.
*/
Resolution append(Transformer transformer);
}
/**
* A canonical implementation of a non-resolved resolution.
*/
class Unresolved implements Resolution {
/**
* The type that is not transformed.
*/
private final TypeDescription typeDescription;
/**
* The unresolved type's class loader.
*/
private final ClassLoader classLoader;
/**
* The non-transformed type's module or {@code null} if the current VM does not support modules.
*/
private final JavaModule module;
/**
* Creates a new unresolved resolution.
*
* @param typeDescription The type that is not transformed.
* @param classLoader The unresolved type's class loader.
* @param module The non-transformed type's module or {@code null} if the current VM does not support modules.
*/
protected Unresolved(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
this.typeDescription = typeDescription;
this.classLoader = classLoader;
this.module = module;
}
@Override
public Sort getSort() {
return Sort.UNDEFINED;
}
@Override
public Resolution asDecoratorOf(Resolution resolution) {
return resolution;
}
@Override
public Resolution prepend(Decoratable resolution) {
return resolution;
}
@Override
public byte[] apply(InitializationStrategy initializationStrategy,
ClassFileLocator classFileLocator,
TypeStrategy typeStrategy,
ByteBuddy byteBuddy,
NativeMethodStrategy methodNameTransformer,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
AccessControlContext accessControlContext,
Listener listener) {
listener.onIgnored(typeDescription, classLoader, module);
return NO_TRANSFORMATION;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Unresolved that = (Unresolved) object;
return typeDescription.equals(that.typeDescription)
&& (classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null)
&& (module != null ? module.equals(that.module) : that.module == null);
}
@Override
public int hashCode() {
int result = typeDescription.hashCode();
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + (module != null ? module.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Resolution.Unresolved{" +
"typeDescription=" + typeDescription +
", classLoader=" + classLoader +
", module=" + module +
'}';
}
}
}
/**
* A transformation that does not attempt to transform any type.
*/
enum Ignored implements Transformation {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Resolution resolve(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
RawMatcher ignoredTypeMatcher) {
return new Resolution.Unresolved(typeDescription, classLoader, module);
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Ignored." + name();
}
}
/**
* A simple, active transformation.
*/
class Simple implements Transformation {
/**
* The raw matcher that is represented by this transformation.
*/
private final RawMatcher rawMatcher;
/**
* The transformer that is represented by this transformation.
*/
private final Transformer transformer;
/**
* {@code true} if this transformer serves as a decorator.
*/
private final boolean decorator;
/**
* Creates a new transformation.
*
* @param rawMatcher The raw matcher that is represented by this transformation.
* @param transformer The transformer that is represented by this transformation.
* @param decorator {@code true} if this transformer serves as a decorator.
*/
protected Simple(RawMatcher rawMatcher, Transformer transformer, boolean decorator) {
this.rawMatcher = rawMatcher;
this.transformer = transformer;
this.decorator = decorator;
}
@Override
public Transformation.Resolution resolve(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
RawMatcher ignoredTypeMatcher) {
return !ignoredTypeMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
&& rawMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
? new Resolution(typeDescription, classLoader, module, protectionDomain, transformer, decorator)
: new Transformation.Resolution.Unresolved(typeDescription, classLoader, module);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& decorator == ((Simple) other).decorator
&& rawMatcher.equals(((Simple) other).rawMatcher)
&& transformer.equals(((Simple) other).transformer);
}
@Override
public int hashCode() {
int result = rawMatcher.hashCode();
result = 31 * result + (decorator ? 1 : 0);
result = 31 * result + transformer.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Simple{" +
"rawMatcher=" + rawMatcher +
", transformer=" + transformer +
", decorator=" + decorator +
'}';
}
/**
* A resolution that performs a type transformation.
*/
protected static class Resolution implements Transformation.Resolution.Decoratable {
/**
* A description of the transformed type.
*/
private final TypeDescription typeDescription;
/**
* The class loader of the transformed type.
*/
private final ClassLoader classLoader;
/**
* The transformed type's module or {@code null} if the current VM does not support modules.
*/
private final JavaModule module;
/**
* The protection domain of the transformed type.
*/
private final ProtectionDomain protectionDomain;
/**
* The transformer to be applied.
*/
private final Transformer transformer;
/**
* {@code true} if this transformer serves as a decorator.
*/
private final boolean decorator;
/**
* Creates a new active transformation.
*
* @param typeDescription A description of the transformed type.
* @param classLoader The class loader of the transformed type.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param protectionDomain The protection domain of the transformed type.
* @param transformer The transformer to be applied.
* @param decorator {@code true} if this transformer serves as a decorator.
*/
protected Resolution(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain,
Transformer transformer,
boolean decorator) {
this.typeDescription = typeDescription;
this.classLoader = classLoader;
this.module = module;
this.protectionDomain = protectionDomain;
this.transformer = transformer;
this.decorator = decorator;
}
@Override
public Sort getSort() {
return decorator
? Sort.DECORATOR
: Sort.TERMINAL;
}
@Override
public Transformation.Resolution asDecoratorOf(Transformation.Resolution resolution) {
return resolution.prepend(this);
}
@Override
public Transformation.Resolution prepend(Decoratable resolution) {
return resolution.append(transformer);
}
@Override
public Transformation.Resolution append(Transformer transformer) {
return new Resolution(typeDescription,
classLoader,
module,
protectionDomain,
new Transformer.Compound(this.transformer, transformer),
decorator);
}
@Override
public byte[] apply(InitializationStrategy initializationStrategy,
ClassFileLocator classFileLocator,
TypeStrategy typeStrategy,
ByteBuddy byteBuddy,
NativeMethodStrategy methodNameTransformer,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
AccessControlContext accessControlContext,
Listener listener) {
InitializationStrategy.Dispatcher dispatcher = initializationStrategy.dispatcher();
DynamicType.Unloaded<?> dynamicType = dispatcher.apply(transformer.transform(typeStrategy.builder(typeDescription,
byteBuddy,
classFileLocator,
methodNameTransformer.resolve()), typeDescription, classLoader)).make();
dispatcher.register(dynamicType, classLoader, new BootstrapClassLoaderCapableInjectorFactory(bootstrapInjectionStrategy,
classLoader,
protectionDomain,
accessControlContext));
listener.onTransformation(typeDescription, classLoader, module, dynamicType);
return dynamicType.getBytes();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Resolution that = (Resolution) other;
return typeDescription.equals(that.typeDescription)
&& decorator == that.decorator
&& !(classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null)
&& !(module != null ? !module.equals(that.module) : that.module != null)
&& !(protectionDomain != null ? !protectionDomain.equals(that.protectionDomain) : that.protectionDomain != null)
&& transformer.equals(that.transformer);
}
@Override
public int hashCode() {
int result = typeDescription.hashCode();
result = 31 * result + (decorator ? 1 : 0);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + (module != null ? module.hashCode() : 0);
result = 31 * result + (protectionDomain != null ? protectionDomain.hashCode() : 0);
result = 31 * result + transformer.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Simple.Resolution{" +
"typeDescription=" + typeDescription +
", classLoader=" + classLoader +
", module=" + module +
", protectionDomain=" + protectionDomain +
", transformer=" + transformer +
", decorator=" + decorator +
'}';
}
/**
* An injector factory that resolves to a bootstrap class loader injection if this is necessary and enabled.
*/
protected static class BootstrapClassLoaderCapableInjectorFactory implements InitializationStrategy.Dispatcher.InjectorFactory {
/**
* The bootstrap injection strategy being used.
*/
private final BootstrapInjectionStrategy bootstrapInjectionStrategy;
/**
* The class loader for which to create an injection factory.
*/
private final ClassLoader classLoader;
/**
* The protection domain of the created classes.
*/
private final ProtectionDomain protectionDomain;
/**
* The access control context to be used.
*/
private final AccessControlContext accessControlContext;
/**
* Creates a new bootstrap class loader capable injector factory.
*
* @param bootstrapInjectionStrategy The bootstrap injection strategy being used.
* @param classLoader The class loader for which to create an injection factory.
* @param protectionDomain The protection domain of the created classes.
* @param accessControlContext The access control context to be used.
*/
protected BootstrapClassLoaderCapableInjectorFactory(BootstrapInjectionStrategy bootstrapInjectionStrategy,
ClassLoader classLoader,
ProtectionDomain protectionDomain,
AccessControlContext accessControlContext) {
this.bootstrapInjectionStrategy = bootstrapInjectionStrategy;
this.classLoader = classLoader;
this.protectionDomain = protectionDomain;
this.accessControlContext = accessControlContext;
}
@Override
public ClassInjector resolve() {
return classLoader == null
? bootstrapInjectionStrategy.make(protectionDomain)
: new ClassInjector.UsingReflection(classLoader, protectionDomain, accessControlContext);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
BootstrapClassLoaderCapableInjectorFactory that = (BootstrapClassLoaderCapableInjectorFactory) other;
return bootstrapInjectionStrategy.equals(that.bootstrapInjectionStrategy)
&& !(classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null)
&& !(protectionDomain != null ? !protectionDomain.equals(that.protectionDomain) : that.protectionDomain != null)
&& accessControlContext.equals(that.accessControlContext);
}
@Override
public int hashCode() {
int result = bootstrapInjectionStrategy.hashCode();
result = 31 * result + (protectionDomain != null ? protectionDomain.hashCode() : 0);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + accessControlContext.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Simple.Resolution.BootstrapClassLoaderCapableInjectorFactory{" +
"bootstrapInjectionStrategy=" + bootstrapInjectionStrategy +
", classLoader=" + classLoader +
", protectionDomain=" + protectionDomain +
", accessControlContext=" + accessControlContext +
'}';
}
}
}
}
/**
* A compound transformation that applied several transformation in the given order and applies the first active transformation.
*/
class Compound implements Transformation {
/**
* The list of transformations to apply in their application order.
*/
private final List<? extends Transformation> transformations;
/**
* Creates a new compound transformation.
*
* @param transformation An array of transformations to apply in their application order.
*/
protected Compound(Transformation... transformation) {
this(Arrays.asList(transformation));
}
/**
* Creates a new compound transformation.
*
* @param transformations A list of transformations to apply in their application order.
*/
protected Compound(List<? extends Transformation> transformations) {
this.transformations = transformations;
}
@Override
public Resolution resolve(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
RawMatcher ignoredTypeMatcher) {
Resolution current = new Resolution.Unresolved(typeDescription, classLoader, module);
for (Transformation transformation : transformations) {
Resolution resolution = transformation.resolve(typeDescription,
classLoader,
module,
classBeingRedefined,
protectionDomain,
ignoredTypeMatcher);
switch (resolution.getSort()) {
case TERMINAL:
return current.asDecoratorOf(resolution);
case DECORATOR:
current = current.asDecoratorOf(resolution);
break;
case UNDEFINED:
break;
default:
throw new IllegalStateException("Unexpected resolution type: " + resolution.getSort());
}
}
return current;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& transformations.equals(((Compound) other).transformations);
}
@Override
public int hashCode() {
return transformations.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Compound{" +
"transformations=" + transformations +
'}';
}
}
}
/**
* A {@link java.lang.instrument.ClassFileTransformer} that implements the enclosing agent builder's
* configuration.
*/
protected static class ExecutingTransformer implements ClassFileTransformer {
/**
* A factory for creating a {@link ClassFileTransformer} that supports the features of the current VM.
*/
protected static final Factory FACTORY;
/*
* Creates a factory for a class file transformer that supports the features of the current VM.
*/
static {
Factory factory;
try {
factory = new Factory.ForJava9CapableVm(new ByteBuddy()
.subclass(ExecutingTransformer.class)
.name(ExecutingTransformer.class.getName() + "$ByteBuddy$ModuleSupport")
.method(named("transform").and(takesArgument(0, JavaType.MODULE.load())))
.intercept(MethodCall.invoke(ExecutingTransformer.class.getDeclaredMethod("transform",
Object.class,
String.class,
Class.class,
ProtectionDomain.class,
byte[].class)).onSuper().withAllArguments())
.make()
.load(ExecutingTransformer.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.getDeclaredConstructor(ByteBuddy.class,
TypeLocator.class,
TypeStrategy.class,
LocationStrategy.class,
Listener.class,
NativeMethodStrategy.class,
AccessControlContext.class,
InitializationStrategy.class,
BootstrapInjectionStrategy.class,
DescriptionStrategy.class,
RawMatcher.class,
Transformation.class));
} catch (RuntimeException exception) {
throw exception;
} catch (Exception ignored) {
factory = Factory.ForLegacyVm.INSTANCE;
}
FACTORY = factory;
}
/**
* The Byte Buddy instance to be used.
*/
private final ByteBuddy byteBuddy;
/**
* The type locator to use.
*/
private final TypeLocator typeLocator;
/**
* The definition handler to use.
*/
private final TypeStrategy typeStrategy;
/**
* The listener to notify on transformations.
*/
private final Listener listener;
/**
* The native method strategy to apply.
*/
private final NativeMethodStrategy nativeMethodStrategy;
/**
* The access control context to use for loading classes.
*/
private final AccessControlContext accessControlContext;
/**
* The initialization strategy to use for transformed types.
*/
private final InitializationStrategy initializationStrategy;
/**
* The injection strategy for injecting classes into the bootstrap class loader.
*/
private final BootstrapInjectionStrategy bootstrapInjectionStrategy;
/**
* The description strategy for resolving type descriptions for types.
*/
private final DescriptionStrategy descriptionStrategy;
/**
* The location strategy to use.
*/
private final LocationStrategy locationStrategy;
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoredTypeMatcher;
/**
* The transformation object for handling type transformations.
*/
private final Transformation transformation;
/**
* Creates a new class file transformer.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param typeLocator The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to notify on transformations.
* @param nativeMethodStrategy The native method strategy to apply.
* @param accessControlContext The access control context to use for loading classes.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param bootstrapInjectionStrategy The injection strategy for injecting classes into the bootstrap class loader.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @param transformation The transformation object for handling type transformations.
*/
public ExecutingTransformer(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
DescriptionStrategy descriptionStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation) {
this.byteBuddy = byteBuddy;
this.typeLocator = typeLocator;
this.locationStrategy = locationStrategy;
this.typeStrategy = typeStrategy;
this.listener = listener;
this.nativeMethodStrategy = nativeMethodStrategy;
this.accessControlContext = accessControlContext;
this.initializationStrategy = initializationStrategy;
this.bootstrapInjectionStrategy = bootstrapInjectionStrategy;
this.descriptionStrategy = descriptionStrategy;
this.ignoredTypeMatcher = ignoredTypeMatcher;
this.transformation = transformation;
}
@Override
public byte[] transform(ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
return transform(JavaModule.UNSUPPORTED, classLoader, internalTypeName, classBeingRedefined, protectionDomain, binaryRepresentation);
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}.
*
* @param rawModule The instrumented class's Java {@code java.lang.reflect.Module}.
* @param internalTypeName The internal name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param protectionDomain The instrumented type's protection domain.
* @param binaryRepresentation The class file of the instrumented class in its current state.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
protected byte[] transform(Object rawModule,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
JavaModule module = JavaModule.of(rawModule);
return transform(module,
module.getClassLoader(accessControlContext),
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation);
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}.
*
* @param module The instrumented class's Java module in its wrapped form or {@code null} if the current VM does not support modules.
* @param classLoader The instrumented class's class loader.
* @param internalTypeName The internal name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param protectionDomain The instrumented type's protection domain.
* @param binaryRepresentation The class file of the instrumented class in its current state.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
private byte[] transform(JavaModule module,
ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
if (internalTypeName == null) {
return NO_TRANSFORMATION;
}
String binaryTypeName = internalTypeName.replace('/', '.');
try {
ClassFileLocator classFileLocator = ClassFileLocator.Simple.of(binaryTypeName,
binaryRepresentation,
locationStrategy.classFileLocator(classLoader, module));
TypePool typePool = typeLocator.typePool(classFileLocator, classLoader);
return transformation.resolve(descriptionStrategy.apply(binaryTypeName, classBeingRedefined, typePool),
classLoader,
module,
classBeingRedefined,
protectionDomain,
ignoredTypeMatcher).apply(initializationStrategy,
classFileLocator,
typeStrategy,
byteBuddy,
nativeMethodStrategy,
bootstrapInjectionStrategy,
accessControlContext,
listener);
} catch (Throwable throwable) {
listener.onError(binaryTypeName, classLoader, module, throwable);
return NO_TRANSFORMATION;
} finally {
listener.onComplete(binaryTypeName, classLoader, module);
}
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
ExecutingTransformer that = (ExecutingTransformer) other;
return byteBuddy.equals(that.byteBuddy)
&& typeLocator.equals(that.typeLocator)
&& typeStrategy.equals(that.typeStrategy)
&& locationStrategy.equals(that.locationStrategy)
&& initializationStrategy.equals(that.initializationStrategy)
&& listener.equals(that.listener)
&& nativeMethodStrategy.equals(that.nativeMethodStrategy)
&& bootstrapInjectionStrategy.equals(that.bootstrapInjectionStrategy)
&& descriptionStrategy.equals(that.descriptionStrategy)
&& accessControlContext.equals(that.accessControlContext)
&& ignoredTypeMatcher.equals(that.ignoredTypeMatcher)
&& transformation.equals(that.transformation);
}
@Override
public int hashCode() {
int result = byteBuddy.hashCode();
result = 31 * result + typeLocator.hashCode();
result = 31 * result + typeStrategy.hashCode();
result = 31 * result + locationStrategy.hashCode();
result = 31 * result + initializationStrategy.hashCode();
result = 31 * result + listener.hashCode();
result = 31 * result + nativeMethodStrategy.hashCode();
result = 31 * result + bootstrapInjectionStrategy.hashCode();
result = 31 * result + descriptionStrategy.hashCode();
result = 31 * result + accessControlContext.hashCode();
result = 31 * result + ignoredTypeMatcher.hashCode();
result = 31 * result + transformation.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.ExecutingTransformer{" +
"byteBuddy=" + byteBuddy +
", typeLocator=" + typeLocator +
", typeStrategy=" + typeStrategy +
", locationStrategy=" + locationStrategy +
", initializationStrategy=" + initializationStrategy +
", listener=" + listener +
", nativeMethodStrategy=" + nativeMethodStrategy +
", bootstrapInjectionStrategy=" + bootstrapInjectionStrategy +
", descriptionStrategy=" + descriptionStrategy +
", accessControlContext=" + accessControlContext +
", ignoredTypeMatcher=" + ignoredTypeMatcher +
", transformation=" + transformation +
'}';
}
/**
* A factory for creating a {@link ClassFileTransformer} for the current VM.
*/
protected interface Factory {
/**
* Creates a new class file transformer for the current VM.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param typeLocator The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to notify on transformations.
* @param nativeMethodStrategy The native method strategy to apply.
* @param accessControlContext The access control context to use for loading classes.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param bootstrapInjectionStrategy The injection strategy for injecting classes into the bootstrap class loader.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @param transformation The transformation object for handling type transformations.
* @return A class file transformer for the current VM that supports the API of the current VM.
*/
ClassFileTransformer make(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
DescriptionStrategy descriptionStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation);
/**
* A factory for a class file transformer on a JVM that supports the {@code java.lang.reflect.Module} API to override
* the newly added method of the {@link ClassFileTransformer} to capture an instrumented class's module.
*/
class ForJava9CapableVm implements Factory {
/**
* A constructor for creating a {@link ClassFileTransformer} that overrides the newly added method for extracting
* the {@code java.lang.reflect.Module} of an instrumented class.
*/
private final Constructor<? extends ClassFileTransformer> executingTransformer;
/**
* Creates a class file transformer factory for a Java 9 capable VM.
*
* @param executingTransformer A constructor for creating a {@link ClassFileTransformer} that overrides the newly added
* method for extracting the {@code java.lang.reflect.Module} of an instrumented class.
*/
protected ForJava9CapableVm(Constructor<? extends ClassFileTransformer> executingTransformer) {
this.executingTransformer = executingTransformer;
}
@Override
public ClassFileTransformer make(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
DescriptionStrategy descriptionStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation) {
try {
return executingTransformer.newInstance(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
bootstrapInjectionStrategy,
descriptionStrategy,
ignoredTypeMatcher,
transformation);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access " + executingTransformer, exception);
} catch (InstantiationException exception) {
throw new IllegalStateException("Cannot instantiate " + executingTransformer.getDeclaringClass(), exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Cannot invoke " + executingTransformer, exception.getCause());
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForJava9CapableVm that = (ForJava9CapableVm) object;
return executingTransformer.equals(that.executingTransformer);
}
@Override
public int hashCode() {
return executingTransformer.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Default.ExecutingTransformer.Factory.ForJava9CapableVm{" +
"executingTransformer=" + executingTransformer +
'}';
}
}
/**
* A factory for a {@link ClassFileTransformer} on a VM that does not support the {@code java.lang.reflect.Module} API.
*/
enum ForLegacyVm implements Factory {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ClassFileTransformer make(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
DescriptionStrategy descriptionStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation) {
return new ExecutingTransformer(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
bootstrapInjectionStrategy,
descriptionStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public String toString() {
return "AgentBuilder.Default.ExecutingTransformer.Factory.ForLegacyVm." + name();
}
}
}
}
/**
* An abstract implementation of an agent builder that delegates all invocation to another instance.
*
* @param <T> The type that is produced by chaining a matcher.
*/
protected abstract class Delegator<T extends Matchable<T>> extends Matchable.AbstractBase<T> implements AgentBuilder {
/**
* Materializes the currently described {@link net.bytebuddy.agent.builder.AgentBuilder}.
*
* @return An agent builder that represents the currently described entry of this instance.
*/
protected abstract AgentBuilder materialize();
@Override
public AgentBuilder with(ByteBuddy byteBuddy) {
return materialize().with(byteBuddy);
}
@Override
public AgentBuilder with(Listener listener) {
return materialize().with(listener);
}
@Override
public AgentBuilder with(TypeStrategy typeStrategy) {
return materialize().with(typeStrategy);
}
@Override
public AgentBuilder with(TypeLocator typeLocator) {
return materialize().with(typeLocator);
}
@Override
public AgentBuilder with(LocationStrategy locationStrategy) {
return materialize().with(locationStrategy);
}
@Override
public AgentBuilder with(AccessControlContext accessControlContext) {
return materialize().with(accessControlContext);
}
@Override
public AgentBuilder with(InitializationStrategy initializationStrategy) {
return materialize().with(initializationStrategy);
}
@Override
public AgentBuilder with(RedefinitionStrategy redefinitionStrategy) {
return materialize().with(redefinitionStrategy);
}
@Override
public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) {
return materialize().with(lambdaInstrumentationStrategy);
}
@Override
public AgentBuilder with(DescriptionStrategy descriptionStrategy) {
return materialize().with(descriptionStrategy);
}
@Override
public AgentBuilder with(InstallationStrategy installationStrategy) {
return materialize().with(installationStrategy);
}
@Override
public AgentBuilder enableBootstrapInjection(Instrumentation instrumentation, File folder) {
return materialize().enableBootstrapInjection(instrumentation, folder);
}
@Override
public AgentBuilder disableBootstrapInjection() {
return materialize().disableBootstrapInjection();
}
@Override
public AgentBuilder enableNativeMethodPrefix(String prefix) {
return materialize().enableNativeMethodPrefix(prefix);
}
@Override
public AgentBuilder disableNativeMethodPrefix() {
return materialize().disableNativeMethodPrefix();
}
@Override
public AgentBuilder disableClassFormatChanges() {
return materialize().disableClassFormatChanges();
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type) {
return materialize().assureReadEdgeTo(instrumentation, type);
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module) {
return materialize().assureReadEdgeTo(instrumentation, module);
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return materialize().assureReadEdgeTo(instrumentation, modules);
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type) {
return materialize().assureReadEdgeFromAndTo(instrumentation, type);
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module) {
return materialize().assureReadEdgeFromAndTo(instrumentation, module);
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return materialize().assureReadEdgeFromAndTo(instrumentation, modules);
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher) {
return materialize().type(typeMatcher);
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return materialize().type(typeMatcher, classLoaderMatcher);
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return materialize().type(typeMatcher, classLoaderMatcher, moduleMatcher);
}
@Override
public Identified.Narrowable type(RawMatcher matcher) {
return materialize().type(matcher);
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> ignoredTypes) {
return materialize().ignore(ignoredTypes);
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> ignoredTypes, ElementMatcher<? super ClassLoader> ignoredClassLoaders) {
return materialize().ignore(ignoredTypes, ignoredClassLoaders);
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return materialize().ignore(typeMatcher, classLoaderMatcher, moduleMatcher);
}
@Override
public Ignored ignore(RawMatcher rawMatcher) {
return materialize().ignore(rawMatcher);
}
@Override
public ClassFileTransformer makeRaw() {
return materialize().makeRaw();
}
@Override
public ClassFileTransformer installOn(Instrumentation instrumentation) {
return materialize().installOn(instrumentation);
}
@Override
public ClassFileTransformer installOnByteBuddyAgent() {
return materialize().installOnByteBuddyAgent();
}
}
/**
* A delegator transformer for further precising what types to ignore.
*/
protected class Ignoring extends Delegator<Ignored> implements Ignored {
/**
* A matcher for identifying types that should not be instrumented.
*/
private final RawMatcher rawMatcher;
/**
* Creates a new agent builder for further specifying what types to ignore.
*
* @param rawMatcher A matcher for identifying types that should not be instrumented.
*/
protected Ignoring(RawMatcher rawMatcher) {
this.rawMatcher = rawMatcher;
}
@Override
protected AgentBuilder materialize() {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
rawMatcher,
transformation);
}
@Override
public Ignored and(RawMatcher rawMatcher) {
return new Ignoring(new RawMatcher.Conjunction(this.rawMatcher, rawMatcher));
}
@Override
public Ignored or(RawMatcher rawMatcher) {
return new Ignoring(new RawMatcher.Disjunction(this.rawMatcher, rawMatcher));
}
/**
* Returns the outer instance.
*
* @return The outer instance.
*/
private Default getOuter() {
return Default.this;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& rawMatcher.equals(((Ignoring) other).rawMatcher)
&& Default.this.equals(((Ignoring) other).getOuter());
}
@Override
public int hashCode() {
int result = rawMatcher.hashCode();
result = 31 * result + Default.this.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Ignoring{" +
"rawMatcher=" + rawMatcher +
", agentBuilder=" + Default.this +
'}';
}
}
/**
* A helper class that describes a {@link net.bytebuddy.agent.builder.AgentBuilder.Default} after supplying
* a {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} such that one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s can be supplied.
*/
protected class Transforming extends Delegator<Identified.Narrowable> implements Identified.Extendable, Identified.Narrowable {
/**
* The supplied raw matcher.
*/
private final RawMatcher rawMatcher;
/**
* The supplied transformer.
*/
private final Transformer transformer;
/**
* {@code true} if this transformer serves as a decorator.
*/
private final boolean decorator;
/**
* Creates a new matched default agent builder.
*
* @param rawMatcher The supplied raw matcher.
* @param transformer The supplied transformer.
* @param decorator {@code true} if this transformer serves as a decorator.
*/
protected Transforming(RawMatcher rawMatcher, Transformer transformer, boolean decorator) {
this.rawMatcher = rawMatcher;
this.transformer = transformer;
this.decorator = decorator;
}
@Override
protected AgentBuilder materialize() {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
new Transformation.Compound(new Transformation.Simple(rawMatcher, transformer, decorator), transformation));
}
@Override
public Identified.Extendable transform(Transformer transformer) {
return new Transforming(rawMatcher, new Transformer.Compound(this.transformer, transformer), decorator);
}
@Override
public AgentBuilder asDecorator() {
return new Transforming(rawMatcher, transformer, true);
}
@Override
public Narrowable and(RawMatcher rawMatcher) {
return new Transforming(new RawMatcher.Conjunction(this.rawMatcher, rawMatcher), transformer, decorator);
}
@Override
public Narrowable or(RawMatcher rawMatcher) {
return new Transforming(new RawMatcher.Disjunction(this.rawMatcher, rawMatcher), transformer, decorator);
}
/**
* Returns the outer instance.
*
* @return The outer instance.
*/
private Default getOuter() {
return Default.this;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& decorator == ((Transforming) other).decorator
&& rawMatcher.equals(((Transforming) other).rawMatcher)
&& transformer.equals(((Transforming) other).transformer)
&& Default.this.equals(((Transforming) other).getOuter());
}
@Override
public int hashCode() {
int result = rawMatcher.hashCode();
result = 31 * result + (decorator ? 1 : 0);
result = 31 * result + transformer.hashCode();
result = 31 * result + Default.this.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transforming{" +
"rawMatcher=" + rawMatcher +
", transformer=" + transformer +
", decorator=" + decorator +
", agentBuilder=" + Default.this +
'}';
}
}
}
}
| byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java | package net.bytebuddy.agent.builder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.modifier.*;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassInjector;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.dynamic.scaffold.inline.MethodNameTransformer;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import net.bytebuddy.implementation.ExceptionMethod;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.LoadedTypeInitializer;
import net.bytebuddy.implementation.MethodCall;
import net.bytebuddy.implementation.auxiliary.AuxiliaryType;
import net.bytebuddy.implementation.bytecode.*;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
import net.bytebuddy.implementation.bytecode.collection.ArrayFactory;
import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
import net.bytebuddy.implementation.bytecode.constant.NullConstant;
import net.bytebuddy.implementation.bytecode.constant.TextConstant;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import net.bytebuddy.implementation.bytecode.member.MethodReturn;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.JavaConstant;
import net.bytebuddy.utility.JavaModule;
import net.bytebuddy.utility.JavaType;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import java.io.*;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import static net.bytebuddy.matcher.ElementMatchers.*;
/**
* <p>
* An agent builder provides a convenience API for defining a
* <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html">Java agent</a>. By default,
* this transformation is applied by rebasing the type if not specified otherwise by setting a
* {@link TypeStrategy}.
* </p>
* <p>
* When defining several {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s, the agent builder always
* applies the transformers that were supplied with the last applicable matcher. Therefore, more general transformers
* should be defined first.
* </p>
*/
public interface AgentBuilder {
/**
* Defines the given {@link net.bytebuddy.ByteBuddy} instance to be used by the created agent.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @return A new instance of this agent builder which makes use of the given {@code byteBuddy} instance.
*/
AgentBuilder with(ByteBuddy byteBuddy);
/**
* Defines the given {@link net.bytebuddy.agent.builder.AgentBuilder.Listener} to be notified by the created agent.
* The given listener is notified after any other listener that is already registered. If a listener is registered
* twice, it is also notified twice.
*
* @param listener The listener to be notified.
* @return A new instance of this agent builder which creates an agent that informs the given listener about
* events.
*/
AgentBuilder with(Listener listener);
/**
* Defines the use of the given type locator for locating a {@link TypeDescription} for an instrumented type.
*
* @param typeLocator The type locator to use.
* @return A new instance of this agent builder which uses the given type locator for looking up class files.
*/
AgentBuilder with(TypeLocator typeLocator);
/**
* Defines the use of the given location strategy for locating binary data to given class names.
*
* @param locationStrategy The location strategy to use.
* @return A new instance of this agent builder which uses the given location strategy for looking up class files.
*/
AgentBuilder with(LocationStrategy locationStrategy);
/**
* Defines how types should be transformed, e.g. if they should be rebased or redefined by the created agent.
*
* @param typeStrategy The type strategy to use.
* @return A new instance of this agent builder which uses the given type strategy.
*/
AgentBuilder with(TypeStrategy typeStrategy);
/**
* Assures that critical actions are performed using the supplied access control context.
*
* @param accessControlContext The access control context to be used for performing security critical action.
* @return A new instance of this agent builder which uses the given access control context for performing critical actions.
*/
AgentBuilder with(AccessControlContext accessControlContext);
/**
* Defines a given initialization strategy to be applied to generated types. An initialization strategy is responsible
* for setting up a type after it was loaded. This initialization must be performed after the transformation because
* a Java agent is only invoked before loading a type. By default, the initialization logic is added to a class's type
* initializer which queries a global object for any objects that are to be injected into the generated type.
*
* @param initializationStrategy The initialization strategy to use.
* @return A new instance of this agent builder that applies the given initialization strategy.
*/
AgentBuilder with(InitializationStrategy initializationStrategy);
/**
* Specifies a strategy for modifying types that were already loaded prior to the installation of this transformer.
*
* @param redefinitionStrategy The redefinition strategy to apply.
* @return A new instance of this agent builder that applies the given redefinition strategy.
*/
AgentBuilder with(RedefinitionStrategy redefinitionStrategy);
/**
* <p>
* Enables or disables management of the JVM's {@code LambdaMetafactory} which is responsible for creating classes that
* implement lambda expressions. Without this feature enabled, classes that are represented by lambda expressions are
* not instrumented by the JVM such that Java agents have no effect on them when a lambda expression's class is loaded
* for the first time.
* </p>
* <p>
* When activating this feature, Byte Buddy instruments the {@code LambdaMetafactory} and takes over the responsibility
* of creating classes that represent lambda expressions. In doing so, Byte Buddy has the opportunity to apply the built
* class file transformer. If the current VM does not support lambda expressions, activating this feature has no effect.
* </p>
* <p>
* <b>Important</b>: If this feature is active, it is important to release the built class file transformer when
* deactivating it. Normally, it is sufficient to call {@link Instrumentation#removeTransformer(ClassFileTransformer)}.
* When this feature is enabled, it is however also required to invoke
* {@link LambdaInstrumentationStrategy#release(ClassFileTransformer, Instrumentation)}. Otherwise, the executing VMs class
* loader retains a reference to the class file transformer what can cause a memory leak.
* </p>
*
* @param lambdaInstrumentationStrategy {@code true} if this feature should be enabled.
* @return A new instance of this agent builder where this feature is explicitly enabled or disabled.
*/
AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy);
/**
* Specifies a strategy to be used for resolving {@link TypeDescription} for any type handled by the created transformer.
*
* @param descriptionStrategy The description strategy to use.
* @return A new instance of this agent builder that applies the given description strategy.
*/
AgentBuilder with(DescriptionStrategy descriptionStrategy);
/**
* Specifies an installation strategy that this agent builder applies upon installing an agent.
*
* @param installationStrategy The installation strategy to be used.
* @return A new agent builder that applies the supplied installation strategy.
*/
AgentBuilder with(InstallationStrategy installationStrategy);
/**
* Enables class injection of auxiliary classes into the bootstrap class loader.
*
* @param instrumentation The instrumentation instance that is used for appending jar files to the
* bootstrap class path.
* @param folder The folder in which jar files of the injected classes are to be stored.
* @return An agent builder with bootstrap class loader class injection enabled.
*/
AgentBuilder enableBootstrapInjection(Instrumentation instrumentation, File folder);
/**
* Enables the use of the given native method prefix for instrumented methods. Note that this prefix is also
* applied when preserving non-native methods. The use of this prefix is also registered when installing the
* final agent with an {@link java.lang.instrument.Instrumentation}.
*
* @param prefix The prefix to be used.
* @return A new instance of this agent builder which uses the given native method prefix.
*/
AgentBuilder enableNativeMethodPrefix(String prefix);
/**
* Disables the use of a native method prefix for instrumented methods.
*
* @return A new instance of this agent builder which does not use a native method prefix.
*/
AgentBuilder disableNativeMethodPrefix();
/**
* Disables injection of auxiliary classes into the bootstrap class path.
*
* @return A new instance of this agent builder which does not apply bootstrap class loader injection.
*/
AgentBuilder disableBootstrapInjection();
/**
* <p>
* Disables all implicit changes on a class file that Byte Buddy would apply for certain instrumentations. When
* using this option, it is no longer possible to rebase a method, i.e. intercepted methods are fully replaced. Furthermore,
* it is no longer possible to implicitly apply loaded type initializers for explicitly initializing the generated type.
* </p>
* <p>
* This is equivalent to setting {@link InitializationStrategy.NoOp} and {@link TypeStrategy.Default#REDEFINE_DECLARED_ONLY}
* as well as configuring the underlying {@link ByteBuddy} instance to use a {@link net.bytebuddy.implementation.Implementation.Context.Disabled}.
* </p>
*
* @return A new instance of this agent builder that does not apply any implicit changes to the received class file.
*/
AgentBuilder disableClassFormatChanges();
/**
* Assures that all modules of the supplied types are read by the module of any instrumented type. If the current VM does not support
* the Java module system, calling this method has no effect and this instance is returned.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param type The types for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type);
/**
* Assures that all supplied modules are read by the module of any instrumented type.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param module The modules for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module);
/**
* Assures that all supplied modules are read by the module of any instrumented type.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param modules The modules for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules);
/**
* Assures that all modules of the supplied types are read by the module of any instrumented type and vice versa.
* If the current VM does not support the Java module system, calling this method has no effect and this instance is returned.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param type The types for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type);
/**
* Assures that all supplied modules are read by the module of any instrumented type and vice versa.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param module The modules for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module);
/**
* Assures that all supplied modules are read by the module of any instrumented type and vice versa.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param modules The modules for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, this matcher is always executed first whereas the following matchers are
* executed in the order of their execution. If any matcher indicates that a type is to be matched, none of the following matchers is still queried.
* This behavior can be changed by {@link Identified.Extendable#asDecorator()} where subsequent type matchers are also applied.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it is
* also recommended, to exclude class loaders such as for example the bootstrap class loader by using
* {@link AgentBuilder#type(ElementMatcher, ElementMatcher)} instead.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being loaded that
* decides if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should
* be applied for that type.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code typeMatcher}
* indicates a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, this matcher is always executed first whereas the following matchers are
* executed in the order of their execution. If any matcher indicates that a type is to be matched, none of the following matchers is still queried.
* This behavior can be changed by {@link Identified.Extendable#asDecorator()} where subsequent type matchers are also applied.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being
* loaded that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for
* that type.
* @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the
* {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher
* is always applied first where the type matcher is not applied in case that this
* matcher does not indicate a match.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given
* {@code typeMatcher} and {@code classLoaderMatcher} indicate a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, this matcher is always executed first whereas the following matchers are
* executed in the order of their execution. If any matcher indicates that a type is to be matched, none of the following matchers is still queried.
* This behavior can be changed by {@link Identified.Extendable#asDecorator()} where subsequent type matchers are also applied.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being
* loaded that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for
* that type.
* @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the
* {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher
* is always applied second where the type matcher is not applied in case that this
* matcher does not indicate a match.
* @param moduleMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the {@link JavaModule}
* of the type being loaded. This matcher is always applied first where the class loader and
* type matchers are not applied in case that this matcher does not indicate a match. On a JVM
* that does not support the Java modules system, this matcher is not applied.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given
* {@code typeMatcher} and {@code classLoaderMatcher} indicate a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, this matcher is always executed first whereas the following matchers are
* executed in the order of their execution. If any matcher indicates that a type is to be matched, none of the following matchers is still queried.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param matcher A matcher that decides if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be
* applied for a type that is being loaded.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code matcher}
* indicates a match.
*/
Identified.Narrowable type(RawMatcher matcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher from instrumentation and considers types by all {@link ClassLoader}s.
* By default, Byte Buddy does not instrument synthetic types or types that are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher and is loaded by a class loader matching the second matcher.
* By default, Byte Buddy does not instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that
* are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @param classLoaderMatcher A matcher that identifies a class loader that identifies classes that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher and is loaded by a class loader matching the second matcher.
* By default, Byte Buddy does not instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that
* are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @param classLoaderMatcher A matcher that identifies a class loader that identifies classes that should not be instrumented.
* @param moduleMatcher A matcher that identifies a module that identifies classes that should not be instrumented. On a JVM
* that does not support the Java modules system, this matcher is not applied.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* <p>
* Excludes any type that is matched by the raw matcher provided to this method. By default, Byte Buddy does not
* instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param rawMatcher A raw matcher that identifies types that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(RawMatcher rawMatcher);
/**
* Creates a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of this
* agent builder.
*
* @return A class file transformer that implements the configuration of this agent builder.
*/
ClassFileTransformer makeRaw();
/**
* <p>
* Creates and installs a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of
* this agent builder with a given {@link java.lang.instrument.Instrumentation}. If retransformation is enabled,
* the installation also causes all loaded types to be retransformed.
* </p>
* <p>
* If installing the created class file transformer causes an exception to be thrown, the consequences of this
* exception are determined by the {@link InstallationStrategy} of this builder.
* </p>
*
* @param instrumentation The instrumentation on which this agent builder's configuration is to be installed.
* @return The installed class file transformer.
*/
ClassFileTransformer installOn(Instrumentation instrumentation);
/**
* Creates and installs a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of
* this agent builder with the Byte Buddy-agent which must be installed prior to calling this method.
*
* @return The installed class file transformer.
* @see AgentBuilder#installOn(Instrumentation)
*/
ClassFileTransformer installOnByteBuddyAgent();
/**
* An abstraction for extending a matcher.
*
* @param <T> The type that is produced by chaining a matcher.
*/
interface Matchable<T extends Matchable<T>> {
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched. When matching a
* type, class loaders are not considered.
*
* @param typeMatcher A matcher for the type being matched.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @param moduleMatcher A matcher for the type's module. On a JVM that does not support modules, the Java module is represented by {@code null}.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param rawMatcher A raw matcher for the type being matched.
* @return A chained matcher.
*/
T and(RawMatcher rawMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched. When matching a
* type, the class loader is not considered.
*
* @param typeMatcher A matcher for the type being matched.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @param moduleMatcher A matcher for the type's module. On a JVM that does not support modules, the Java module is represented by {@code null}.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param rawMatcher A raw matcher for the type being matched.
* @return A chained matcher.
*/
T or(RawMatcher rawMatcher);
/**
* An abstract base implementation of a matchable.
*
* @param <S> The type that is produced by chaining a matcher.
*/
abstract class AbstractBase<S extends Matchable<S>> implements Matchable<S> {
@Override
public S and(ElementMatcher<? super TypeDescription> typeMatcher) {
return and(typeMatcher, any());
}
@Override
public S and(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return and(typeMatcher, classLoaderMatcher, any());
}
@Override
public S and(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return and(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, moduleMatcher));
}
@Override
public S or(ElementMatcher<? super TypeDescription> typeMatcher) {
return or(typeMatcher, any());
}
@Override
public S or(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return or(typeMatcher, classLoaderMatcher, any());
}
@Override
public S or(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return or(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, moduleMatcher));
}
}
}
/**
* Allows to further specify ignored types.
*/
interface Ignored extends Matchable<Ignored>, AgentBuilder {
/* this is merely a unionizing interface that does not declare methods */
}
/**
* Describes an {@link net.bytebuddy.agent.builder.AgentBuilder} which was handed a matcher for identifying
* types to instrumented in order to supply one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*/
interface Identified {
/**
* Applies the given transformer for the already supplied matcher.
*
* @param transformer The transformer to apply.
* @return A new instance of this agent builder with the transformer being applied when the previously supplied matcher
* identified a type for instrumentation which also allows for the registration of subsequent transformers.
*/
Extendable transform(Transformer transformer);
/**
* Allows to specify a type matcher for a type to instrument.
*/
interface Narrowable extends Matchable<Narrowable>, Identified {
/* this is merely a unionizing interface that does not declare methods */
}
/**
* This interface is used to allow for optionally providing several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} to applied when a matcher identifies a type
* to be instrumented. Any subsequent transformers are applied in the order they are registered.
*/
interface Extendable extends AgentBuilder, Identified {
/**
* <p>
* Applies the specified transformation as a decorative transformation. For a decorative transformation, the supplied
* transformer is prepended to any previous transformation that also matches the instrumented type, i.e. both transformations
* are supplied. This procedure is repeated until a transformer is reached that matches the instrumented type but is not
* defined as decorating after which no further transformations are considered. If all matching transformations are declared
* as decorating, all matching transformers are applied.
* </p>
* <p>
* <b>Note</b>: A decorating transformer is applied <b>after</b> previously registered transformers.
* </p>
*
* @return A new instance of this agent builder with the specified transformation being applied as a decorator.
*/
AgentBuilder asDecorator();
}
}
/**
* A matcher that allows to determine if a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}
* should be applied during the execution of a {@link java.lang.instrument.ClassFileTransformer} that was
* generated by an {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface RawMatcher {
/**
* Decides if the given {@code typeDescription} should be instrumented with the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*
* @param typeDescription A description of the type to be instrumented.
* @param classLoader The class loader of the instrumented type. Might be {@code null} if this class
* loader represents the bootstrap class loader.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param classBeingRedefined The class being redefined which is only not {@code null} if a retransformation
* is applied.
* @param protectionDomain The protection domain of the type being transformed.
* @return {@code true} if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should
* be applied for the given {@code typeDescription}.
*/
boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain);
/**
* A conjunction of two raw matchers.
*/
class Conjunction implements RawMatcher {
/**
* The left matcher which is applied first.
*/
private final RawMatcher left;
/**
* The right matcher which is applied second.
*/
private final RawMatcher right;
/**
* Creates a new conjunction of two raw matchers.
*
* @param left The left matcher which is applied first.
* @param right The right matcher which is applied second.
*/
protected Conjunction(RawMatcher left, RawMatcher right) {
this.left = left;
this.right = right;
}
@Override
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return left.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
&& right.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Conjunction that = (Conjunction) object;
return left.equals(that.left) && right.equals(that.right);
}
@Override
public int hashCode() {
int result = left.hashCode();
result = 31 * result + right.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.RawMatcher.Conjunction{" +
"left=" + left +
", right=" + right +
'}';
}
}
/**
* A disjunction of two raw matchers.
*/
class Disjunction implements RawMatcher {
/**
* The left matcher which is applied first.
*/
private final RawMatcher left;
/**
* The right matcher which is applied second.
*/
private final RawMatcher right;
/**
* Creates a new disjunction of two raw matchers.
*
* @param left The left matcher which is applied first.
* @param right The right matcher which is applied second.
*/
protected Disjunction(RawMatcher left, RawMatcher right) {
this.left = left;
this.right = right;
}
@Override
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return left.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
|| right.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Disjunction that = (Disjunction) object;
return left.equals(that.left) && right.equals(that.right);
}
@Override
public int hashCode() {
int result = left.hashCode();
result = 31 * result + right.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.RawMatcher.Disjunction{" +
"left=" + left +
", right=" + right +
'}';
}
}
/**
* A raw matcher implementation that checks a {@link TypeDescription}
* and its {@link java.lang.ClassLoader} against two suitable matchers in order to determine if the matched
* type should be instrumented.
*/
class ForElementMatchers implements RawMatcher {
/**
* The type matcher to apply to a {@link TypeDescription}.
*/
private final ElementMatcher<? super TypeDescription> typeMatcher;
/**
* The class loader matcher to apply to a {@link java.lang.ClassLoader}.
*/
private final ElementMatcher<? super ClassLoader> classLoaderMatcher;
/**
* A module matcher to apply to a {@code java.lang.reflect.Module}.
*/
private final ElementMatcher<? super JavaModule> moduleMatcher;
/**
* Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the
* supplied {@link TypeDescription} and its {@link java.lang.ClassLoader} against two matcher in order
* to decided if an instrumentation should be conducted.
*
* @param typeMatcher The type matcher to apply to a {@link TypeDescription}.
* @param classLoaderMatcher The class loader matcher to apply to a {@link java.lang.ClassLoader}.
* @param moduleMatcher A module matcher to apply to a {@code java.lang.reflect.Module}.
*/
public ForElementMatchers(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
this.typeMatcher = typeMatcher;
this.classLoaderMatcher = classLoaderMatcher;
this.moduleMatcher = moduleMatcher;
}
@Override
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return moduleMatcher.matches(module) && classLoaderMatcher.matches(classLoader) && typeMatcher.matches(typeDescription);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& classLoaderMatcher.equals(((ForElementMatchers) other).classLoaderMatcher)
&& moduleMatcher.equals(((ForElementMatchers) other).moduleMatcher)
&& typeMatcher.equals(((ForElementMatchers) other).typeMatcher);
}
@Override
public int hashCode() {
int result = typeMatcher.hashCode();
result = 31 * result + classLoaderMatcher.hashCode();
result = 31 * result + moduleMatcher.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.RawMatcher.ForElementMatchers{" +
"typeMatcher=" + typeMatcher +
", classLoaderMatcher=" + classLoaderMatcher +
", moduleMatcher=" + moduleMatcher +
'}';
}
}
}
/**
* A type strategy is responsible for creating a type builder for a type that is being instrumented.
*/
interface TypeStrategy {
/**
* Creates a type builder for a given type.
*
* @param typeDescription The type being instrumented.
* @param byteBuddy The Byte Buddy configuration.
* @param classFileLocator The class file locator to use.
* @param methodNameTransformer The method name transformer to use.
* @return A type builder for the given arguments.
*/
DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer);
/**
* Default implementations of type strategies.
*/
enum Default implements TypeStrategy {
/**
* A definition handler that performs a rebasing for all types.
*/
REBASE {
@Override
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer) {
return byteBuddy.rebase(typeDescription, classFileLocator, methodNameTransformer);
}
},
/**
* <p>
* A definition handler that performs a redefinition for all types.
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
REDEFINE {
@Override
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer) {
return byteBuddy.redefine(typeDescription, classFileLocator);
}
},
/**
* <p>
* A definition handler that performs a redefinition for all types and ignores all methods that were not declared by the instrumented type.
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
REDEFINE_DECLARED_ONLY {
@Override
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer) {
return byteBuddy.redefine(typeDescription, classFileLocator).ignoreAlso(not(isDeclaredBy(typeDescription)));
}
};
@Override
public String toString() {
return "AgentBuilder.TypeStrategy.Default." + name();
}
}
}
/**
* A transformer allows to apply modifications to a {@link net.bytebuddy.dynamic.DynamicType}. Such a modification
* is then applied to any instrumented type that was matched by the preceding matcher.
*/
interface Transformer {
/**
* Allows for a transformation of a {@link net.bytebuddy.dynamic.DynamicType.Builder}.
*
* @param builder The dynamic builder to transform.
* @param typeDescription The description of the type currently being instrumented.
* @param classLoader The class loader of the instrumented class. Might be {@code null} to
* represent the bootstrap class loader.
* @return A transformed version of the supplied {@code builder}.
*/
DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader);
/**
* A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} that does
* not modify the supplied dynamic type.
*/
enum NoOp implements Transformer {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader) {
return builder;
}
@Override
public String toString() {
return "AgentBuilder.Transformer.NoOp." + name();
}
}
/**
* A compound transformer that allows to group several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s as a single transformer.
*/
class Compound implements Transformer {
/**
* The transformers to apply in their application order.
*/
private final Transformer[] transformer;
/**
* Creates a new compound transformer.
*
* @param transformer The transformers to apply in their application order.
*/
public Compound(Transformer... transformer) {
this.transformer = transformer;
}
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader) {
for (Transformer transformer : this.transformer) {
builder = transformer.transform(builder, typeDescription, classLoader);
}
return builder;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& Arrays.equals(transformer, ((Compound) other).transformer);
}
@Override
public int hashCode() {
return Arrays.hashCode(transformer);
}
@Override
public String toString() {
return "AgentBuilder.Transformer.Compound{" +
"transformer=" + Arrays.toString(transformer) +
'}';
}
}
}
/**
* A type locator allows to specify how {@link TypeDescription}s are resolved by an {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface TypeLocator {
/**
* Creates a type pool for a given class file locator.
*
* @param classFileLocator The class file locator to use.
* @param classLoader The class loader for which the class file locator was created.
* @return A type pool for the supplied class file locator.
*/
TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader);
/**
* A default implementation of a {@link TypeLocator} that is using a {@link net.bytebuddy.pool.TypePool.Default} with a
* {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple}.
*/
enum Default implements TypeLocator {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
Default(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
@Override
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.LazyFacade(new TypePool.Default(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode));
}
@Override
public String toString() {
return "AgentBuilder.TypeLocator.Default." + name();
}
}
/**
* An implementation of a {@link TypeLocator} that is using a {@link net.bytebuddy.pool.TypePool.Default} with a
* {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple}. Additionally, this type locator falls back to class
* loadings for non-locatable class files.
*/
enum ClassLoading implements TypeLocator {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
ClassLoading(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
@Override
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.LazyFacade(TypePool.ClassLoading.of(classLoader, new TypePool.Default(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode)));
}
@Override
public String toString() {
return "AgentBuilder.TypeLocator.ClassLoading." + name();
}
}
/**
* A type locator that uses type pools but allows for the configuration of a custom cache provider by class loader. Note that a
* {@link TypePool} can grow in size and that a static reference is kept to this pool by Byte Buddy's registration of a
* {@link ClassFileTransformer} what can cause a memory leak if the supplied caches are not cleared on a regular basis. Also note
* that a cache provider can be accessed concurrently by multiple {@link ClassLoader}s.
*/
abstract class WithTypePoolCache implements TypeLocator {
/**
* The reader mode to use for parsing a class file.
*/
protected final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator that creates {@link TypePool}s but provides a custom {@link net.bytebuddy.pool.TypePool.CacheProvider}.
*
* @param readerMode The reader mode to use for parsing a class file.
*/
protected WithTypePoolCache(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
@Override
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.LazyFacade(new TypePool.Default(locate(classLoader), classFileLocator, readerMode));
}
/**
* Locates a cache provider for a given class loader.
*
* @param classLoader The class loader for which to locate a cache. This class loader might be {@code null} to represent the bootstrap loader.
* @return The cache provider to use.
*/
protected abstract TypePool.CacheProvider locate(ClassLoader classLoader);
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
WithTypePoolCache that = (WithTypePoolCache) object;
return readerMode == that.readerMode;
}
@Override
public int hashCode() {
return readerMode.hashCode();
}
/**
* An implementation of a type locator {@link WithTypePoolCache} (note documentation of the linked class) that is based on a
* {@link ConcurrentMap}. It is the responsibility of the type locator's user to avoid the type locator from leaking memory.
*/
public static class Simple extends WithTypePoolCache {
/**
* The concurrent map that is used for storing a cache provider per class loader.
*/
private final ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders;
/**
* Creates a new type locator that caches a cache provider per class loader in a concurrent map. The type
* locator uses a fast {@link net.bytebuddy.pool.TypePool.Default.ReaderMode}.
*
* @param cacheProviders The concurrent map that is used for storing a cache provider per class loader.
*/
public Simple(ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders) {
this(TypePool.Default.ReaderMode.FAST, cacheProviders);
}
/**
* Creates a new type locator that caches a cache provider per class loader in a concurrent map.
*
* @param readerMode The reader mode to use for parsing a class file.
* @param cacheProviders The concurrent map that is used for storing a cache provider per class loader.
*/
public Simple(TypePool.Default.ReaderMode readerMode, ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders) {
super(readerMode);
this.cacheProviders = cacheProviders;
}
@Override
protected TypePool.CacheProvider locate(ClassLoader classLoader) {
classLoader = classLoader == null ? BootstrapClassLoaderMarker.INSTANCE : classLoader;
TypePool.CacheProvider cacheProvider = cacheProviders.get(classLoader);
while (cacheProvider == null) {
cacheProviders.putIfAbsent(classLoader, TypePool.CacheProvider.Simple.withObjectType());
cacheProvider = cacheProviders.get(classLoader);
}
return cacheProvider;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
if (!super.equals(object)) return false;
Simple simple = (Simple) object;
return cacheProviders.equals(simple.cacheProviders);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + cacheProviders.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.TypeLocator.WithTypePoolCache.Simple{" +
"cacheProviders=" + cacheProviders +
'}';
}
/**
* A marker for the bootstrap class loader which is represented by {@code null}.
*/
private static class BootstrapClassLoaderMarker extends ClassLoader {
/**
* A static reference to the a singleton instance of the marker to preserve reference equality.
*/
protected static final ClassLoader INSTANCE = AccessController.doPrivileged(new CreationAction());
@Override
protected Class<?> loadClass(String name, boolean resolve) {
throw new UnsupportedOperationException("This loader is only a non-null marker and is not supposed to be used");
}
/**
* A simple action for creating a bootstrap class loader marker.
*/
private static class CreationAction implements PrivilegedAction<ClassLoader> {
@Override
public ClassLoader run() {
return new BootstrapClassLoaderMarker();
}
}
}
}
}
}
/**
* A listener that is informed about events that occur during an instrumentation process.
*/
interface Listener {
/**
* Invoked right before a successful transformation is applied.
*
* @param typeDescription The type that is being transformed.
* @param classLoader The class loader which is loading this type.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param dynamicType The dynamic type that was created.
*/
void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType);
/**
* Invoked when a type is not transformed but ignored.
*
* @param typeDescription The type being ignored for transformation.
* @param classLoader The class loader which is loading this type.
* @param module The ignored type's module or {@code null} if the current VM does not support modules.
*/
void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module);
/**
* Invoked when an error has occurred during transformation.
*
* @param typeName The type name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param throwable The occurred error.
*/
void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable);
/**
* Invoked after a class was attempted to be loaded, independently of its treatment.
*
* @param typeName The binary name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
*/
void onComplete(String typeName, ClassLoader classLoader, JavaModule module);
/**
* A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Listener}.
*/
enum NoOp implements Listener {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
/* do nothing */
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
/* do nothing */
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable) {
/* do nothing */
}
@Override
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module) {
/* do nothing */
}
@Override
public String toString() {
return "AgentBuilder.Listener.NoOp." + name();
}
}
/**
* An adapter for a listener wher all methods are implemented as non-operational.
*/
abstract class Adapter implements Listener {
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
/* do nothing */
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
/* do nothing */
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable) {
/* do nothing */
}
@Override
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module) {
/* do nothing */
}
}
/**
* A listener that writes events to a {@link PrintStream}. This listener prints a line per event, including the event type and
* the name of the type in question.
*/
class StreamWriting implements Listener {
/**
* The prefix that is appended to all written messages.
*/
protected static final String PREFIX = "[Byte Buddy]";
/**
* The print stream written to.
*/
private final PrintStream printStream;
/**
* Creates a new stream writing listener.
*
* @param printStream The print stream written to.
*/
public StreamWriting(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Creates a new stream writing listener that writes to {@link System#out}.
*
* @return A listener writing events to the standard output stream.
*/
public static Listener toSystemOut() {
return new StreamWriting(System.out);
}
/**
* Creates a new stream writing listener that writes to {@link System#err}.
*
* @return A listener writing events to the standad error stream.
*/
public static Listener toSystemError() {
return new StreamWriting(System.err);
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
printStream.println(PREFIX + " TRANSFORM " + typeDescription.getName() + "[" + classLoader + ", " + module + "]");
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
printStream.println(PREFIX + " IGNORE " + typeDescription.getName() + "[" + classLoader + ", " + module + "]");
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable) {
printStream.println(PREFIX + " ERROR " + typeName + "[" + classLoader + ", " + module + "]");
throwable.printStackTrace(printStream);
}
@Override
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module) {
printStream.println(PREFIX + " COMPLETE " + typeName + "[" + classLoader + ", " + module + "]");
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& printStream.equals(((StreamWriting) other).printStream);
}
@Override
public int hashCode() {
return printStream.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Listener.StreamWriting{" +
"printStream=" + printStream +
'}';
}
}
/**
* A listener that adds read-edges to any module of an instrumented class upon its transformation.
*/
class ModuleReadEdgeCompleting extends Listener.Adapter {
/**
* The instrumentation instance used for adding read edges.
*/
private final Instrumentation instrumentation;
/**
* {@code true} if the listener should also add a read-edge from the supplied modules to the instrumented type's module.
*/
private final boolean addTargetEdge;
/**
* The modules to add as a read edge to any transformed class's module.
*/
private final Set<? extends JavaModule> modules;
/**
* Creates a new module read-edge completing listener.
*
* @param instrumentation The instrumentation instance used for adding read edges.
* @param addTargetEdge {@code true} if the listener should also add a read-edge from the supplied modules
* to the instrumented type's module.
* @param modules The modules to add as a read edge to any transformed class's module.
*/
public ModuleReadEdgeCompleting(Instrumentation instrumentation, boolean addTargetEdge, Set<? extends JavaModule> modules) {
this.instrumentation = instrumentation;
this.addTargetEdge = addTargetEdge;
this.modules = modules;
}
/**
* Resolves a listener that adds module edges from and to the instrumented type's module.
*
* @param instrumentation The instrumentation instance used for adding read edges.
* @param addTargetEdge {@code true} if the listener should also add a read-edge from the supplied
* modules to the instrumented type's module.
* @param type The types for which to extract the modules.
* @return An appropriate listener.
*/
protected static Listener of(Instrumentation instrumentation, boolean addTargetEdge, Class<?>... type) {
Set<JavaModule> modules = new HashSet<JavaModule>();
for (Class<?> aType : type) {
JavaModule module = JavaModule.ofType(aType);
if (module.isNamed()) {
modules.add(module);
}
}
return modules.isEmpty()
? Listener.NoOp.INSTANCE
: new Listener.ModuleReadEdgeCompleting(instrumentation, addTargetEdge, modules);
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
if (module != null && module.isNamed()) {
for (JavaModule target : modules) {
if (!module.canRead(target)) {
module.addReads(instrumentation, target);
}
if (addTargetEdge && !target.canRead(module)) {
target.addReads(instrumentation, module);
}
}
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ModuleReadEdgeCompleting that = (ModuleReadEdgeCompleting) object;
return instrumentation.equals(that.instrumentation)
&& addTargetEdge == that.addTargetEdge
&& modules.equals(that.modules);
}
@Override
public int hashCode() {
int result = instrumentation.hashCode();
result = 31 * result + modules.hashCode();
result = 31 * result + (addTargetEdge ? 1 : 0);
return result;
}
@Override
public String toString() {
return "AgentBuilder.Listener.ModuleReadEdgeCompleting{" +
"instrumentation=" + instrumentation +
", addTargetEdge=" + addTargetEdge +
", modules=" + modules +
'}';
}
}
/**
* A compound listener that allows to group several listeners in one instance.
*/
class Compound implements Listener {
/**
* The listeners that are represented by this compound listener in their application order.
*/
private final List<? extends Listener> listeners;
/**
* Creates a new compound listener.
*
* @param listener The listeners to apply in their application order.
*/
public Compound(Listener... listener) {
this(Arrays.asList(listener));
}
/**
* Creates a new compound listener.
*
* @param listeners The listeners to apply in their application order.
*/
public Compound(List<? extends Listener> listeners) {
this.listeners = listeners;
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
for (Listener listener : listeners) {
listener.onTransformation(typeDescription, classLoader, module, dynamicType);
}
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
for (Listener listener : listeners) {
listener.onIgnored(typeDescription, classLoader, module);
}
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable) {
for (Listener listener : listeners) {
listener.onError(typeName, classLoader, module, throwable);
}
}
@Override
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module) {
for (Listener listener : listeners) {
listener.onComplete(typeName, classLoader, module);
}
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& listeners.equals(((Compound) other).listeners);
}
@Override
public int hashCode() {
return listeners.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Listener.Compound{" +
"listeners=" + listeners +
'}';
}
}
}
/**
* An initialization strategy which determines the handling of {@link net.bytebuddy.implementation.LoadedTypeInitializer}s
* and the loading of auxiliary types.
*/
interface InitializationStrategy {
/**
* Creates a new dispatcher for injecting this initialization strategy during a transformation process.
*
* @return The dispatcher to be used.
*/
Dispatcher dispatcher();
/**
* A dispatcher for changing a class file to adapt a self-initialization strategy.
*/
interface Dispatcher {
/**
* Transforms the instrumented type to implement an appropriate initialization strategy.
*
* @param builder The builder which should implement the initialization strategy.
* @return The given {@code builder} with the initialization strategy applied.
*/
DynamicType.Builder<?> apply(DynamicType.Builder<?> builder);
/**
* Registers a dynamic type for initialization and/or begins the initialization process.
*
* @param dynamicType The dynamic type that is created.
* @param classLoader The class loader of the dynamic type.
* @param injectorFactory The injector factory
*/
void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory);
/**
* A factory for creating a {@link ClassInjector} only if it is required.
*/
interface InjectorFactory {
/**
* Resolves the class injector for this factory.
*
* @return The class injector for this factory.
*/
ClassInjector resolve();
}
}
/**
* A non-initializing initialization strategy.
*/
enum NoOp implements InitializationStrategy, Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Dispatcher dispatcher() {
return this;
}
@Override
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder;
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
/* do nothing */
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.NoOp." + name();
}
}
/**
* An initialization strategy that adds a code block to an instrumented type's type initializer which
* then calls a specific class that is responsible for the explicit initialization.
*/
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE", justification = "Avoiding synchronization without security concerns")
enum SelfInjection implements InitializationStrategy {
/**
* A form of self-injection where auxiliary types that are annotated by
* {@link net.bytebuddy.implementation.auxiliary.AuxiliaryType.SignatureRelevant} of the instrumented type are loaded lazily and
* any other auxiliary type is loaded eagerly.
*/
SPLIT {
@Override
public InitializationStrategy.Dispatcher dispatcher() {
return new SelfInjection.Dispatcher.Split(new Random().nextInt());
}
},
/**
* A form of self-injection where any auxiliary type is loaded lazily.
*/
LAZY {
@Override
public InitializationStrategy.Dispatcher dispatcher() {
return new SelfInjection.Dispatcher.Lazy(new Random().nextInt());
}
},
/**
* A form of self-injection where any auxiliary type is loaded eagerly.
*/
EAGER {
@Override
public InitializationStrategy.Dispatcher dispatcher() {
return new SelfInjection.Dispatcher.Eager(new Random().nextInt());
}
};
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection." + name();
}
/**
* A dispatcher for a self-initialization strategy.
*/
protected abstract static class Dispatcher implements InitializationStrategy.Dispatcher {
/**
* A random identification for the applied self-initialization.
*/
protected final int identification;
/**
* Creates a new dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(int identification) {
this.identification = identification;
}
@Override
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder.initializer(NexusAccessor.INSTANCE.identifiedBy(identification));
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& identification == ((Dispatcher) other).identification;
}
@Override
public int hashCode() {
return identification;
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#SPLIT} strategy.
*/
protected static class Split extends Dispatcher {
/**
* Creates a new split dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Split(int identification) {
super(identification);
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
LoadedTypeInitializer loadedTypeInitializer;
if (!auxiliaryTypes.isEmpty()) {
TypeDescription instrumentedType = dynamicType.getTypeDescription();
ClassInjector classInjector = injectorFactory.resolve();
Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
Map<TypeDescription, byte[]> dependentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) {
(auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class)
? dependentTypes
: independentTypes).remove(auxiliaryType);
}
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
if (!independentTypes.isEmpty()) {
for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
Map<TypeDescription, LoadedTypeInitializer> lazyInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>(loadedTypeInitializers);
loadedTypeInitializers.keySet().removeAll(independentTypes.keySet());
loadedTypeInitializer = lazyInitializers.size() > 1 // there exist auxiliary types that need lazy loading
? new InjectingInitializer(instrumentedType, dependentTypes, lazyInitializers, classInjector)
: lazyInitializers.get(instrumentedType);
} else {
loadedTypeInitializer = dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription());
}
if (loadedTypeInitializer.isAlive()) {
NexusAccessor.INSTANCE.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.Split{identification=" + identification + "}";
}
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#LAZY} strategy.
*/
protected static class Lazy extends Dispatcher {
/**
* Creates a new lazy dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Lazy(int identification) {
super(identification);
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
LoadedTypeInitializer loadedTypeInitializer = auxiliaryTypes.isEmpty()
? dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription())
: new InjectingInitializer(dynamicType.getTypeDescription(), auxiliaryTypes, dynamicType.getLoadedTypeInitializers(), injectorFactory.resolve());
if (loadedTypeInitializer.isAlive()) {
NexusAccessor.INSTANCE.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.Lazy{identification=" + identification + "}";
}
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#EAGER} strategy.
*/
protected static class Eager extends Dispatcher {
/**
* Creates a new eager dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Eager(int identification) {
super(identification);
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
if (!auxiliaryTypes.isEmpty()) {
for (Map.Entry<TypeDescription, Class<?>> entry : injectorFactory.resolve().inject(auxiliaryTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
LoadedTypeInitializer loadedTypeInitializer = loadedTypeInitializers.get(dynamicType.getTypeDescription());
if (loadedTypeInitializer.isAlive()) {
NexusAccessor.INSTANCE.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.Eager{identification=" + identification + "}";
}
}
/**
* A type initializer that injects all auxiliary types of the instrumented type.
*/
protected static class InjectingInitializer implements LoadedTypeInitializer {
/**
* The instrumented type.
*/
private final TypeDescription instrumentedType;
/**
* The auxiliary types mapped to their class file representation.
*/
private final Map<TypeDescription, byte[]> rawAuxiliaryTypes;
/**
* The instrumented types and auxiliary types mapped to their loaded type initializers.
* The instrumented types and auxiliary types mapped to their loaded type initializers.
*/
private final Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers;
/**
* The class injector to use.
*/
private final ClassInjector classInjector;
/**
* Creates a new injection initializer.
*
* @param instrumentedType The instrumented type.
* @param rawAuxiliaryTypes The auxiliary types mapped to their class file representation.
* @param loadedTypeInitializers The instrumented types and auxiliary types mapped to their loaded type initializers.
* @param classInjector The class injector to use.
*/
protected InjectingInitializer(TypeDescription instrumentedType,
Map<TypeDescription, byte[]> rawAuxiliaryTypes,
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers,
ClassInjector classInjector) {
this.instrumentedType = instrumentedType;
this.rawAuxiliaryTypes = rawAuxiliaryTypes;
this.loadedTypeInitializers = loadedTypeInitializers;
this.classInjector = classInjector;
}
@Override
public void onLoad(Class<?> type) {
for (Map.Entry<TypeDescription, Class<?>> auxiliary : classInjector.inject(rawAuxiliaryTypes).entrySet()) {
loadedTypeInitializers.get(auxiliary.getKey()).onLoad(auxiliary.getValue());
}
loadedTypeInitializers.get(instrumentedType).onLoad(type);
}
@Override
public boolean isAlive() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InjectingInitializer that = (InjectingInitializer) o;
return classInjector.equals(that.classInjector)
&& instrumentedType.equals(that.instrumentedType)
&& rawAuxiliaryTypes.equals(that.rawAuxiliaryTypes)
&& loadedTypeInitializers.equals(that.loadedTypeInitializers);
}
@Override
public int hashCode() {
int result = instrumentedType.hashCode();
result = 31 * result + rawAuxiliaryTypes.hashCode();
result = 31 * result + loadedTypeInitializers.hashCode();
result = 31 * result + classInjector.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.InjectingInitializer{" +
"instrumentedType=" + instrumentedType +
", rawAuxiliaryTypes=" + rawAuxiliaryTypes +
", loadedTypeInitializers=" + loadedTypeInitializers +
", classInjector=" + classInjector +
'}';
}
}
}
/**
* An accessor for making sure that the accessed {@link net.bytebuddy.agent.builder.Nexus} is the class that is loaded by the system class loader.
*/
protected enum NexusAccessor {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The dispatcher for registering type initializers in the {@link Nexus}.
*/
private final Dispatcher dispatcher;
/**
* The {@link ClassLoader#getSystemClassLoader()} method.
*/
private final MethodDescription.InDefinedShape getSystemClassLoader;
/**
* The {@link java.lang.ClassLoader#loadClass(String)} method.
*/
private final MethodDescription.InDefinedShape loadClass;
/**
* The {@link Integer#valueOf(int)} method.
*/
private final MethodDescription.InDefinedShape valueOf;
/**
* The {@link java.lang.Class#getDeclaredMethod(String, Class[])} method.
*/
private final MethodDescription getDeclaredMethod;
/**
* The {@link java.lang.reflect.Method#invoke(Object, Object...)} method.
*/
private final MethodDescription invokeMethod;
/**
* Creates the singleton accessor.
*/
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Explicit delegation of the exception")
NexusAccessor() {
Dispatcher dispatcher;
try {
TypeDescription nexusType = new TypeDescription.ForLoadedType(Nexus.class);
dispatcher = new Dispatcher.Available(ClassInjector.UsingReflection.ofSystemClassLoader()
.inject(Collections.singletonMap(nexusType, ClassFileLocator.ForClassLoader.read(Nexus.class).resolve()))
.get(nexusType)
.getDeclaredMethod("register", String.class, ClassLoader.class, int.class, Object.class));
} catch (Exception exception) {
try {
dispatcher = new Dispatcher.Available(ClassLoader.getSystemClassLoader()
.loadClass(Nexus.class.getName())
.getDeclaredMethod("register", String.class, ClassLoader.class, int.class, Object.class));
} catch (Exception ignored) {
dispatcher = new Dispatcher.Unavailable(exception);
}
}
this.dispatcher = dispatcher;
getSystemClassLoader = new TypeDescription.ForLoadedType(ClassLoader.class).getDeclaredMethods()
.filter(named("getSystemClassLoader").and(takesArguments(0))).getOnly();
loadClass = new TypeDescription.ForLoadedType(ClassLoader.class).getDeclaredMethods()
.filter(named("loadClass").and(takesArguments(String.class))).getOnly();
getDeclaredMethod = new TypeDescription.ForLoadedType(Class.class).getDeclaredMethods()
.filter(named("getDeclaredMethod").and(takesArguments(String.class, Class[].class))).getOnly();
invokeMethod = new TypeDescription.ForLoadedType(Method.class).getDeclaredMethods()
.filter(named("invoke").and(takesArguments(Object.class, Object[].class))).getOnly();
valueOf = new TypeDescription.ForLoadedType(Integer.class).getDeclaredMethods()
.filter(named("valueOf").and(takesArguments(int.class))).getOnly();
}
/**
* Registers a type initializer with the class loader's nexus.
*
* @param name The name of a type for which a loaded type initializer is registered.
* @param classLoader The class loader for which a loaded type initializer is registered.
* @param identification An identification for the initializer to run.
* @param typeInitializer The loaded type initializer to be registered.
*/
public void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer) {
dispatcher.register(name, classLoader, identification, typeInitializer);
}
/**
* Creates a byte code appender for injecting a self-initializing type initializer block into the generated class.
*
* @param identification The identification of the initialization.
* @return An appropriate byte code appender.
*/
public ByteCodeAppender identifiedBy(int identification) {
return new InitializationAppender(identification);
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor." + name();
}
/**
* A dispatcher for registering type initializers in the {@link Nexus}.
*/
protected interface Dispatcher {
/**
* Registers a type initializer with the class loader's nexus.
*
* @param name The name of a type for which a loaded type initializer is registered.
* @param classLoader The class loader for which a loaded type initializer is registered.
* @param identification An identification for the initializer to run.
* @param typeInitializer The loaded type initializer to be registered.
*/
void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer);
/**
* An enabled dispatcher for registering a type initializer in a {@link Nexus}.
*/
class Available implements Dispatcher {
/**
* Indicates that a static method is invoked by reflection.
*/
private static final Object STATIC_METHOD = null;
/**
* The method for registering a type initializer in the system class loader's {@link Nexus}.
*/
private final Method registration;
/**
* Creates a new dispatcher.
*
* @param registration The method for registering a type initializer in the system class loader's {@link Nexus}.
*/
protected Available(Method registration) {
this.registration = registration;
}
@Override
public void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer) {
try {
registration.invoke(STATIC_METHOD, name, classLoader, identification, typeInitializer);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot register type initializer for " + name, exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Cannot register type initializer for " + name, exception.getCause());
}
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& registration.equals(((Available) other).registration);
}
@Override
public int hashCode() {
return registration.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor.Dispatcher.Available{" +
"registration=" + registration +
'}';
}
}
/**
* A disabled dispatcher where a {@link Nexus} is not available.
*/
class Unavailable implements Dispatcher {
/**
* The exception that was raised during the dispatcher initialization.
*/
private final Exception exception;
/**
* Creates a new disabled dispatcher.
*
* @param exception The exception that was raised during the dispatcher initialization.
*/
protected Unavailable(Exception exception) {
this.exception = exception;
}
@Override
public void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer) {
throw new IllegalStateException("Could not locate registration method", exception);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& exception.equals(((Unavailable) other).exception);
}
@Override
public int hashCode() {
return exception.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor.Dispatcher.Unavailable{" +
"exception=" + exception +
'}';
}
}
}
/**
* A byte code appender for invoking a Nexus for initializing the instrumented type.
*/
protected static class InitializationAppender implements ByteCodeAppender {
/**
* The identification for the self-initialization to execute.
*/
private final int identification;
/**
* Creates a new initialization appender.
*
* @param identification The identification for the self-initialization to execute.
*/
protected InitializationAppender(int identification) {
this.identification = identification;
}
@Override
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
return new ByteCodeAppender.Simple(new StackManipulation.Compound(
MethodInvocation.invoke(NexusAccessor.INSTANCE.getSystemClassLoader),
new TextConstant(Nexus.class.getName()),
MethodInvocation.invoke(NexusAccessor.INSTANCE.loadClass),
new TextConstant("initialize"),
ArrayFactory.forType(new TypeDescription.Generic.OfNonGenericType.ForLoadedType(Class.class))
.withValues(Arrays.asList(
ClassConstant.of(TypeDescription.CLASS),
ClassConstant.of(new TypeDescription.ForLoadedType(int.class)))),
MethodInvocation.invoke(NexusAccessor.INSTANCE.getDeclaredMethod),
NullConstant.INSTANCE,
ArrayFactory.forType(TypeDescription.Generic.OBJECT)
.withValues(Arrays.asList(
ClassConstant.of(instrumentedMethod.getDeclaringType().asErasure()),
new StackManipulation.Compound(
IntegerConstant.forValue(identification),
MethodInvocation.invoke(INSTANCE.valueOf)))),
MethodInvocation.invoke(NexusAccessor.INSTANCE.invokeMethod),
Removal.SINGLE
)).apply(methodVisitor, implementationContext, instrumentedMethod);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
InitializationAppender that = (InitializationAppender) other;
return identification == that.identification;
}
@Override
public int hashCode() {
return identification;
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor.InitializationAppender{" +
"identification=" + identification +
'}';
}
}
}
}
/**
* An initialization strategy that loads auxiliary types before loading the instrumented type. This strategy skips all types
* that are a subtype of the instrumented type which would cause a premature loading of the instrumented type and abort
* the instrumentation process.
*/
enum Minimal implements InitializationStrategy, Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Dispatcher dispatcher() {
return this;
}
@Override
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder;
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) {
if (!auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class)) {
independentTypes.remove(auxiliaryType);
}
}
if (!independentTypes.isEmpty()) {
ClassInjector classInjector = injectorFactory.resolve();
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.Minimal." + name();
}
}
}
/**
* A description strategy is responsible for resolving a {@link TypeDescription} when transforming or retransforming/-defining a type.
*/
interface DescriptionStrategy {
/**
* Describes the given type.
*
* @param typeName The binary name of the type to describe.
* @param typeBeingRedefined The type that is being redefined, if a redefinition is applied or {@code null} if no redefined type is available.
* @param typePool The type pool to use for locating a type if required.
* @return An appropriate type description.
*/
TypeDescription apply(String typeName, Class<?> typeBeingRedefined, TypePool typePool);
/**
* Describes the given type.
*
* @param type The loaded type to be described.
* @param typeLocator The type locator to use.
* @param locationStrategy The location strategy to use.
* @return An appropriate type description.
*/
TypeDescription apply(Class<?> type, TypeLocator typeLocator, LocationStrategy locationStrategy);
/**
* Default implementations of a {@link DescriptionStrategy}.
*/
enum Default implements DescriptionStrategy {
/**
* A description type strategy represents a type as a {@link net.bytebuddy.description.type.TypeDescription.ForLoadedType} if a
* retransformation or redefinition is applied on a type. Using a loaded type typically results in better performance as no
* I/O is required for resolving type descriptions. However, any interaction with the type is carried out via the Java reflection
* API. Using the reflection API triggers eager loading of any type that is part of a method or field signature. If any of these
* types are missing from the class path, this eager loading will cause a {@link NoClassDefFoundError}. Some Java code declares
* optional dependencies to other classes which are only realized if the optional dependency is present. Such code relies on the
* Java reflection API not being used for types using optional dependencies.
*/
HYBRID {
@Override
public TypeDescription apply(String typeName, Class<?> typeBeingRedefined, TypePool typePool) {
return typeBeingRedefined == null
? typePool.describe(typeName).resolve()
: new TypeDescription.ForLoadedType(typeBeingRedefined);
}
@Override
public TypeDescription apply(Class<?> type, TypeLocator typeLocator, LocationStrategy locationStrategy) {
return new TypeDescription.ForLoadedType(type);
}
},
/**
* <p>
* A description strategy that always describes Java types using a {@link TypePool}. This requires that any type - even if it is already
* loaded and a {@link Class} instance is available - is processed as a non-loaded type description. Doing so can cause overhead as processing
* loaded types is supported very efficiently by a JVM.
* </p>
* <p>
* Avoiding the usage of loaded types can improve robustness as this approach does not rely on the Java reflection API which triggers eager
* validation of this loaded type which can fail an application if optional types are used by any types field or method signatures. Also, it
* is possible to guarantee debugging meta data to be available also for retransformed or redefined types if a {@link TypeStrategy} specifies
* the extraction of such meta data.
* </p>
*/
POOL_ONLY {
@Override
public TypeDescription apply(String typeName, Class<?> typeBeingRedefined, TypePool typePool) {
return typePool.describe(typeName).resolve();
}
@Override
public TypeDescription apply(Class<?> type, TypeLocator typeLocator, LocationStrategy locationStrategy) {
return apply(TypeDescription.ForLoadedType.getName(type), type, typeLocator.typePool(locationStrategy.classFileLocator(type.getClassLoader(), JavaModule.ofType(type)), type.getClassLoader()));
}
};
@Override
public String toString() {
return "AgentBuilder.DescriptionStrategy.Default." + name();
}
}
}
/**
* An installation strategy determines the reaction to a raised exception after the registration of a {@link ClassFileTransformer}.
*/
interface InstallationStrategy {
/**
* Handles an error that occured after registering a class file transformer during installation.
*
* @param instrumentation The instrumentation onto which the class file transformer was registered.
* @param classFileTransformer The class file transformer that was registered.
* @param throwable The error that occurred.
* @return The class file transformer to return when an error occurred.
*/
ClassFileTransformer onError(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, Throwable throwable);
/**
* Default implementations of installation strategies.
*/
enum Default implements InstallationStrategy {
/**
* An installation strategy that unregisters the transformer and propagates the exception. Using this strategy does not guarantee
* that the registered transformer was not applied to any class, nor does it attempt to revert previous transformations. It only
* guarantees that the class file transformer is unregistered and does no longer apply after this method returns.
*/
ESCALATING {
@Override
public ClassFileTransformer onError(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, Throwable throwable) {
instrumentation.removeTransformer(classFileTransformer);
throw new IllegalStateException("Could not install class file transformer", throwable);
}
},
/**
* An installation strategy that retains the class file transformer and suppresses the error.
*/
SUPPRESSING {
@Override
public ClassFileTransformer onError(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, Throwable throwable) {
return classFileTransformer;
}
};
@Override
public String toString() {
return "AgentBuilder.InstallationStrategy.Default." + name();
}
}
}
/**
* A strategy for creating a {@link ClassFileLocator} when instrumenting a type.
*/
interface LocationStrategy {
/**
* Creates a class file locator for a given class loader and module combination.
*
* @param classLoader The class loader that is loading an instrumented type. Might be {@code null} to represent the bootstrap class loader.
* @param module The type's module or {@code null} if Java modules are not supported on the current VM.
* @return The class file locator to use.
*/
ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module);
/**
* A location strategy that locates class files by querying an instrumented type's {@link ClassLoader}.
*/
enum ForClassLoader implements LocationStrategy {
/**
* A location strategy that keeps a strong reference to the class loader the created class file locator represents.
*/
STRONG {
@Override
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.ForClassLoader.of(classLoader);
}
},
/**
* A location strategy that keeps a weak reference to the class loader the created class file locator represents.
* As a consequence, any returned class file locator stops working once the represented class loader is garbage collected.
*/
WEAK {
@Override
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.ForClassLoader.WeaklyReferenced.of(classLoader);
}
};
@Override
public String toString() {
return "AgentBuilder.LocationStrategy.ForClassLoader." + name();
}
}
}
/**
* A redefinition strategy regulates how already loaded classes are modified by a built agent.
*/
enum RedefinitionStrategy {
/**
* Disables redefinition such that already loaded classes are not affected by the agent.
*/
DISABLED {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
return false;
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
throw new IllegalStateException("A disabled redefinition strategy cannot create a collector");
}
},
/**
* <p>
* Applies a <b>redefinition</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is <b>not</b>
* registered for applying retransformations.
* </p>
* <p>
* Using this strategy, a redefinition is applied as a single transformation request. This means that a single illegal
* redefinition of a class causes the entire redefinition attempt to fail.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
REDEFINITION {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
if (!instrumentation.isRedefineClassesSupported()) {
throw new IllegalArgumentException("Cannot redefine classes: " + instrumentation);
}
return false;
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
return new Collector.ForRedefinition.Cumulative(transformation);
}
},
/**
* <p>
* Applies a <b>redefinition</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is <b>not</b>
* registered for applying retransformations.
* </p>
* <p>
* Using this strategy, a redefinition is applied in single class chunks. This means that a single illegal
* redefinition of a class does not cause the failure of any other redefinition. Chunking the redefinition does
* however imply a performance penalty. If at least one redefinition has failed, applying this strategy still causes an
* exception to be thrown as a result of the application.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
REDEFINITION_CHUNKED {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
return REDEFINITION.isRetransforming(instrumentation);
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
return new Collector.ForRedefinition.Chunked(transformation);
}
},
/**
* <p>
* Applies a <b>retransformation</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is registered
* for applying retransformations.
* </p>
* <p>
* Using this strategy, a retransformation is applied as a single transformation request. This means that a single illegal
* retransformation of a class causes the entire retransformation attempt to fail.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
RETRANSFORMATION {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
if (!instrumentation.isRetransformClassesSupported()) {
throw new IllegalArgumentException("Cannot retransform classes: " + instrumentation);
}
return true;
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
return new Collector.ForRetransformation.Cumulative(transformation);
}
},
/**
* <p>
* Applies a <b>retransformation</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is registered
* for applying retransformations.
* </p>
* <p>
* Using this strategy, a retransformation is applied in single class chunks. This means that a single illegal
* retransformation of a class does not cause the failure of any other redefinition. Chunking the retransformation does
* however imply a performance penalty. If at least one retransformation has failed, applying this strategy still causes an
* exception to be thrown as a result of the application.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
RETRANSFORMATION_CHUNKED {
@Override
protected boolean isRetransforming(Instrumentation instrumentation) {
return RETRANSFORMATION.isRetransforming(instrumentation);
}
@Override
protected Collector makeCollector(Default.Transformation transformation) {
return new Collector.ForRetransformation.Chunked(transformation);
}
};
/**
* Indicates if this strategy requires a class file transformer to be registered with a hint to apply the
* transformer for retransformation.
*
* @param instrumentation The instrumentation instance used.
* @return {@code true} if a class file transformer must be registered with a hint for retransformation.
*/
protected abstract boolean isRetransforming(Instrumentation instrumentation);
/**
* Indicates that this redefinition strategy applies a modification of already loaded classes.
*
* @return {@code true} if this redefinition strategy applies a modification of already loaded classes.
*/
protected boolean isEnabled() {
return this != DISABLED;
}
/**
* Creates a collector instance that is responsible for collecting loaded classes for potential retransformation.
*
* @param transformation The transformation that is registered for the agent.
* @return A new collector for collecting already loaded classes for transformation.
*/
protected abstract Collector makeCollector(Default.Transformation transformation);
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy." + name();
}
/**
* A collector is responsible for collecting classes that are to be considered for modification.
*/
protected interface Collector {
/**
* Considers a loaded class for modification.
*
* @param typeDescription The type description of the type that is to be considered.
* @param type The loaded representation of the type that is to be considered.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @return {@code true} if the class is considered to be redefined.
*/
boolean consider(TypeDescription typeDescription, Class<?> type, RawMatcher ignoredTypeMatcher);
/**
* Applies this collector.
*
* @param instrumentation The instrumentation instance to apply the transformation for.
* @param typeLocator The type locator to use.
* @param locationStrategy The location strategy to use.
* @param listener the listener to notify.
* @throws UnmodifiableClassException If a class is not modifiable.
* @throws ClassNotFoundException If a class could not be found.
*/
void apply(Instrumentation instrumentation,
TypeLocator typeLocator,
LocationStrategy locationStrategy,
Listener listener) throws UnmodifiableClassException, ClassNotFoundException;
/**
* A collector that applies a <b>redefinition</b> of already loaded classes.
*/
abstract class ForRedefinition implements Collector {
/**
* The transformation of the built agent.
*/
protected final Default.Transformation transformation;
/**
* A list of already collected redefinitions.
*/
protected final List<Entry> entries;
/**
* Creates a new collector for a redefinition.
*
* @param transformation The transformation of the built agent.
*/
protected ForRedefinition(Default.Transformation transformation) {
this.transformation = transformation;
entries = new ArrayList<Entry>();
}
@Override
public boolean consider(TypeDescription typeDescription, Class<?> type, RawMatcher ignoredTypeMatcher) {
return transformation.resolve(typeDescription,
type.getClassLoader(),
JavaModule.ofType(type),
type,
type.getProtectionDomain(),
ignoredTypeMatcher).getSort().isAlive() && entries.add(new Entry(type));
}
@Override
public void apply(Instrumentation instrumentation,
TypeLocator typeLocator,
LocationStrategy locationStrategy,
Listener listener) throws UnmodifiableClassException, ClassNotFoundException {
List<ClassDefinition> classDefinitions = new ArrayList<ClassDefinition>(entries.size());
for (Entry entry : entries) {
try {
classDefinitions.add(entry.resolve(locationStrategy));
} catch (Throwable throwable) {
JavaModule module = JavaModule.ofType(entry.getType());
try {
listener.onError(TypeDescription.ForLoadedType.getName(entry.getType()), entry.getType().getClassLoader(), module, throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(entry.getType()), entry.getType().getClassLoader(), module);
}
}
}
doApply(instrumentation, classDefinitions);
}
/**
* Applies a redefinition.
*
* @param instrumentation The instrumentation instance to use.
* @param classDefinitions The class definitions to apply.
* @throws UnmodifiableClassException If a class is not modifiable.
* @throws ClassNotFoundException If a class could not be found.
*/
protected abstract void doApply(Instrumentation instrumentation, List<ClassDefinition> classDefinitions) throws UnmodifiableClassException, ClassNotFoundException;
/**
* A collector that applies a redefinition and applies all redefinitions as a single transformation request.
*/
protected static class Cumulative extends ForRedefinition {
/**
* Creates a new cumulative redefinition collector.
*
* @param transformation The transformation of the built agent.
*/
protected Cumulative(Default.Transformation transformation) {
super(transformation);
}
@Override
protected void doApply(Instrumentation instrumentation, List<ClassDefinition> classDefinitions) throws UnmodifiableClassException, ClassNotFoundException {
if (!classDefinitions.isEmpty()) {
instrumentation.redefineClasses(classDefinitions.toArray(new ClassDefinition[classDefinitions.size()]));
}
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRedefinition.Cumulative{" +
"transformation=" + transformation +
", entries=" + entries +
'}';
}
}
/**
* A collector that applies a redefinition and applies all redefinitions as a separate transformation request per class.
*/
protected static class Chunked extends ForRedefinition {
/**
* Creates a new chunked redefinition collector.
*
* @param transformation The transformation of the built agent.
*/
protected Chunked(Default.Transformation transformation) {
super(transformation);
}
@Override
protected void doApply(Instrumentation instrumentation, List<ClassDefinition> classDefinitions) throws UnmodifiableClassException, ClassNotFoundException {
Map<Class<?>, Exception> exceptions = new HashMap<Class<?>, Exception>();
for (ClassDefinition classDefinition : classDefinitions) {
try {
instrumentation.redefineClasses(classDefinition);
} catch (Exception exception) {
exceptions.put(classDefinition.getDefinitionClass(), exception);
}
}
if (!exceptions.isEmpty()) {
throw new IllegalStateException("Could not retransform at least one class: " + exceptions);
}
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRedefinition.Chunked{" +
"transformation=" + transformation +
", entries=" + entries +
'}';
}
}
/**
* An entry describing a type redefinition.
*/
protected static class Entry {
/**
* The type to be redefined.
*/
private final Class<?> type;
/**
* Creates a new entry for a given type.
*
* @param type The type to be redefined.
*/
protected Entry(Class<?> type) {
this.type = type;
}
/**
* Returns the type that is being redefined.
*
* @return The type that is being redefined.
*/
public Class<?> getType() {
return type;
}
/**
* Resolves the entry to a class definition.
*
* @param locationStrategy A strategy for creating a class file locator.
* @return A class definition representing the redefined class.
* @throws IOException If an IO exception occurs.
*/
protected ClassDefinition resolve(LocationStrategy locationStrategy) throws IOException {
return new ClassDefinition(type, locationStrategy.classFileLocator(type.getClassLoader(), JavaModule.ofType(type)).locate(TypeDescription.ForLoadedType.getName(type)).resolve());
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Entry entry = (Entry) other;
return type.equals(entry.type);
}
@Override
public int hashCode() {
return type.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRedefinition.Entry{" +
"type=" + type +
'}';
}
}
}
/**
* A collector that applies a <b>retransformation</b> of already loaded classes.
*/
abstract class ForRetransformation implements Collector {
/**
* The transformation defined by the built agent.
*/
protected final Default.Transformation transformation;
/**
* The types that were collected for retransformation.
*/
protected final List<Class<?>> types;
/**
* Creates a new collector for a retransformation.
*
* @param transformation The transformation defined by the built agent.
*/
protected ForRetransformation(Default.Transformation transformation) {
this.transformation = transformation;
types = new ArrayList<Class<?>>();
}
@Override
public boolean consider(TypeDescription typeDescription, Class<?> type, RawMatcher ignoredTypeMatcher) {
return transformation.resolve(typeDescription,
type.getClassLoader(),
JavaModule.ofType(type),
type,
type.getProtectionDomain(),
ignoredTypeMatcher).getSort().isAlive() && types.add(type);
}
/**
* A collector that applies a retransformation and applies all redefinitions as a single transformation request.
*/
protected static class Cumulative extends ForRetransformation {
/**
* Creates a new cumulative retransformation collector.
*
* @param transformation The transformation of the built agent.
*/
protected Cumulative(Default.Transformation transformation) {
super(transformation);
}
@Override
public void apply(Instrumentation instrumentation,
TypeLocator typeLocator,
LocationStrategy locationStrategy,
Listener listener) throws UnmodifiableClassException {
if (!types.isEmpty()) {
instrumentation.retransformClasses(types.toArray(new Class<?>[types.size()]));
}
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRetransformation.Cumulative{" +
"transformation=" + transformation +
", types=" + types +
'}';
}
}
/**
* A collector that applies a retransformation and applies all redefinitions as a chunked transformation request.
*/
protected static class Chunked extends ForRetransformation {
/**
* Creates a new chunked retransformation collector.
*
* @param transformation The transformation of the built agent.
*/
protected Chunked(Default.Transformation transformation) {
super(transformation);
}
@Override
public void apply(Instrumentation instrumentation,
TypeLocator typeLocator,
LocationStrategy locationStrategy,
Listener listener) throws UnmodifiableClassException {
Map<Class<?>, Exception> exceptions = new HashMap<Class<?>, Exception>();
for (Class<?> type : types) {
try {
instrumentation.retransformClasses(type);
} catch (Exception exception) {
exceptions.put(type, exception);
}
}
if (!exceptions.isEmpty()) {
throw new IllegalStateException("Could not retransform at least one class: " + exceptions);
}
}
@Override
public String toString() {
return "AgentBuilder.RedefinitionStrategy.Collector.ForRetransformation.Chunked{" +
"transformation=" + transformation +
", types=" + types +
'}';
}
}
}
}
}
/**
* Implements the instrumentation of the {@code LambdaMetafactory} if this feature is enabled.
*/
enum LambdaInstrumentationStrategy implements Callable<Class<?>> {
/**
* A strategy that enables instrumentation of the {@code LambdaMetafactory} if such a factory exists on the current VM.
* Classes representing lambda expressions that are created by Byte Buddy are fully compatible to those created by
* the JVM and can be serialized or deserialized to one another. The classes do however show a few differences:
* <ul>
* <li>Byte Buddy's classes are public with a public executing transformer. Doing so, it is not necessary to instantiate a
* non-capturing lambda expression by reflection. This is done because Byte Buddy is not necessarily capable
* of using reflection due to an active security manager.</li>
* <li>Byte Buddy's classes are not marked as synthetic as an agent builder does not instrument synthetic classes
* by default.</li>
* </ul>
*/
ENABLED {
@Override
protected void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
if (LambdaFactory.register(classFileTransformer, new LambdaInstanceFactory(byteBuddy), this)) {
Class<?> lambdaMetaFactory;
try {
lambdaMetaFactory = Class.forName("java.lang.invoke.LambdaMetafactory");
} catch (ClassNotFoundException ignored) {
return;
}
byteBuddy.with(Implementation.Context.Disabled.Factory.INSTANCE)
.redefine(lambdaMetaFactory)
.visit(new AsmVisitorWrapper.ForDeclaredMethods()
.method(named("metafactory"), MetaFactoryRedirection.INSTANCE)
.method(named("altMetafactory"), AlternativeMetaFactoryRedirection.INSTANCE))
.make()
.load(lambdaMetaFactory.getClassLoader(), ClassReloadingStrategy.of(instrumentation));
}
}
@Override
public Class<?> call() throws Exception {
TypeDescription lambdaFactory = new TypeDescription.ForLoadedType(LambdaFactory.class);
return ClassInjector.UsingReflection.ofSystemClassLoader()
.inject(Collections.singletonMap(lambdaFactory, ClassFileLocator.ForClassLoader.read(LambdaFactory.class).resolve()))
.get(lambdaFactory);
}
},
/**
* A strategy that does not instrument the {@code LambdaMetafactory}.
*/
DISABLED {
@Override
protected void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
/* do nothing */
}
@Override
public Class<?> call() throws Exception {
throw new IllegalStateException("Cannot inject LambdaFactory from disabled instrumentation strategy");
}
};
/**
* Indicates that an original implementation can be ignored when redefining a method.
*/
protected static final MethodVisitor IGNORE_ORIGINAL = null;
/**
* Releases the supplied class file transformer when it was built with {@link AgentBuilder#with(LambdaInstrumentationStrategy)} enabled.
* Subsequently, the class file transformer is no longer applied when a class that represents a lambda expression is created.
*
* @param classFileTransformer The class file transformer to release.
* @param instrumentation The instrumentation instance that is used to potentially rollback the instrumentation of the {@code LambdaMetafactory}.
*/
public static void release(ClassFileTransformer classFileTransformer, Instrumentation instrumentation) {
if (LambdaFactory.release(classFileTransformer)) {
try {
ClassReloadingStrategy.of(instrumentation).reset(Class.forName("java.lang.invoke.LambdaMetafactory"));
} catch (Exception exception) {
throw new IllegalStateException("Could not release lambda transformer", exception);
}
}
}
/**
* Returns an enabled lambda instrumentation strategy for {@code true}.
*
* @param enabled If lambda instrumentation should be enabled.
* @return {@code true} if the returned strategy should be enabled.
*/
public static LambdaInstrumentationStrategy of(boolean enabled) {
return enabled
? ENABLED
: DISABLED;
}
/**
* Applies a transformation to lambda instances if applicable.
*
* @param byteBuddy The Byte Buddy instance to use.
* @param instrumentation The instrumentation instance for applying a redefinition.
* @param classFileTransformer The class file transformer to apply.
*/
protected abstract void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer);
/**
* Indicates if this strategy enables instrumentation of the {@code LambdaMetafactory}.
*
* @return {@code true} if this strategy is enabled.
*/
public boolean isEnabled() {
return this == ENABLED;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy." + name();
}
/**
* A factory that creates instances that represent lambda expressions.
*/
protected static class LambdaInstanceFactory {
/**
* The name of a factory for a lambda expression.
*/
private static final String LAMBDA_FACTORY = "get$Lambda";
/**
* A prefix for a field that represents a property of a lambda expression.
*/
private static final String FIELD_PREFIX = "arg$";
/**
* The infix to use for naming classes that represent lambda expression. The additional prefix
* is necessary because the subsequent counter is not sufficient to keep names unique compared
* to the original factory.
*/
private static final String LAMBDA_TYPE_INFIX = "$$Lambda$ByteBuddy$";
/**
* A type-safe constant to express that a class is not already loaded when applying a class file transformer.
*/
private static final Class<?> NOT_PREVIOUSLY_DEFINED = null;
/**
* A counter for naming lambda expressions randomly.
*/
private static final AtomicInteger LAMBDA_NAME_COUNTER = new AtomicInteger();
/**
* The Byte Buddy instance to use for creating lambda objects.
*/
private final ByteBuddy byteBuddy;
/**
* Creates a new lambda instance factory.
*
* @param byteBuddy The Byte Buddy instance to use for creating lambda objects.
*/
protected LambdaInstanceFactory(ByteBuddy byteBuddy) {
this.byteBuddy = byteBuddy;
}
/**
* Applies this lambda meta factory.
*
* @param targetTypeLookup A lookup context representing the creating class of this lambda expression.
* @param lambdaMethodName The name of the lambda expression's represented method.
* @param factoryMethodType The type of the lambda expression's represented method.
* @param lambdaMethodType The type of the lambda expression's factory method.
* @param targetMethodHandle A handle representing the target of the lambda expression's method.
* @param specializedLambdaMethodType A specialization of the type of the lambda expression's represented method.
* @param serializable {@code true} if the lambda expression should be serializable.
* @param markerInterfaces A list of interfaces for the lambda expression to represent.
* @param additionalBridges A list of additional bridge methods to be implemented by the lambda expression.
* @param classFileTransformers A collection of class file transformers to apply when creating the class.
* @return A binary representation of the transformed class file.
*/
public byte[] make(Object targetTypeLookup,
String lambdaMethodName,
Object factoryMethodType,
Object lambdaMethodType,
Object targetMethodHandle,
Object specializedLambdaMethodType,
boolean serializable,
List<Class<?>> markerInterfaces,
List<?> additionalBridges,
Collection<? extends ClassFileTransformer> classFileTransformers) {
JavaConstant.MethodType factoryMethod = JavaConstant.MethodType.ofLoaded(factoryMethodType);
JavaConstant.MethodType lambdaMethod = JavaConstant.MethodType.ofLoaded(lambdaMethodType);
JavaConstant.MethodHandle targetMethod = JavaConstant.MethodHandle.ofLoaded(targetMethodHandle, targetTypeLookup);
JavaConstant.MethodType specializedLambdaMethod = JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType);
Class<?> targetType = JavaConstant.MethodHandle.lookupType(targetTypeLookup);
String lambdaClassName = targetType.getName() + LAMBDA_TYPE_INFIX + LAMBDA_NAME_COUNTER.incrementAndGet();
DynamicType.Builder<?> builder = byteBuddy
.subclass(factoryMethod.getReturnType(), ConstructorStrategy.Default.NO_CONSTRUCTORS)
.modifiers(TypeManifestation.FINAL, Visibility.PUBLIC)
.implement(markerInterfaces)
.name(lambdaClassName)
.defineConstructor(Visibility.PUBLIC)
.withParameters(factoryMethod.getParameterTypes())
.intercept(ConstructorImplementation.INSTANCE)
.method(named(lambdaMethodName)
.and(takesArguments(lambdaMethod.getParameterTypes()))
.and(returns(lambdaMethod.getReturnType())))
.intercept(new LambdaMethodImplementation(targetMethod, specializedLambdaMethod));
int index = 0;
for (TypeDescription capturedType : factoryMethod.getParameterTypes()) {
builder = builder.defineField(FIELD_PREFIX + ++index, capturedType, Visibility.PRIVATE, FieldManifestation.FINAL);
}
if (!factoryMethod.getParameterTypes().isEmpty()) {
builder = builder.defineMethod(LAMBDA_FACTORY, factoryMethod.getReturnType(), Visibility.PRIVATE, Ownership.STATIC)
.withParameters(factoryMethod.getParameterTypes())
.intercept(FactoryImplementation.INSTANCE);
}
if (serializable) {
if (!markerInterfaces.contains(Serializable.class)) {
builder = builder.implement(Serializable.class);
}
builder = builder.defineMethod("writeReplace", Object.class, Visibility.PRIVATE)
.intercept(new SerializationImplementation(new TypeDescription.ForLoadedType(targetType),
factoryMethod.getReturnType(),
lambdaMethodName,
lambdaMethod,
targetMethod,
JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType)));
} else if (factoryMethod.getReturnType().isAssignableTo(Serializable.class)) {
builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE)
.withParameters(ObjectInputStream.class)
.throwing(NotSerializableException.class)
.intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda"))
.defineMethod("writeObject", void.class, Visibility.PRIVATE)
.withParameters(ObjectOutputStream.class)
.throwing(NotSerializableException.class)
.intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda"));
}
for (Object additionalBridgeType : additionalBridges) {
JavaConstant.MethodType additionalBridge = JavaConstant.MethodType.ofLoaded(additionalBridgeType);
builder = builder.defineMethod(lambdaMethodName, additionalBridge.getReturnType(), MethodManifestation.BRIDGE, Visibility.PUBLIC)
.withParameters(additionalBridge.getParameterTypes())
.intercept(new BridgeMethodImplementation(lambdaMethodName, lambdaMethod));
}
byte[] classFile = builder.make().getBytes();
for (ClassFileTransformer classFileTransformer : classFileTransformers) {
try {
byte[] transformedClassFile = classFileTransformer.transform(targetType.getClassLoader(),
lambdaClassName.replace('.', '/'),
NOT_PREVIOUSLY_DEFINED,
targetType.getProtectionDomain(),
classFile);
classFile = transformedClassFile == null
? classFile
: transformedClassFile;
} catch (Throwable ignored) {
/* do nothing */
}
}
return classFile;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& byteBuddy.equals(((LambdaInstanceFactory) other).byteBuddy);
}
@Override
public int hashCode() {
return byteBuddy.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory{" +
"byteBuddy=" + byteBuddy +
'}';
}
/**
* Implements a lambda class's executing transformer.
*/
@SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "An enumeration does not serialize fields")
protected enum ConstructorImplementation implements Implementation {
/**
* The singleton instance.
*/
INSTANCE;
/**
* A reference to the {@link Object} class's default executing transformer.
*/
private final MethodDescription.InDefinedShape objectConstructor;
/**
* Creates a new executing transformer implementation.
*/
ConstructorImplementation() {
objectConstructor = TypeDescription.OBJECT.getDeclaredMethods().filter(isConstructor()).getOnly();
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.getInstrumentedType().getDeclaredFields());
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.ConstructorImplementation." + name();
}
/**
* An appender to implement the executing transformer.
*/
protected static class Appender implements ByteCodeAppender {
/**
* The fields that are declared by the instrumented type.
*/
private final List<FieldDescription.InDefinedShape> declaredFields;
/**
* Creates a new appender.
*
* @param declaredFields The fields that are declared by the instrumented type.
*/
protected Appender(List<FieldDescription.InDefinedShape> declaredFields) {
this.declaredFields = declaredFields;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
List<StackManipulation> fieldAssignments = new ArrayList<StackManipulation>(declaredFields.size() * 3);
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
fieldAssignments.add(MethodVariableAccess.REFERENCE.loadOffset(0));
fieldAssignments.add(MethodVariableAccess.of(parameterDescription.getType()).loadOffset(parameterDescription.getOffset()));
fieldAssignments.add(FieldAccess.forField(declaredFields.get(parameterDescription.getIndex())).putter());
}
return new Size(new StackManipulation.Compound(
MethodVariableAccess.REFERENCE.loadOffset(0),
MethodInvocation.invoke(INSTANCE.objectConstructor),
new StackManipulation.Compound(fieldAssignments),
MethodReturn.VOID
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& declaredFields.equals(((Appender) other).declaredFields);
}
@Override
public int hashCode() {
return declaredFields.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.ConstructorImplementation.Appender{" +
"declaredFields=" + declaredFields +
'}';
}
}
}
/**
* An implementation of a instance factory for a lambda expression's class.
*/
protected enum FactoryImplementation implements Implementation {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.getInstrumentedType());
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.FactoryImplementation." + name();
}
/**
* An appender for a lambda expression factory.
*/
protected static class Appender implements ByteCodeAppender {
/**
* The instrumented type.
*/
private final TypeDescription instrumentedType;
/**
* Creates a new appender.
*
* @param instrumentedType The instrumented type.
*/
protected Appender(TypeDescription instrumentedType) {
this.instrumentedType = instrumentedType;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
return new Size(new StackManipulation.Compound(
TypeCreation.of(instrumentedType),
Duplication.SINGLE,
MethodVariableAccess.allArgumentsOf(instrumentedMethod),
MethodInvocation.invoke(instrumentedType.getDeclaredMethods().filter(isConstructor()).getOnly()),
MethodReturn.REFERENCE
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& instrumentedType.equals(((Appender) other).instrumentedType);
}
@Override
public int hashCode() {
return instrumentedType.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.FactoryImplementation.Appender{" +
"instrumentedType=" + instrumentedType +
'}';
}
}
}
/**
* Implements a lambda expression's functional method.
*/
protected static class LambdaMethodImplementation implements Implementation {
/**
* The handle of the target method of the lambda expression.
*/
private final JavaConstant.MethodHandle targetMethod;
/**
* The specialized type of the lambda method.
*/
private final JavaConstant.MethodType specializedLambdaMethod;
/**
* Creates a implementation of a lambda expression's functional method.
*
* @param targetMethod The target method of the lambda expression.
* @param specializedLambdaMethod The specialized type of the lambda method.
*/
protected LambdaMethodImplementation(JavaConstant.MethodHandle targetMethod, JavaConstant.MethodType specializedLambdaMethod) {
this.targetMethod = targetMethod;
this.specializedLambdaMethod = specializedLambdaMethod;
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(targetMethod.getOwnerType()
.getDeclaredMethods()
.filter(named(targetMethod.getName())
.and(returns(targetMethod.getReturnType()))
.and(takesArguments(targetMethod.getParameterTypes())))
.getOnly(),
specializedLambdaMethod,
implementationTarget.getInstrumentedType().getDeclaredFields());
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
LambdaMethodImplementation that = (LambdaMethodImplementation) other;
return targetMethod.equals(that.targetMethod)
&& specializedLambdaMethod.equals(that.specializedLambdaMethod);
}
@Override
public int hashCode() {
int result = targetMethod.hashCode();
result = 31 * result + specializedLambdaMethod.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.LambdaMethodImplementation{" +
"targetMethod=" + targetMethod +
", specializedLambdaMethod=" + specializedLambdaMethod +
'}';
}
/**
* An appender for a lambda expression's functional method.
*/
protected static class Appender implements ByteCodeAppender {
/**
* The target method of the lambda expression.
*/
private final MethodDescription targetMethod;
/**
* The specialized type of the lambda method.
*/
private final JavaConstant.MethodType specializedLambdaMethod;
/**
* The instrumented type's declared fields.
*/
private final List<FieldDescription.InDefinedShape> declaredFields;
/**
* Creates an appender of a lambda expression's functional method.
*
* @param targetMethod The target method of the lambda expression.
* @param specializedLambdaMethod The specialized type of the lambda method.
* @param declaredFields The instrumented type's declared fields.
*/
protected Appender(MethodDescription targetMethod,
JavaConstant.MethodType specializedLambdaMethod,
List<FieldDescription.InDefinedShape> declaredFields) {
this.targetMethod = targetMethod;
this.specializedLambdaMethod = specializedLambdaMethod;
this.declaredFields = declaredFields;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
List<StackManipulation> fieldAccess = new ArrayList<StackManipulation>(declaredFields.size() * 2);
for (FieldDescription.InDefinedShape fieldDescription : declaredFields) {
fieldAccess.add(MethodVariableAccess.REFERENCE.loadOffset(0));
fieldAccess.add(FieldAccess.forField(fieldDescription).getter());
}
List<StackManipulation> parameterAccess = new ArrayList<StackManipulation>(instrumentedMethod.getParameters().size() * 2);
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
parameterAccess.add(MethodVariableAccess.of(parameterDescription.getType()).loadOffset(parameterDescription.getOffset()));
parameterAccess.add(Assigner.DEFAULT.assign(parameterDescription.getType(),
specializedLambdaMethod.getParameterTypes().get(parameterDescription.getIndex()).asGenericType(),
Assigner.Typing.DYNAMIC));
}
return new Size(new StackManipulation.Compound(
new StackManipulation.Compound(fieldAccess),
new StackManipulation.Compound(parameterAccess),
MethodInvocation.invoke(targetMethod),
MethodReturn.returning(targetMethod.getReturnType().asErasure())
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Appender appender = (Appender) other;
return targetMethod.equals(appender.targetMethod)
&& declaredFields.equals(appender.declaredFields)
&& specializedLambdaMethod.equals(appender.specializedLambdaMethod);
}
@Override
public int hashCode() {
int result = targetMethod.hashCode();
result = 31 * result + declaredFields.hashCode();
result = 31 * result + specializedLambdaMethod.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.LambdaMethodImplementation.Appender{" +
"targetMethod=" + targetMethod +
", specializedLambdaMethod=" + specializedLambdaMethod +
", declaredFields=" + declaredFields +
'}';
}
}
}
/**
* Implements the {@code writeReplace} method for serializable lambda expressions.
*/
protected static class SerializationImplementation implements Implementation {
/**
* The lambda expression's declaring type.
*/
private final TypeDescription targetType;
/**
* The lambda expression's functional type.
*/
private final TypeDescription lambdaType;
/**
* The lambda expression's functional method name.
*/
private final String lambdaMethodName;
/**
* The method type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType lambdaMethod;
/**
* A handle that references the lambda expressions invocation target.
*/
private final JavaConstant.MethodHandle targetMethod;
/**
* The specialized method type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType specializedMethod;
/**
* Creates a new implementation for a serializable's lambda expression's {@code writeReplace} method.
*
* @param targetType The lambda expression's declaring type.
* @param lambdaType The lambda expression's functional type.
* @param lambdaMethodName The lambda expression's functional method name.
* @param lambdaMethod The method type of the lambda expression's functional method.
* @param targetMethod A handle that references the lambda expressions invocation target.
* @param specializedMethod The specialized method type of the lambda expression's functional method.
*/
protected SerializationImplementation(TypeDescription targetType,
TypeDescription lambdaType,
String lambdaMethodName,
JavaConstant.MethodType lambdaMethod,
JavaConstant.MethodHandle targetMethod,
JavaConstant.MethodType specializedMethod) {
this.targetType = targetType;
this.lambdaType = lambdaType;
this.lambdaMethodName = lambdaMethodName;
this.lambdaMethod = lambdaMethod;
this.targetMethod = targetMethod;
this.specializedMethod = specializedMethod;
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
TypeDescription serializedLambda;
try {
serializedLambda = new TypeDescription.ForLoadedType(Class.forName("java.lang.invoke.SerializedLambda"));
} catch (ClassNotFoundException exception) {
throw new IllegalStateException("Cannot find class for lambda serialization", exception);
}
List<StackManipulation> lambdaArguments = new ArrayList<StackManipulation>(implementationTarget.getInstrumentedType().getDeclaredFields().size());
for (FieldDescription.InDefinedShape fieldDescription : implementationTarget.getInstrumentedType().getDeclaredFields()) {
lambdaArguments.add(new StackManipulation.Compound(MethodVariableAccess.REFERENCE.loadOffset(0),
FieldAccess.forField(fieldDescription).getter(),
Assigner.DEFAULT.assign(fieldDescription.getType(), TypeDescription.Generic.OBJECT, Assigner.Typing.STATIC)));
}
return new ByteCodeAppender.Simple(new StackManipulation.Compound(
TypeCreation.of(serializedLambda),
Duplication.SINGLE,
ClassConstant.of(targetType),
new TextConstant(lambdaType.getInternalName()),
new TextConstant(lambdaMethodName),
new TextConstant(lambdaMethod.getDescriptor()),
IntegerConstant.forValue(targetMethod.getHandleType().getIdentifier()),
new TextConstant(targetMethod.getOwnerType().getInternalName()),
new TextConstant(targetMethod.getName()),
new TextConstant(targetMethod.getDescriptor()),
new TextConstant(specializedMethod.getDescriptor()),
ArrayFactory.forType(TypeDescription.Generic.OBJECT).withValues(lambdaArguments),
MethodInvocation.invoke(serializedLambda.getDeclaredMethods().filter(isConstructor()).getOnly()),
MethodReturn.REFERENCE
));
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
SerializationImplementation that = (SerializationImplementation) other;
return targetType.equals(that.targetType)
&& lambdaType.equals(that.lambdaType)
&& lambdaMethodName.equals(that.lambdaMethodName)
&& lambdaMethod.equals(that.lambdaMethod)
&& targetMethod.equals(that.targetMethod)
&& specializedMethod.equals(that.specializedMethod);
}
@Override
public int hashCode() {
int result = targetType.hashCode();
result = 31 * result + lambdaType.hashCode();
result = 31 * result + lambdaMethodName.hashCode();
result = 31 * result + lambdaMethod.hashCode();
result = 31 * result + targetMethod.hashCode();
result = 31 * result + specializedMethod.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.SerializationImplementation{" +
"targetType=" + targetType +
", lambdaType=" + lambdaType +
", lambdaMethodName='" + lambdaMethodName + '\'' +
", lambdaMethod=" + lambdaMethod +
", targetMethod=" + targetMethod +
", specializedMethod=" + specializedMethod +
'}';
}
}
/**
* Implements an explicit bridge method for a lambda expression.
*/
protected static class BridgeMethodImplementation implements Implementation {
/**
* The name of the lambda expression's functional method.
*/
private final String lambdaMethodName;
/**
* The actual type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType lambdaMethod;
/**
* Creates a new bridge method implementation for a lambda expression.
*
* @param lambdaMethodName The name of the lambda expression's functional method.
* @param lambdaMethod The actual type of the lambda expression's functional method.
*/
protected BridgeMethodImplementation(String lambdaMethodName, JavaConstant.MethodType lambdaMethod) {
this.lambdaMethodName = lambdaMethodName;
this.lambdaMethod = lambdaMethod;
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.invokeSuper(new MethodDescription.SignatureToken(lambdaMethodName,
lambdaMethod.getReturnType(),
lambdaMethod.getParameterTypes())));
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
BridgeMethodImplementation that = (BridgeMethodImplementation) other;
return lambdaMethodName.equals(that.lambdaMethodName) && lambdaMethod.equals(that.lambdaMethod);
}
@Override
public int hashCode() {
int result = lambdaMethodName.hashCode();
result = 31 * result + lambdaMethod.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.BridgeMethodImplementation{" +
"lambdaMethodName='" + lambdaMethodName + '\'' +
", lambdaMethod=" + lambdaMethod +
'}';
}
/**
* An appender for implementing a bridge method for a lambda expression.
*/
protected static class Appender implements ByteCodeAppender {
/**
* The invocation of the bridge's target method.
*/
private final SpecialMethodInvocation bridgeTargetInvocation;
/**
* Creates a new appender for invoking a lambda expression's bridge method target.
*
* @param bridgeTargetInvocation The invocation of the bridge's target method.
*/
protected Appender(SpecialMethodInvocation bridgeTargetInvocation) {
this.bridgeTargetInvocation = bridgeTargetInvocation;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
return new Compound(new Simple(
MethodVariableAccess.allArgumentsOf(instrumentedMethod)
.asBridgeOf(bridgeTargetInvocation.getMethodDescription())
.prependThisReference(),
bridgeTargetInvocation,
bridgeTargetInvocation.getMethodDescription().getReturnType().asErasure().isAssignableTo(instrumentedMethod.getReturnType().asErasure())
? StackManipulation.Trivial.INSTANCE
: TypeCasting.to(instrumentedMethod.getReceiverType().asErasure()),
MethodReturn.returning(instrumentedMethod.getReturnType().asErasure())
)).apply(methodVisitor, implementationContext, instrumentedMethod);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& bridgeTargetInvocation.equals(((Appender) other).bridgeTargetInvocation);
}
@Override
public int hashCode() {
return bridgeTargetInvocation.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.BridgeMethodImplementation.Appender{" +
"bridgeTargetInvocation=" + bridgeTargetInvocation +
'}';
}
}
}
}
/**
* Implements the regular lambda meta factory. The implementation represents the following code:
* <blockquote><pre>
* public static CallSite metafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* MethodType samMethodType,
* MethodHandle implMethod,
* MethodType instantiatedMethodType) throws Exception {
* Unsafe unsafe = Unsafe.getUnsafe();
* {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(),
* (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make",
* Object.class,
* String.class,
* Object.class,
* Object.class,
* Object.class,
* Object.class,
* boolean.class,
* List.class,
* List.class).invoke(null,
* caller,
* invokedName,
* invokedType,
* samMethodType,
* implMethod,
* instantiatedMethodType,
* false,
* Collections.emptyList(),
* Collections.emptyList()),
* null);
* unsafe.ensureClassInitialized(lambdaClass);
* return invokedType.parameterCount() == 0
* ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance()))
* : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType));
* </pre></blockquote>
*/
protected enum MetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription.InDefinedShape methodDescription,
MethodVisitor methodVisitor,
ClassFileVersion classFileVersion,
int writerFlags,
int readerFlags) {
methodVisitor.visitCode();
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "sun/misc/Unsafe", "getUnsafe", "()Lsun/misc/Unsafe;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false);
methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false);
methodVisitor.visitLdcInsn("make");
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 4);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 5);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B");
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "ensureClassInitialized", "(Ljava/lang/Class;)V", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false);
Label conditionalDefault = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNE, conditionalDefault);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
Label conditionalAlternative = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, conditionalAlternative);
methodVisitor.visitLabel(conditionalDefault);
methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{"sun/misc/Unsafe", "java/lang/Class"}, 0, null);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitLdcInsn("get$Lambda");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
methodVisitor.visitLabel(conditionalAlternative);
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"});
methodVisitor.visitInsn(Opcodes.ARETURN);
methodVisitor.visitMaxs(8, 8);
methodVisitor.visitEnd();
return IGNORE_ORIGINAL;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.MetaFactoryRedirection." + name();
}
}
/**
* Implements the alternative lambda meta factory. The implementation represents the following code:
* <blockquote><pre>
* public static CallSite altMetafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* Object... args) throws Exception {
* int flags = (Integer) args[3];
* int argIndex = 4;
* {@code Class<?>[]} markerInterface;
* if ((flags {@code &} FLAG_MARKERS) != 0) {
* int markerCount = (Integer) args[argIndex++];
* markerInterface = new {@code Class<?>}[markerCount];
* System.arraycopy(args, argIndex, markerInterface, 0, markerCount);
* argIndex += markerCount;
* } else {
* markerInterface = new {@code Class<?>}[0];
* }
* MethodType[] additionalBridge;
* if ((flags {@code &} FLAG_BRIDGES) != 0) {
* int bridgeCount = (Integer) args[argIndex++];
* additionalBridge = new MethodType[bridgeCount];
* System.arraycopy(args, argIndex, additionalBridge, 0, bridgeCount);
* // argIndex += bridgeCount;
* } else {
* additionalBridge = new MethodType[0];
* }
* Unsafe unsafe = Unsafe.getUnsafe();
* {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(),
* (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make",
* Object.class,
* String.class,
* Object.class,
* Object.class,
* Object.class,
* Object.class,
* boolean.class,
* List.class,
* List.class).invoke(null,
* caller,
* invokedName,
* invokedType,
* args[0],
* args[1],
* args[2],
* (flags {@code &} FLAG_SERIALIZABLE) != 0,
* Arrays.asList(markerInterface),
* Arrays.asList(additionalBridge)),
* null);
* unsafe.ensureClassInitialized(lambdaClass);
* return invokedType.parameterCount() == 0
* ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance()))
* : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType));
* }
* </pre></blockquote>
*/
protected enum AlternativeMetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription.InDefinedShape methodDescription,
MethodVisitor methodVisitor,
ClassFileVersion classFileVersion,
int writerFlags,
int readerFlags) {
methodVisitor.visitCode();
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 4);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 5);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitInsn(Opcodes.IAND);
Label markerInterfaceLoop = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, markerInterfaceLoop);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitIincInsn(5, 1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitInsn(Opcodes.IADD);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 5);
Label markerInterfaceExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, markerInterfaceExit);
methodVisitor.visitLabel(markerInterfaceLoop);
methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{Opcodes.INTEGER, Opcodes.INTEGER}, 0, null);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitLabel(markerInterfaceExit);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/Class;"}, 0, null);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitInsn(Opcodes.IAND);
Label additionalBridgesLoop = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, additionalBridgesLoop);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitIincInsn(5, 1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 8);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 8);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 8);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false);
Label additionalBridgesExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, additionalBridgesExit);
methodVisitor.visitLabel(additionalBridgesLoop);
methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitLabel(additionalBridgesExit);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/invoke/MethodType;"}, 0, null);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "sun/misc/Unsafe", "getUnsafe", "()Lsun/misc/Unsafe;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false);
methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false);
methodVisitor.visitLdcInsn("make");
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.IAND);
Label callSiteConditional = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, callSiteConditional);
methodVisitor.visitInsn(Opcodes.ICONST_1);
Label callSiteAlternative = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteAlternative);
methodVisitor.visitLabel(callSiteConditional);
methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", "sun/misc/Unsafe"}, 7, new Object[]{"sun/misc/Unsafe", "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER});
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLabel(callSiteAlternative);
methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", "sun/misc/Unsafe"}, 8, new Object[]{"sun/misc/Unsafe", "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER});
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B");
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 9);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "ensureClassInitialized", "(Ljava/lang/Class;)V", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false);
Label callSiteJump = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNE, callSiteJump);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
Label callSiteExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteExit);
methodVisitor.visitLabel(callSiteJump);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"java/lang/Class"}, 0, null);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitLdcInsn("get$Lambda");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
methodVisitor.visitLabel(callSiteExit);
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"});
methodVisitor.visitInsn(Opcodes.ARETURN);
methodVisitor.visitMaxs(9, 10);
methodVisitor.visitEnd();
return IGNORE_ORIGINAL;
}
@Override
public String toString() {
return "AgentBuilder.LambdaInstrumentationStrategy.AlternativeMetaFactoryRedirection." + name();
}
}
}
/**
* <p>
* The default implementation of an {@link net.bytebuddy.agent.builder.AgentBuilder}.
* </p>
* <p>
* By default, Byte Buddy ignores any types loaded by the bootstrap class loader and
* any synthetic type. Self-injection and rebasing is enabled. In order to avoid class format changes, set
* {@link AgentBuilder#disableBootstrapInjection()}). All types are parsed without their debugging information ({@link TypeLocator.Default#FAST}).
* </p>
*/
class Default implements AgentBuilder {
/**
* The name of the Byte Buddy {@code net.bytebuddy.agent.Installer} class.
*/
private static final String INSTALLER_TYPE = "net.bytebuddy.agent.Installer";
/**
* The name of the {@code net.bytebuddy.agent.Installer} field containing an installed {@link Instrumentation}.
*/
private static final String INSTRUMENTATION_FIELD = "instrumentation";
/**
* Indicator for access to a static member via reflection to make the code more readable.
*/
private static final Object STATIC_FIELD = null;
/**
* The value that is to be returned from a {@link java.lang.instrument.ClassFileTransformer} to indicate
* that no class file transformation is to be applied.
*/
private static final byte[] NO_TRANSFORMATION = null;
/**
* The {@link net.bytebuddy.ByteBuddy} instance to be used.
*/
private final ByteBuddy byteBuddy;
/**
* The type locator to use.
*/
private final TypeLocator typeLocator;
/**
* The definition handler to use.
*/
private final TypeStrategy typeStrategy;
/**
* The location strategy to use.
*/
private final LocationStrategy locationStrategy;
/**
* The listener to notify on transformations.
*/
private final Listener listener;
/**
* The native method strategy to use.
*/
private final NativeMethodStrategy nativeMethodStrategy;
/**
* The access control context to use for loading classes.
*/
private final AccessControlContext accessControlContext;
/**
* The initialization strategy to use for creating classes.
*/
private final InitializationStrategy initializationStrategy;
/**
* The redefinition strategy to apply.
*/
private final RedefinitionStrategy redefinitionStrategy;
/**
* The injection strategy for injecting classes into the bootstrap class loader.
*/
private final BootstrapInjectionStrategy bootstrapInjectionStrategy;
/**
* A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the instrumentation
* of classes that represent lambda expressions.
*/
private final LambdaInstrumentationStrategy lambdaInstrumentationStrategy;
/**
* The description strategy for resolving type descriptions for types.
*/
private final DescriptionStrategy descriptionStrategy;
/**
* The installation strategy to use.
*/
private final InstallationStrategy installationStrategy;
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoredTypeMatcher;
/**
* The transformation object for handling type transformations.
*/
private final Transformation transformation;
/**
* Creates a new default agent builder that uses a default {@link net.bytebuddy.ByteBuddy} instance for creating classes.
*
* @see Default#Default(ByteBuddy)
*/
public Default() {
this(new ByteBuddy());
}
/**
* Creates a new agent builder with default settings. By default, Byte Buddy ignores any types loaded by the bootstrap class loader, any
* type within a {@code net.bytebuddy} package and any synthetic type. Self-injection and rebasing is enabled. In order to avoid class format
* changes, set {@link AgentBuilder#disableBootstrapInjection()}). All types are parsed without their debugging information
* ({@link TypeLocator.Default#FAST}).
*
* @param byteBuddy The Byte Buddy instance to be used.
*/
public Default(ByteBuddy byteBuddy) {
this(byteBuddy,
TypeLocator.Default.FAST,
TypeStrategy.Default.REBASE,
LocationStrategy.ForClassLoader.STRONG,
Listener.NoOp.INSTANCE,
NativeMethodStrategy.Disabled.INSTANCE,
AccessController.getContext(),
InitializationStrategy.SelfInjection.SPLIT,
RedefinitionStrategy.DISABLED,
BootstrapInjectionStrategy.Disabled.INSTANCE,
LambdaInstrumentationStrategy.DISABLED,
DescriptionStrategy.Default.HYBRID,
InstallationStrategy.Default.ESCALATING,
new RawMatcher.Disjunction(new RawMatcher.ForElementMatchers(any(), isBootstrapClassLoader(), any()), new RawMatcher.ForElementMatchers(nameStartsWith("net.bytebuddy.").<TypeDescription>or(isSynthetic()), any(), any())),
Transformation.Ignored.INSTANCE);
}
/**
* Creates a new default agent builder.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param typeLocator The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to notify on transformations.
* @param nativeMethodStrategy The native method strategy to apply.
* @param accessControlContext The access control context to use for loading classes.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param redefinitionStrategy The redefinition strategy to apply.
* @param bootstrapInjectionStrategy The injection strategy for injecting classes into the bootstrap class loader.
* @param lambdaInstrumentationStrategy A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the
* instrumentation of classes that represent lambda expressions.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param installationStrategy The installation strategy to use.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @param transformation The transformation object for handling type transformations.
*/
protected Default(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
RedefinitionStrategy redefinitionStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
InstallationStrategy installationStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation) {
this.byteBuddy = byteBuddy;
this.typeLocator = typeLocator;
this.typeStrategy = typeStrategy;
this.locationStrategy = locationStrategy;
this.listener = listener;
this.nativeMethodStrategy = nativeMethodStrategy;
this.accessControlContext = accessControlContext;
this.initializationStrategy = initializationStrategy;
this.redefinitionStrategy = redefinitionStrategy;
this.bootstrapInjectionStrategy = bootstrapInjectionStrategy;
this.lambdaInstrumentationStrategy = lambdaInstrumentationStrategy;
this.descriptionStrategy = descriptionStrategy;
this.installationStrategy = installationStrategy;
this.ignoredTypeMatcher = ignoredTypeMatcher;
this.transformation = transformation;
}
@Override
public AgentBuilder with(ByteBuddy byteBuddy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(Listener listener) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
new Listener.Compound(this.listener, listener),
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(TypeStrategy typeStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(TypeLocator typeLocator) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(LocationStrategy locationStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder enableNativeMethodPrefix(String prefix) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
NativeMethodStrategy.ForPrefix.of(prefix),
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder disableNativeMethodPrefix() {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
NativeMethodStrategy.Disabled.INSTANCE,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(AccessControlContext accessControlContext) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(RedefinitionStrategy redefinitionStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(InitializationStrategy initializationStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(DescriptionStrategy descriptionStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder with(InstallationStrategy installationStrategy) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder enableBootstrapInjection(Instrumentation instrumentation, File folder) {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
new BootstrapInjectionStrategy.Enabled(folder, instrumentation),
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder disableBootstrapInjection() {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
BootstrapInjectionStrategy.Disabled.INSTANCE,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder disableClassFormatChanges() {
return new Default(byteBuddy.with(Implementation.Context.Disabled.Factory.INSTANCE),
typeLocator,
TypeStrategy.Default.REDEFINE_DECLARED_ONLY,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
InitializationStrategy.NoOp.INSTANCE,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type) {
return JavaModule.isSupported()
? with(Listener.ModuleReadEdgeCompleting.of(instrumentation, false, type))
: this;
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module) {
return assureReadEdgeTo(instrumentation, Arrays.asList(module));
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return with(new Listener.ModuleReadEdgeCompleting(instrumentation, false, new HashSet<JavaModule>(modules)));
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type) {
return JavaModule.isSupported()
? with(Listener.ModuleReadEdgeCompleting.of(instrumentation, true, type))
: this;
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module) {
return assureReadEdgeFromAndTo(instrumentation, Arrays.asList(module));
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return with(new Listener.ModuleReadEdgeCompleting(instrumentation, true, new HashSet<JavaModule>(modules)));
}
@Override
public Identified.Narrowable type(RawMatcher matcher) {
return new Transforming(matcher, Transformer.NoOp.INSTANCE, false);
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher) {
return type(typeMatcher, any());
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return type(typeMatcher, classLoaderMatcher, any());
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return type(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, not(supportsModules()).or(moduleMatcher)));
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher) {
return ignore(typeMatcher, any());
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return ignore(typeMatcher, classLoaderMatcher, any());
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return ignore(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, not(supportsModules()).or(moduleMatcher)));
}
@Override
public Ignored ignore(RawMatcher rawMatcher) {
return new Ignoring(rawMatcher);
}
@Override
public ClassFileTransformer makeRaw() {
return ExecutingTransformer.FACTORY.make(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
bootstrapInjectionStrategy,
descriptionStrategy,
ignoredTypeMatcher, transformation);
}
@Override
public ClassFileTransformer installOn(Instrumentation instrumentation) {
ClassFileTransformer classFileTransformer = makeRaw();
instrumentation.addTransformer(classFileTransformer, redefinitionStrategy.isRetransforming(instrumentation));
try {
if (nativeMethodStrategy.isEnabled(instrumentation)) {
instrumentation.setNativeMethodPrefix(classFileTransformer, nativeMethodStrategy.getPrefix());
}
lambdaInstrumentationStrategy.apply(byteBuddy, instrumentation, classFileTransformer);
if (redefinitionStrategy.isEnabled()) {
RedefinitionStrategy.Collector collector = redefinitionStrategy.makeCollector(transformation);
for (Class<?> type : instrumentation.getAllLoadedClasses()) {
TypeDescription typeDescription = descriptionStrategy.apply(type, typeLocator, locationStrategy);
JavaModule module = JavaModule.ofType(type);
try {
if (!instrumentation.isModifiableClass(type) || !collector.consider(typeDescription, type, ignoredTypeMatcher)) {
try {
try {
listener.onIgnored(typeDescription, type.getClassLoader(), module);
} finally {
listener.onComplete(typeDescription.getName(), type.getClassLoader(), module);
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
}
} catch (Throwable throwable) {
try {
try {
listener.onError(typeDescription.getName(), type.getClassLoader(), module, throwable);
} finally {
listener.onComplete(typeDescription.getName(), type.getClassLoader(), module);
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
}
}
collector.apply(instrumentation, typeLocator, locationStrategy, listener);
}
return classFileTransformer;
} catch (Throwable throwable) {
return installationStrategy.onError(instrumentation, classFileTransformer, throwable);
}
}
@Override
public ClassFileTransformer installOnByteBuddyAgent() {
try {
Instrumentation instrumentation = (Instrumentation) ClassLoader.getSystemClassLoader()
.loadClass(INSTALLER_TYPE)
.getDeclaredField(INSTRUMENTATION_FIELD)
.get(STATIC_FIELD);
if (instrumentation == null) {
throw new IllegalStateException("The Byte Buddy agent is not installed");
}
return installOn(instrumentation);
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("The Byte Buddy agent is not installed or not accessible", exception);
}
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Default aDefault = (Default) other;
return typeLocator.equals(aDefault.typeLocator)
&& byteBuddy.equals(aDefault.byteBuddy)
&& listener.equals(aDefault.listener)
&& nativeMethodStrategy.equals(aDefault.nativeMethodStrategy)
&& typeStrategy.equals(aDefault.typeStrategy)
&& locationStrategy.equals(aDefault.locationStrategy)
&& accessControlContext.equals(aDefault.accessControlContext)
&& initializationStrategy == aDefault.initializationStrategy
&& redefinitionStrategy == aDefault.redefinitionStrategy
&& bootstrapInjectionStrategy.equals(aDefault.bootstrapInjectionStrategy)
&& lambdaInstrumentationStrategy.equals(aDefault.lambdaInstrumentationStrategy)
&& descriptionStrategy.equals(aDefault.descriptionStrategy)
&& installationStrategy.equals(aDefault.installationStrategy)
&& ignoredTypeMatcher.equals(aDefault.ignoredTypeMatcher)
&& transformation.equals(aDefault.transformation);
}
@Override
public int hashCode() {
int result = byteBuddy.hashCode();
result = 31 * result + typeLocator.hashCode();
result = 31 * result + listener.hashCode();
result = 31 * result + typeStrategy.hashCode();
result = 31 * result + locationStrategy.hashCode();
result = 31 * result + nativeMethodStrategy.hashCode();
result = 31 * result + accessControlContext.hashCode();
result = 31 * result + initializationStrategy.hashCode();
result = 31 * result + redefinitionStrategy.hashCode();
result = 31 * result + bootstrapInjectionStrategy.hashCode();
result = 31 * result + lambdaInstrumentationStrategy.hashCode();
result = 31 * result + descriptionStrategy.hashCode();
result = 31 * result + installationStrategy.hashCode();
result = 31 * result + ignoredTypeMatcher.hashCode();
result = 31 * result + transformation.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default{" +
"byteBuddy=" + byteBuddy +
", typeLocator=" + typeLocator +
", typeStrategy=" + typeStrategy +
", locationStrategy=" + locationStrategy +
", listener=" + listener +
", nativeMethodStrategy=" + nativeMethodStrategy +
", accessControlContext=" + accessControlContext +
", initializationStrategy=" + initializationStrategy +
", redefinitionStrategy=" + redefinitionStrategy +
", bootstrapInjectionStrategy=" + bootstrapInjectionStrategy +
", lambdaInstrumentationStrategy=" + lambdaInstrumentationStrategy +
", descriptionStrategy=" + descriptionStrategy +
", installationStrategy=" + installationStrategy +
", ignoredTypeMatcher=" + ignoredTypeMatcher +
", transformation=" + transformation +
'}';
}
/**
* An injection strategy for injecting classes into the bootstrap class loader.
*/
protected interface BootstrapInjectionStrategy {
/**
* Creates an injector for the bootstrap class loader.
*
* @param protectionDomain The protection domain to be used.
* @return A class injector for the bootstrap class loader.
*/
ClassInjector make(ProtectionDomain protectionDomain);
/**
* A disabled bootstrap injection strategy.
*/
enum Disabled implements BootstrapInjectionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ClassInjector make(ProtectionDomain protectionDomain) {
throw new IllegalStateException("Injecting classes into the bootstrap class loader was not enabled");
}
@Override
public String toString() {
return "AgentBuilder.Default.BootstrapInjectionStrategy.Disabled." + name();
}
}
/**
* An enabled bootstrap injection strategy.
*/
class Enabled implements BootstrapInjectionStrategy {
/**
* The folder in which jar files are to be saved.
*/
private final File folder;
/**
* The instrumentation to use for appending jar files.
*/
private final Instrumentation instrumentation;
/**
* Creates a new enabled bootstrap class loader injection strategy.
*
* @param folder The folder in which jar files are to be saved.
* @param instrumentation The instrumentation to use for appending jar files.
*/
public Enabled(File folder, Instrumentation instrumentation) {
this.folder = folder;
this.instrumentation = instrumentation;
}
@Override
public ClassInjector make(ProtectionDomain protectionDomain) {
return ClassInjector.UsingInstrumentation.of(folder, ClassInjector.UsingInstrumentation.Target.BOOTSTRAP, instrumentation);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Enabled enabled = (Enabled) other;
return folder.equals(enabled.folder) && instrumentation.equals(enabled.instrumentation);
}
@Override
public int hashCode() {
int result = folder.hashCode();
result = 31 * result + instrumentation.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.BootstrapInjectionStrategy.Enabled{" +
"folder=" + folder +
", instrumentation=" + instrumentation +
'}';
}
}
}
/**
* A strategy for determining if a native method name prefix should be used when rebasing methods.
*/
protected interface NativeMethodStrategy {
/**
* Determines if this strategy enables name prefixing for native methods.
*
* @param instrumentation The instrumentation used.
* @return {@code true} if this strategy indicates that a native method prefix should be used.
*/
boolean isEnabled(Instrumentation instrumentation);
/**
* Resolves the method name transformer for this strategy.
*
* @return A method name transformer for this strategy.
*/
MethodNameTransformer resolve();
/**
* Returns the method prefix if the strategy is enabled. This method must only be called if this strategy enables prefixing.
*
* @return The method prefix.
*/
String getPrefix();
/**
* A native method strategy that suffixes method names with a random suffix and disables native method rebasement.
*/
enum Disabled implements NativeMethodStrategy {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public MethodNameTransformer resolve() {
return MethodNameTransformer.Suffixing.withRandomSuffix();
}
@Override
public boolean isEnabled(Instrumentation instrumentation) {
return false;
}
@Override
public String getPrefix() {
throw new IllegalStateException("A disabled native method strategy does not define a method name prefix");
}
@Override
public String toString() {
return "AgentBuilder.Default.NativeMethodStrategy.Disabled." + name();
}
}
/**
* A native method strategy that prefixes method names with a fixed value for supporting rebasing of native methods.
*/
class ForPrefix implements NativeMethodStrategy {
/**
* The method name prefix.
*/
private final String prefix;
/**
* Creates a new name prefixing native method strategy.
*
* @param prefix The method name prefix.
*/
protected ForPrefix(String prefix) {
this.prefix = prefix;
}
/**
* Creates a new native method strategy for prefixing method names.
*
* @param prefix The method name prefix.
* @return An appropriate native method strategy.
*/
protected static NativeMethodStrategy of(String prefix) {
if (prefix.length() == 0) {
throw new IllegalArgumentException("A method name prefix must not be the empty string");
}
return new ForPrefix(prefix);
}
@Override
public MethodNameTransformer resolve() {
return new MethodNameTransformer.Prefixing(prefix);
}
@Override
public boolean isEnabled(Instrumentation instrumentation) {
if (!instrumentation.isNativeMethodPrefixSupported()) {
throw new IllegalArgumentException("A prefix for native methods is not supported: " + instrumentation);
}
return true;
}
@Override
public String getPrefix() {
return prefix;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass()) && prefix.equals(((ForPrefix) other).prefix);
}
@Override
public int hashCode() {
return prefix.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Default.NativeMethodStrategy.ForPrefix{" +
"prefix='" + prefix + '\'' +
'}';
}
}
}
/**
* A transformation serves as a handler for modifying a class.
*/
protected interface Transformation {
/**
* Resolves an attempted transformation to a specific transformation.
*
* @param typeDescription A description of the type that is to be transformed.
* @param classLoader The class loader of the type being transformed.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param classBeingRedefined In case of a type redefinition, the loaded type being transformed or {@code null} if that is not the case.
* @param protectionDomain The protection domain of the type being transformed.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @return A resolution for the given type.
*/
Resolution resolve(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
RawMatcher ignoredTypeMatcher);
/**
* A resolution to a transformation.
*/
interface Resolution {
/**
* Returns the sort of this resolution.
*
* @return The sort of this resolution.
*/
Sort getSort();
/**
* Resolves this resolution as a decorator of the supplied resolution.
*
* @param resolution The resolution for which this resolution should serve as a decorator.
* @return A resolution where this resolution is applied as a decorator if this resolution is alive.
*/
Resolution asDecoratorOf(Resolution resolution);
/**
* Resolves this resolution as a decorator of the supplied resolution.
*
* @param resolution The resolution for which this resolution should serve as a decorator.
* @return A resolution where this resolution is applied as a decorator if this resolution is alive.
*/
Resolution prepend(Decoratable resolution);
/**
* Transforms a type or returns {@code null} if a type is not to be transformed.
*
* @param initializationStrategy The initialization strategy to use.
* @param classFileLocator The class file locator to use.
* @param typeStrategy The definition handler to use.
* @param byteBuddy The Byte Buddy instance to use.
* @param methodNameTransformer The method name transformer to be used.
* @param bootstrapInjectionStrategy The bootstrap injection strategy to be used.
* @param accessControlContext The access control context to be used.
* @param listener The listener to be invoked to inform about an applied or non-applied transformation.
* @return The class file of the transformed class or {@code null} if no transformation is attempted.
*/
byte[] apply(InitializationStrategy initializationStrategy,
ClassFileLocator classFileLocator,
TypeStrategy typeStrategy,
ByteBuddy byteBuddy,
NativeMethodStrategy methodNameTransformer,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
AccessControlContext accessControlContext,
Listener listener);
/**
* Describes a specific sort of a {@link Resolution}.
*/
enum Sort {
/**
* A terminal resolution. After discovering such a resolution, no further transformers are considered.
*/
TERMINAL(true),
/**
* A resolution that can serve as a decorator for another resolution. After discovering such a resolution
* further transformations are considered where the represented resolution is prepended if applicable.
*/
DECORATOR(true),
/**
* A non-resolved resolution.
*/
UNDEFINED(false);
/**
* Indicates if this sort represents an active resolution.
*/
private final boolean alive;
/**
* Creates a new resolution sort.
*
* @param alive Indicates if this sort represents an active resolution.
*/
Sort(boolean alive) {
this.alive = alive;
}
/**
* Returns {@code true} if this resolution is alive.
*
* @return {@code true} if this resolution is alive.
*/
protected boolean isAlive() {
return alive;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Resolution.Sort." + name();
}
}
/**
* A resolution that can be decorated by a transformer.
*/
interface Decoratable extends Resolution {
/**
* Appends the supplied transformer to this resolution.
*
* @param transformer The transformer to append to the transformer that is represented bz this instance.
* @return A new resolution with the supplied transformer appended to this transformer.
*/
Resolution append(Transformer transformer);
}
/**
* A canonical implementation of a non-resolved resolution.
*/
class Unresolved implements Resolution {
/**
* The type that is not transformed.
*/
private final TypeDescription typeDescription;
/**
* The unresolved type's class loader.
*/
private final ClassLoader classLoader;
/**
* The non-transformed type's module or {@code null} if the current VM does not support modules.
*/
private final JavaModule module;
/**
* Creates a new unresolved resolution.
*
* @param typeDescription The type that is not transformed.
* @param classLoader The unresolved type's class loader.
* @param module The non-transformed type's module or {@code null} if the current VM does not support modules.
*/
protected Unresolved(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
this.typeDescription = typeDescription;
this.classLoader = classLoader;
this.module = module;
}
@Override
public Sort getSort() {
return Sort.UNDEFINED;
}
@Override
public Resolution asDecoratorOf(Resolution resolution) {
return resolution;
}
@Override
public Resolution prepend(Decoratable resolution) {
return resolution;
}
@Override
public byte[] apply(InitializationStrategy initializationStrategy,
ClassFileLocator classFileLocator,
TypeStrategy typeStrategy,
ByteBuddy byteBuddy,
NativeMethodStrategy methodNameTransformer,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
AccessControlContext accessControlContext,
Listener listener) {
listener.onIgnored(typeDescription, classLoader, module);
return NO_TRANSFORMATION;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Unresolved that = (Unresolved) object;
return typeDescription.equals(that.typeDescription)
&& (classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null)
&& (module != null ? module.equals(that.module) : that.module == null);
}
@Override
public int hashCode() {
int result = typeDescription.hashCode();
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + (module != null ? module.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Resolution.Unresolved{" +
"typeDescription=" + typeDescription +
", classLoader=" + classLoader +
", module=" + module +
'}';
}
}
}
/**
* A transformation that does not attempt to transform any type.
*/
enum Ignored implements Transformation {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Resolution resolve(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
RawMatcher ignoredTypeMatcher) {
return new Resolution.Unresolved(typeDescription, classLoader, module);
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Ignored." + name();
}
}
/**
* A simple, active transformation.
*/
class Simple implements Transformation {
/**
* The raw matcher that is represented by this transformation.
*/
private final RawMatcher rawMatcher;
/**
* The transformer that is represented by this transformation.
*/
private final Transformer transformer;
/**
* {@code true} if this transformer serves as a decorator.
*/
private final boolean decorator;
/**
* Creates a new transformation.
*
* @param rawMatcher The raw matcher that is represented by this transformation.
* @param transformer The transformer that is represented by this transformation.
* @param decorator {@code true} if this transformer serves as a decorator.
*/
protected Simple(RawMatcher rawMatcher, Transformer transformer, boolean decorator) {
this.rawMatcher = rawMatcher;
this.transformer = transformer;
this.decorator = decorator;
}
@Override
public Transformation.Resolution resolve(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
RawMatcher ignoredTypeMatcher) {
return !ignoredTypeMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
&& rawMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
? new Resolution(typeDescription, classLoader, module, protectionDomain, transformer, decorator)
: new Transformation.Resolution.Unresolved(typeDescription, classLoader, module);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& decorator == ((Simple) other).decorator
&& rawMatcher.equals(((Simple) other).rawMatcher)
&& transformer.equals(((Simple) other).transformer);
}
@Override
public int hashCode() {
int result = rawMatcher.hashCode();
result = 31 * result + (decorator ? 1 : 0);
result = 31 * result + transformer.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Simple{" +
"rawMatcher=" + rawMatcher +
", transformer=" + transformer +
", decorator=" + decorator +
'}';
}
/**
* A resolution that performs a type transformation.
*/
protected static class Resolution implements Transformation.Resolution.Decoratable {
/**
* A description of the transformed type.
*/
private final TypeDescription typeDescription;
/**
* The class loader of the transformed type.
*/
private final ClassLoader classLoader;
/**
* The transformed type's module or {@code null} if the current VM does not support modules.
*/
private final JavaModule module;
/**
* The protection domain of the transformed type.
*/
private final ProtectionDomain protectionDomain;
/**
* The transformer to be applied.
*/
private final Transformer transformer;
/**
* {@code true} if this transformer serves as a decorator.
*/
private final boolean decorator;
/**
* Creates a new active transformation.
*
* @param typeDescription A description of the transformed type.
* @param classLoader The class loader of the transformed type.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param protectionDomain The protection domain of the transformed type.
* @param transformer The transformer to be applied.
* @param decorator {@code true} if this transformer serves as a decorator.
*/
protected Resolution(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain,
Transformer transformer,
boolean decorator) {
this.typeDescription = typeDescription;
this.classLoader = classLoader;
this.module = module;
this.protectionDomain = protectionDomain;
this.transformer = transformer;
this.decorator = decorator;
}
@Override
public Sort getSort() {
return decorator
? Sort.DECORATOR
: Sort.TERMINAL;
}
@Override
public Transformation.Resolution asDecoratorOf(Transformation.Resolution resolution) {
return resolution.prepend(this);
}
@Override
public Transformation.Resolution prepend(Decoratable resolution) {
return resolution.append(transformer);
}
@Override
public Transformation.Resolution append(Transformer transformer) {
return new Resolution(typeDescription,
classLoader,
module,
protectionDomain,
new Transformer.Compound(this.transformer, transformer),
decorator);
}
@Override
public byte[] apply(InitializationStrategy initializationStrategy,
ClassFileLocator classFileLocator,
TypeStrategy typeStrategy,
ByteBuddy byteBuddy,
NativeMethodStrategy methodNameTransformer,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
AccessControlContext accessControlContext,
Listener listener) {
InitializationStrategy.Dispatcher dispatcher = initializationStrategy.dispatcher();
DynamicType.Unloaded<?> dynamicType = dispatcher.apply(transformer.transform(typeStrategy.builder(typeDescription,
byteBuddy,
classFileLocator,
methodNameTransformer.resolve()), typeDescription, classLoader)).make();
dispatcher.register(dynamicType, classLoader, new BootstrapClassLoaderCapableInjectorFactory(bootstrapInjectionStrategy,
classLoader,
protectionDomain,
accessControlContext));
listener.onTransformation(typeDescription, classLoader, module, dynamicType);
return dynamicType.getBytes();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Resolution that = (Resolution) other;
return typeDescription.equals(that.typeDescription)
&& decorator == that.decorator
&& !(classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null)
&& !(module != null ? !module.equals(that.module) : that.module != null)
&& !(protectionDomain != null ? !protectionDomain.equals(that.protectionDomain) : that.protectionDomain != null)
&& transformer.equals(that.transformer);
}
@Override
public int hashCode() {
int result = typeDescription.hashCode();
result = 31 * result + (decorator ? 1 : 0);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + (module != null ? module.hashCode() : 0);
result = 31 * result + (protectionDomain != null ? protectionDomain.hashCode() : 0);
result = 31 * result + transformer.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Simple.Resolution{" +
"typeDescription=" + typeDescription +
", classLoader=" + classLoader +
", module=" + module +
", protectionDomain=" + protectionDomain +
", transformer=" + transformer +
", decorator=" + decorator +
'}';
}
/**
* An injector factory that resolves to a bootstrap class loader injection if this is necessary and enabled.
*/
protected static class BootstrapClassLoaderCapableInjectorFactory implements InitializationStrategy.Dispatcher.InjectorFactory {
/**
* The bootstrap injection strategy being used.
*/
private final BootstrapInjectionStrategy bootstrapInjectionStrategy;
/**
* The class loader for which to create an injection factory.
*/
private final ClassLoader classLoader;
/**
* The protection domain of the created classes.
*/
private final ProtectionDomain protectionDomain;
/**
* The access control context to be used.
*/
private final AccessControlContext accessControlContext;
/**
* Creates a new bootstrap class loader capable injector factory.
*
* @param bootstrapInjectionStrategy The bootstrap injection strategy being used.
* @param classLoader The class loader for which to create an injection factory.
* @param protectionDomain The protection domain of the created classes.
* @param accessControlContext The access control context to be used.
*/
protected BootstrapClassLoaderCapableInjectorFactory(BootstrapInjectionStrategy bootstrapInjectionStrategy,
ClassLoader classLoader,
ProtectionDomain protectionDomain,
AccessControlContext accessControlContext) {
this.bootstrapInjectionStrategy = bootstrapInjectionStrategy;
this.classLoader = classLoader;
this.protectionDomain = protectionDomain;
this.accessControlContext = accessControlContext;
}
@Override
public ClassInjector resolve() {
return classLoader == null
? bootstrapInjectionStrategy.make(protectionDomain)
: new ClassInjector.UsingReflection(classLoader, protectionDomain, accessControlContext);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
BootstrapClassLoaderCapableInjectorFactory that = (BootstrapClassLoaderCapableInjectorFactory) other;
return bootstrapInjectionStrategy.equals(that.bootstrapInjectionStrategy)
&& !(classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null)
&& !(protectionDomain != null ? !protectionDomain.equals(that.protectionDomain) : that.protectionDomain != null)
&& accessControlContext.equals(that.accessControlContext);
}
@Override
public int hashCode() {
int result = bootstrapInjectionStrategy.hashCode();
result = 31 * result + (protectionDomain != null ? protectionDomain.hashCode() : 0);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + accessControlContext.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Simple.Resolution.BootstrapClassLoaderCapableInjectorFactory{" +
"bootstrapInjectionStrategy=" + bootstrapInjectionStrategy +
", classLoader=" + classLoader +
", protectionDomain=" + protectionDomain +
", accessControlContext=" + accessControlContext +
'}';
}
}
}
}
/**
* A compound transformation that applied several transformation in the given order and applies the first active transformation.
*/
class Compound implements Transformation {
/**
* The list of transformations to apply in their application order.
*/
private final List<? extends Transformation> transformations;
/**
* Creates a new compound transformation.
*
* @param transformation An array of transformations to apply in their application order.
*/
protected Compound(Transformation... transformation) {
this(Arrays.asList(transformation));
}
/**
* Creates a new compound transformation.
*
* @param transformations A list of transformations to apply in their application order.
*/
protected Compound(List<? extends Transformation> transformations) {
this.transformations = transformations;
}
@Override
public Resolution resolve(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
RawMatcher ignoredTypeMatcher) {
Resolution current = new Resolution.Unresolved(typeDescription, classLoader, module);
for (Transformation transformation : transformations) {
Resolution resolution = transformation.resolve(typeDescription,
classLoader,
module,
classBeingRedefined,
protectionDomain,
ignoredTypeMatcher);
switch (resolution.getSort()) {
case TERMINAL:
return current.asDecoratorOf(resolution);
case DECORATOR:
current = current.asDecoratorOf(resolution);
break;
case UNDEFINED:
break;
default:
throw new IllegalStateException("Unexpected resolution type: " + resolution.getSort());
}
}
return current;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& transformations.equals(((Compound) other).transformations);
}
@Override
public int hashCode() {
return transformations.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Default.Transformation.Compound{" +
"transformations=" + transformations +
'}';
}
}
}
/**
* A {@link java.lang.instrument.ClassFileTransformer} that implements the enclosing agent builder's
* configuration.
*/
protected static class ExecutingTransformer implements ClassFileTransformer {
/**
* A factory for creating a {@link ClassFileTransformer} that supports the features of the current VM.
*/
protected static final Factory FACTORY;
/*
* Creates a factory for a class file transformer that supports the features of the current VM.
*/
static {
Factory factory;
try {
factory = new Factory.ForJava9CapableVm(new ByteBuddy()
.subclass(ExecutingTransformer.class)
.name(ExecutingTransformer.class.getName() + "$ByteBuddy$Java9Support")
.method(named("transform").and(takesArgument(0, JavaType.MODULE.load())))
.intercept(MethodCall.invoke(ExecutingTransformer.class.getDeclaredMethod("transform",
Object.class,
String.class,
Class.class,
ProtectionDomain.class,
byte[].class)).onSuper().withAllArguments())
.make()
.load(ExecutingTransformer.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.getDeclaredConstructor(ByteBuddy.class,
TypeLocator.class,
TypeStrategy.class,
LocationStrategy.class,
Listener.class,
NativeMethodStrategy.class,
AccessControlContext.class,
InitializationStrategy.class,
BootstrapInjectionStrategy.class,
DescriptionStrategy.class,
RawMatcher.class,
Transformation.class));
} catch (RuntimeException exception) {
throw exception;
} catch (Exception ignored) {
factory = Factory.ForLegacyVm.INSTANCE;
}
FACTORY = factory;
}
/**
* The Byte Buddy instance to be used.
*/
private final ByteBuddy byteBuddy;
/**
* The type locator to use.
*/
private final TypeLocator typeLocator;
/**
* The definition handler to use.
*/
private final TypeStrategy typeStrategy;
/**
* The listener to notify on transformations.
*/
private final Listener listener;
/**
* The native method strategy to apply.
*/
private final NativeMethodStrategy nativeMethodStrategy;
/**
* The access control context to use for loading classes.
*/
private final AccessControlContext accessControlContext;
/**
* The initialization strategy to use for transformed types.
*/
private final InitializationStrategy initializationStrategy;
/**
* The injection strategy for injecting classes into the bootstrap class loader.
*/
private final BootstrapInjectionStrategy bootstrapInjectionStrategy;
/**
* The description strategy for resolving type descriptions for types.
*/
private final DescriptionStrategy descriptionStrategy;
/**
* The location strategy to use.
*/
private final LocationStrategy locationStrategy;
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoredTypeMatcher;
/**
* The transformation object for handling type transformations.
*/
private final Transformation transformation;
/**
* Creates a new class file transformer.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param typeLocator The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to notify on transformations.
* @param nativeMethodStrategy The native method strategy to apply.
* @param accessControlContext The access control context to use for loading classes.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param bootstrapInjectionStrategy The injection strategy for injecting classes into the bootstrap class loader.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @param transformation The transformation object for handling type transformations.
*/
public ExecutingTransformer(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
DescriptionStrategy descriptionStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation) {
this.byteBuddy = byteBuddy;
this.typeLocator = typeLocator;
this.locationStrategy = locationStrategy;
this.typeStrategy = typeStrategy;
this.listener = listener;
this.nativeMethodStrategy = nativeMethodStrategy;
this.accessControlContext = accessControlContext;
this.initializationStrategy = initializationStrategy;
this.bootstrapInjectionStrategy = bootstrapInjectionStrategy;
this.descriptionStrategy = descriptionStrategy;
this.ignoredTypeMatcher = ignoredTypeMatcher;
this.transformation = transformation;
}
@Override
public byte[] transform(ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
return transform(JavaModule.UNSUPPORTED, classLoader, internalTypeName, classBeingRedefined, protectionDomain, binaryRepresentation);
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}.
*
* @param rawModule The instrumented class's Java {@code java.lang.reflect.Module}.
* @param internalTypeName The internal name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param protectionDomain The instrumented type's protection domain.
* @param binaryRepresentation The class file of the instrumented class in its current state.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
protected byte[] transform(Object rawModule,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
JavaModule module = JavaModule.of(rawModule);
return transform(module,
module.getClassLoader(accessControlContext),
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation);
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}.
*
* @param module The instrumented class's Java module in its wrapped form or {@code null} if the current VM does not support modules.
* @param classLoader The instrumented class's class loader.
* @param internalTypeName The internal name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param protectionDomain The instrumented type's protection domain.
* @param binaryRepresentation The class file of the instrumented class in its current state.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
private byte[] transform(JavaModule module,
ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
if (internalTypeName == null) {
return NO_TRANSFORMATION;
}
String binaryTypeName = internalTypeName.replace('/', '.');
try {
ClassFileLocator classFileLocator = ClassFileLocator.Simple.of(binaryTypeName,
binaryRepresentation,
locationStrategy.classFileLocator(classLoader, module));
TypePool typePool = typeLocator.typePool(classFileLocator, classLoader);
return transformation.resolve(descriptionStrategy.apply(binaryTypeName, classBeingRedefined, typePool),
classLoader,
module,
classBeingRedefined,
protectionDomain,
ignoredTypeMatcher).apply(initializationStrategy,
classFileLocator,
typeStrategy,
byteBuddy,
nativeMethodStrategy,
bootstrapInjectionStrategy,
accessControlContext,
listener);
} catch (Throwable throwable) {
listener.onError(binaryTypeName, classLoader, module, throwable);
return NO_TRANSFORMATION;
} finally {
listener.onComplete(binaryTypeName, classLoader, module);
}
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
ExecutingTransformer that = (ExecutingTransformer) other;
return byteBuddy.equals(that.byteBuddy)
&& typeLocator.equals(that.typeLocator)
&& typeStrategy.equals(that.typeStrategy)
&& locationStrategy.equals(that.locationStrategy)
&& initializationStrategy.equals(that.initializationStrategy)
&& listener.equals(that.listener)
&& nativeMethodStrategy.equals(that.nativeMethodStrategy)
&& bootstrapInjectionStrategy.equals(that.bootstrapInjectionStrategy)
&& descriptionStrategy.equals(that.descriptionStrategy)
&& accessControlContext.equals(that.accessControlContext)
&& ignoredTypeMatcher.equals(that.ignoredTypeMatcher)
&& transformation.equals(that.transformation);
}
@Override
public int hashCode() {
int result = byteBuddy.hashCode();
result = 31 * result + typeLocator.hashCode();
result = 31 * result + typeStrategy.hashCode();
result = 31 * result + locationStrategy.hashCode();
result = 31 * result + initializationStrategy.hashCode();
result = 31 * result + listener.hashCode();
result = 31 * result + nativeMethodStrategy.hashCode();
result = 31 * result + bootstrapInjectionStrategy.hashCode();
result = 31 * result + descriptionStrategy.hashCode();
result = 31 * result + accessControlContext.hashCode();
result = 31 * result + ignoredTypeMatcher.hashCode();
result = 31 * result + transformation.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.ExecutingTransformer{" +
"byteBuddy=" + byteBuddy +
", typeLocator=" + typeLocator +
", typeStrategy=" + typeStrategy +
", locationStrategy=" + locationStrategy +
", initializationStrategy=" + initializationStrategy +
", listener=" + listener +
", nativeMethodStrategy=" + nativeMethodStrategy +
", bootstrapInjectionStrategy=" + bootstrapInjectionStrategy +
", descriptionStrategy=" + descriptionStrategy +
", accessControlContext=" + accessControlContext +
", ignoredTypeMatcher=" + ignoredTypeMatcher +
", transformation=" + transformation +
'}';
}
/**
* A factory for creating a {@link ClassFileTransformer} for the current VM.
*/
protected interface Factory {
/**
* Creates a new class file transformer for the current VM.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param typeLocator The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to notify on transformations.
* @param nativeMethodStrategy The native method strategy to apply.
* @param accessControlContext The access control context to use for loading classes.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param bootstrapInjectionStrategy The injection strategy for injecting classes into the bootstrap class loader.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param ignoredTypeMatcher Identifies types that should not be instrumented.
* @param transformation The transformation object for handling type transformations.
* @return A class file transformer for the current VM that supports the API of the current VM.
*/
ClassFileTransformer make(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
DescriptionStrategy descriptionStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation);
/**
* A factory for a class file transformer on a JVM that supports the {@code java.lang.reflect.Module} API to override
* the newly added method of the {@link ClassFileTransformer} to capture an instrumented class's module.
*/
class ForJava9CapableVm implements Factory {
/**
* A constructor for creating a {@link ClassFileTransformer} that overrides the newly added method for extracting
* the {@code java.lang.reflect.Module} of an instrumented class.
*/
private final Constructor<? extends ClassFileTransformer> executingTransformer;
/**
* Creates a class file transformer factory for a Java 9 capable VM.
*
* @param executingTransformer A constructor for creating a {@link ClassFileTransformer} that overrides the newly added
* method for extracting the {@code java.lang.reflect.Module} of an instrumented class.
*/
protected ForJava9CapableVm(Constructor<? extends ClassFileTransformer> executingTransformer) {
this.executingTransformer = executingTransformer;
}
@Override
public ClassFileTransformer make(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
DescriptionStrategy descriptionStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation) {
try {
return executingTransformer.newInstance(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
bootstrapInjectionStrategy,
descriptionStrategy,
ignoredTypeMatcher,
transformation);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access " + executingTransformer, exception);
} catch (InstantiationException exception) {
throw new IllegalStateException("Cannot instantiate " + executingTransformer.getDeclaringClass(), exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Cannot invoke " + executingTransformer, exception.getCause());
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForJava9CapableVm that = (ForJava9CapableVm) object;
return executingTransformer.equals(that.executingTransformer);
}
@Override
public int hashCode() {
return executingTransformer.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Default.ExecutingTransformer.Factory.ForJava9CapableVm{" +
"executingTransformer=" + executingTransformer +
'}';
}
}
/**
* A factory for a {@link ClassFileTransformer} on a VM that does not support the {@code java.lang.reflect.Module} API.
*/
enum ForLegacyVm implements Factory {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ClassFileTransformer make(ByteBuddy byteBuddy,
TypeLocator typeLocator,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
Listener listener,
NativeMethodStrategy nativeMethodStrategy,
AccessControlContext accessControlContext,
InitializationStrategy initializationStrategy,
BootstrapInjectionStrategy bootstrapInjectionStrategy,
DescriptionStrategy descriptionStrategy,
RawMatcher ignoredTypeMatcher,
Transformation transformation) {
return new ExecutingTransformer(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
bootstrapInjectionStrategy,
descriptionStrategy,
ignoredTypeMatcher,
transformation);
}
@Override
public String toString() {
return "AgentBuilder.Default.ExecutingTransformer.Factory.ForLegacyVm." + name();
}
}
}
}
/**
* An abstract implementation of an agent builder that delegates all invocation to another instance.
*
* @param <T> The type that is produced by chaining a matcher.
*/
protected abstract class Delegator<T extends Matchable<T>> extends Matchable.AbstractBase<T> implements AgentBuilder {
/**
* Materializes the currently described {@link net.bytebuddy.agent.builder.AgentBuilder}.
*
* @return An agent builder that represents the currently described entry of this instance.
*/
protected abstract AgentBuilder materialize();
@Override
public AgentBuilder with(ByteBuddy byteBuddy) {
return materialize().with(byteBuddy);
}
@Override
public AgentBuilder with(Listener listener) {
return materialize().with(listener);
}
@Override
public AgentBuilder with(TypeStrategy typeStrategy) {
return materialize().with(typeStrategy);
}
@Override
public AgentBuilder with(TypeLocator typeLocator) {
return materialize().with(typeLocator);
}
@Override
public AgentBuilder with(LocationStrategy locationStrategy) {
return materialize().with(locationStrategy);
}
@Override
public AgentBuilder with(AccessControlContext accessControlContext) {
return materialize().with(accessControlContext);
}
@Override
public AgentBuilder with(InitializationStrategy initializationStrategy) {
return materialize().with(initializationStrategy);
}
@Override
public AgentBuilder with(RedefinitionStrategy redefinitionStrategy) {
return materialize().with(redefinitionStrategy);
}
@Override
public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) {
return materialize().with(lambdaInstrumentationStrategy);
}
@Override
public AgentBuilder with(DescriptionStrategy descriptionStrategy) {
return materialize().with(descriptionStrategy);
}
@Override
public AgentBuilder with(InstallationStrategy installationStrategy) {
return materialize().with(installationStrategy);
}
@Override
public AgentBuilder enableBootstrapInjection(Instrumentation instrumentation, File folder) {
return materialize().enableBootstrapInjection(instrumentation, folder);
}
@Override
public AgentBuilder disableBootstrapInjection() {
return materialize().disableBootstrapInjection();
}
@Override
public AgentBuilder enableNativeMethodPrefix(String prefix) {
return materialize().enableNativeMethodPrefix(prefix);
}
@Override
public AgentBuilder disableNativeMethodPrefix() {
return materialize().disableNativeMethodPrefix();
}
@Override
public AgentBuilder disableClassFormatChanges() {
return materialize().disableClassFormatChanges();
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type) {
return materialize().assureReadEdgeTo(instrumentation, type);
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module) {
return materialize().assureReadEdgeTo(instrumentation, module);
}
@Override
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return materialize().assureReadEdgeTo(instrumentation, modules);
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type) {
return materialize().assureReadEdgeFromAndTo(instrumentation, type);
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module) {
return materialize().assureReadEdgeFromAndTo(instrumentation, module);
}
@Override
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return materialize().assureReadEdgeFromAndTo(instrumentation, modules);
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher) {
return materialize().type(typeMatcher);
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return materialize().type(typeMatcher, classLoaderMatcher);
}
@Override
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return materialize().type(typeMatcher, classLoaderMatcher, moduleMatcher);
}
@Override
public Identified.Narrowable type(RawMatcher matcher) {
return materialize().type(matcher);
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> ignoredTypes) {
return materialize().ignore(ignoredTypes);
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> ignoredTypes, ElementMatcher<? super ClassLoader> ignoredClassLoaders) {
return materialize().ignore(ignoredTypes, ignoredClassLoaders);
}
@Override
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return materialize().ignore(typeMatcher, classLoaderMatcher, moduleMatcher);
}
@Override
public Ignored ignore(RawMatcher rawMatcher) {
return materialize().ignore(rawMatcher);
}
@Override
public ClassFileTransformer makeRaw() {
return materialize().makeRaw();
}
@Override
public ClassFileTransformer installOn(Instrumentation instrumentation) {
return materialize().installOn(instrumentation);
}
@Override
public ClassFileTransformer installOnByteBuddyAgent() {
return materialize().installOnByteBuddyAgent();
}
}
/**
* A delegator transformer for further precising what types to ignore.
*/
protected class Ignoring extends Delegator<Ignored> implements Ignored {
/**
* A matcher for identifying types that should not be instrumented.
*/
private final RawMatcher rawMatcher;
/**
* Creates a new agent builder for further specifying what types to ignore.
*
* @param rawMatcher A matcher for identifying types that should not be instrumented.
*/
protected Ignoring(RawMatcher rawMatcher) {
this.rawMatcher = rawMatcher;
}
@Override
protected AgentBuilder materialize() {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
rawMatcher,
transformation);
}
@Override
public Ignored and(RawMatcher rawMatcher) {
return new Ignoring(new RawMatcher.Conjunction(this.rawMatcher, rawMatcher));
}
@Override
public Ignored or(RawMatcher rawMatcher) {
return new Ignoring(new RawMatcher.Disjunction(this.rawMatcher, rawMatcher));
}
/**
* Returns the outer instance.
*
* @return The outer instance.
*/
private Default getOuter() {
return Default.this;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& rawMatcher.equals(((Ignoring) other).rawMatcher)
&& Default.this.equals(((Ignoring) other).getOuter());
}
@Override
public int hashCode() {
int result = rawMatcher.hashCode();
result = 31 * result + Default.this.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Ignoring{" +
"rawMatcher=" + rawMatcher +
", agentBuilder=" + Default.this +
'}';
}
}
/**
* A helper class that describes a {@link net.bytebuddy.agent.builder.AgentBuilder.Default} after supplying
* a {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} such that one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s can be supplied.
*/
protected class Transforming extends Delegator<Identified.Narrowable> implements Identified.Extendable, Identified.Narrowable {
/**
* The supplied raw matcher.
*/
private final RawMatcher rawMatcher;
/**
* The supplied transformer.
*/
private final Transformer transformer;
/**
* {@code true} if this transformer serves as a decorator.
*/
private final boolean decorator;
/**
* Creates a new matched default agent builder.
*
* @param rawMatcher The supplied raw matcher.
* @param transformer The supplied transformer.
* @param decorator {@code true} if this transformer serves as a decorator.
*/
protected Transforming(RawMatcher rawMatcher, Transformer transformer, boolean decorator) {
this.rawMatcher = rawMatcher;
this.transformer = transformer;
this.decorator = decorator;
}
@Override
protected AgentBuilder materialize() {
return new Default(byteBuddy,
typeLocator,
typeStrategy,
locationStrategy,
listener,
nativeMethodStrategy,
accessControlContext,
initializationStrategy,
redefinitionStrategy,
bootstrapInjectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
installationStrategy,
ignoredTypeMatcher,
new Transformation.Compound(new Transformation.Simple(rawMatcher, transformer, decorator), transformation));
}
@Override
public Identified.Extendable transform(Transformer transformer) {
return new Transforming(rawMatcher, new Transformer.Compound(this.transformer, transformer), decorator);
}
@Override
public AgentBuilder asDecorator() {
return new Transforming(rawMatcher, transformer, true);
}
@Override
public Narrowable and(RawMatcher rawMatcher) {
return new Transforming(new RawMatcher.Conjunction(this.rawMatcher, rawMatcher), transformer, decorator);
}
@Override
public Narrowable or(RawMatcher rawMatcher) {
return new Transforming(new RawMatcher.Disjunction(this.rawMatcher, rawMatcher), transformer, decorator);
}
/**
* Returns the outer instance.
*
* @return The outer instance.
*/
private Default getOuter() {
return Default.this;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& decorator == ((Transforming) other).decorator
&& rawMatcher.equals(((Transforming) other).rawMatcher)
&& transformer.equals(((Transforming) other).transformer)
&& Default.this.equals(((Transforming) other).getOuter());
}
@Override
public int hashCode() {
int result = rawMatcher.hashCode();
result = 31 * result + (decorator ? 1 : 0);
result = 31 * result + transformer.hashCode();
result = 31 * result + Default.this.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.Default.Transforming{" +
"rawMatcher=" + rawMatcher +
", transformer=" + transformer +
", decorator=" + decorator +
", agentBuilder=" + Default.this +
'}';
}
}
}
}
| Better name for executing transformer.
| byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java | Better name for executing transformer. | <ide><path>yte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java
<ide> try {
<ide> factory = new Factory.ForJava9CapableVm(new ByteBuddy()
<ide> .subclass(ExecutingTransformer.class)
<del> .name(ExecutingTransformer.class.getName() + "$ByteBuddy$Java9Support")
<add> .name(ExecutingTransformer.class.getName() + "$ByteBuddy$ModuleSupport")
<ide> .method(named("transform").and(takesArgument(0, JavaType.MODULE.load())))
<ide> .intercept(MethodCall.invoke(ExecutingTransformer.class.getDeclaredMethod("transform",
<ide> Object.class, |
|
JavaScript | mit | e5cdb6e8ef780598e0060b39c0e59695bd6e0c78 | 0 | anaoaktree/vcgen,anaoaktree/vcgen,anaoaktree/vcgen | function saveTextAsFile()
{
var textToWrite = codeEditor.getValue();
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs+".imp";
downloadLink.innerHTML = "Download File";
if (window.URL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
codeEditor.setValue(fileLoadedEvent.target.result);
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject ("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
return request;
};
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function getResultConds(){
//ajax request to get conditions
event.preventDefault();
var textToWrite = codeEditor.getValue();
xhr = createRequest();
xhr.open("POST", "/getconds/", true);
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert("done");
}
}
xhr.send(textToWrite);
}
window.onload = function(){
//checked jsperf.com for perfomance
document.getElementById("loadFileBtn").addEventListener("click", loadFileAsText);
document.getElementById("saveAsFileBtn").addEventListener("click", saveTextAsFile);
document.getElementById("getResult").addEventListener("click", getResultConds);
}; | textinterface/static/textinterface/js/script.js | function saveTextAsFile()
{
var textToWrite = codeEditor.getValue();
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs+".imp";
downloadLink.innerHTML = "Download File";
if (window.URL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
codeEditor.setValue(fileLoadedEvent.target.result);
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject ("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
return request;
};
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function getResultConds(){
//ajax request to get conditions
event.preventDefault();
var textToWrite = codeEditor.getValue();
xhr = createRequest();
xhr.open("POST", "/getconds/", true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert("done");
}
}
xhr.send(String(textToWrite));
}
window.onload = function(){
//checked jsperf.com for perfomance
document.getElementById("loadFileBtn").addEventListener("click", loadFileAsText);
document.getElementById("saveAsFileBtn").addEventListener("click", saveTextAsFile);
document.getElementById("getResult").addEventListener("click", getResultConds);
}; | request
| textinterface/static/textinterface/js/script.js | request | <ide><path>extinterface/static/textinterface/js/script.js
<ide>
<ide> xhr = createRequest();
<ide> xhr.open("POST", "/getconds/", true);
<del> xhr.setRequestHeader('Content-Type', 'text/plain');
<ide> xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
<ide> xhr.onreadystatechange = function() {
<ide> if (xhr.readyState == 4) {
<ide>
<ide> }
<ide> }
<del> xhr.send(String(textToWrite));
<add> xhr.send(textToWrite);
<ide> }
<ide>
<ide> window.onload = function(){ |
|
JavaScript | mit | e863bf0eaa2da122cd9f4bd91e58469fd6a6a3cf | 0 | rbelling/CleanStart,rbelling/CleanStart | var dest = "./build";
var src = './src';
var templateData = require('./data/template');
module.exports = {
browserSync: {
server: {
// Serve up our build folder
baseDir: dest
},
ghostMode: false
},
sprite: {
src: src,
dest: dest,
path: '/sprite/dew_green_can',
cssPath: src + "/sass/modules/sprite/",
cssName: './_green.scss',
destPath: src + "/images/modules/sprite-green"
},
sass: {
src: src + "/sass/",
sassFiles: src + "/sass/**/*.{sass,scss}",
dest: dest,
settings: {
indentedSyntax: true, // Enable .sass syntax!
imagePath: 'images' // Used by the image-url helper
}
},
images: {
src: src + "/images/**/*.{gif,jpg,png,svg,jpeg}",
dest: dest + "/images"
},
markup: {
src: src + "/htdocs/**",
dest: dest
},
app: {
breakpoints: {
small: 414,
medium: 1024,
large: 1600
}
},
criticalPath: {
// Inline the generated critical-path CSS
// - true generates HTML
// - false generates CSS
inline: true,
// Your base directory
base: dest,
// HTML source
html: '<html>...</html>',
// HTML source file
src: 'index.html',
// Your CSS Files (optional)
css: [dest+'/app.css'],
// Viewport width
width: 1600,
// Viewport height
height: 1024,
// Target for final HTML output.
// use some css file when the inline option is not set
dest: 'index-critical.html',
// Minify critical-path CSS when inlining
minify: true,
// Extract inlined styles from referenced stylesheets
// extract: true,
// Prefix for asset directory
// pathPrefix: '/MySubfolderDocrot',
// ignore css rules
// ignore: ['font-face',/some-regexp/],
// overwrite default options
ignoreOptions: {}
},
templates: {
baseFolder: src + "/templates/**/*",
src: src + "/templates/base/",
dest: src + "/htdocs/",
templateExtension: '.handlebars',
myPage: 'index', //'styleguide' //the entry point page: this file includes other templates
templateData: templateData,
templateOptions: {
//https://www.npmjs.com/package/gulp-compile-handlebars
ignorePartials: true, //ignores the unknown footer2 partial in the handlebars template, defaults to false
partials: {
footer: '<footer>the end</footer>'
},
batch: [src + '/templates/partials/'],
helpers: {
capitals: function(str) {
return str.toUpperCase();
}
}
}
},
browserify: {
// A separate bundle will be generated for each
// bundle config in the list below
bundleConfigs: [{
delay: 0,
entries: src + '/javascript/page.js',
dest: dest,
outputName: 'page.js',
// list of modules to make require-able externally
// require: ['npm-zepto', 'lodash'],
// list of externally available modules to exclude from the bundle
// external: ['underscore']
},{
delay: 0,
entries: src + '/javascript/critical.js',
dest: dest,
outputName: 'critical.js',
// list of modules to make require-able externally
// require: ['jquery'],
}]
},
production: {
cssSrc: dest + '/*.css',
jsSrc: dest + '/*.js',
dest: dest
},
jsprettify: {
jsFiles: src + '/**/*.{js,json}',
src: src,
dest: dest
},
tests: {
src: src + '/javascript/__tests__',
},
};
| gulp/config.js | var dest = "./build";
var src = './src';
var templateData = require('./data/template');
module.exports = {
browserSync: {
server: {
// Serve up our build folder
baseDir: dest
},
ghostMode: false
},
sprite: {
src: src,
dest: dest,
path: '/sprite/dew_green_can',
cssPath: src + "/sass/modules/sprite/",
cssName: './_green.scss',
destPath: src + "/images/modules/sprite-green"
},
sass: {
src: src + "/sass/",
sassFiles: src + "/sass/**/*.{sass,scss}",
dest: dest,
settings: {
indentedSyntax: true, // Enable .sass syntax!
imagePath: 'images' // Used by the image-url helper
}
},
images: {
src: src + "/images/**/*.{gif,jpg,png,svg,jpeg}",
dest: dest + "/images"
},
markup: {
src: src + "/htdocs/**",
dest: dest
},
app: {
breakpoints: {
small: 414,
medium: 1024,
large: 1600
}
},
criticalPath: {
// Inline the generated critical-path CSS
// - true generates HTML
// - false generates CSS
inline: true,
// Your base directory
base: dest,
// HTML source
html: '<html>...</html>',
// HTML source file
src: 'index.html',
// Your CSS Files (optional)
css: [dest+'/app.css'],
// Viewport width
width: 1600,
// Viewport height
height: 1024,
// Target for final HTML output.
// use some css file when the inline option is not set
dest: 'index-critical.html',
// Minify critical-path CSS when inlining
minify: true,
// Extract inlined styles from referenced stylesheets
// extract: true,
// Prefix for asset directory
// pathPrefix: '/MySubfolderDocrot',
// ignore css rules
// ignore: ['font-face',/some-regexp/],
// overwrite default options
ignoreOptions: {}
},
templates: {
baseFolder: src + "/templates/**/*",
src: src + "/templates/base/",
dest: src + "/htdocs/",
templateExtension: '.handlebars',
myPage: 'index', //'styleguide' //the entry point page: this file includes other templates
templateData: templateData,
templateOptions: {
//https://www.npmjs.com/package/gulp-compile-handlebars
ignorePartials: true, //ignores the unknown footer2 partial in the handlebars template, defaults to false
partials: {
footer: '<footer>the end</footer>'
},
batch: [src + '/templates/partials/'],
helpers: {
capitals: function(str) {
return str.toUpperCase();
}
}
}
},
browserify: {
// A separate bundle will be generated for each
// bundle config in the list below
bundleConfigs: [{
delay: 0,
entries: src + '/javascript/page.js',
dest: dest,
outputName: 'page.js',
// list of modules to make require-able externally
// require: ['npm-zepto', 'lodash'],
// list of externally available modules to exclude from the bundle
// external: ['underscore']
},{
delay: 0,
entries: src + '/javascript/critical.js',
dest: dest,
outputName: 'critical.js',
// list of modules to make require-able externally
// require: ['jquery'],
}]
},
production: {
cssSrc: dest + '/*.css',
jsSrc: dest + '/*.js',
dest: dest
},
jsprettify: {
jsFiles: src + '/**/*.{js,json}',
src: src,
dest: dest
},
tests: {
src: src + '/javascript/__tests__',
},
aws: {
url: {
staging: 'clash-achievery-staging.s3-website-us-east-1.amazonaws.com'
},
src: src,
dest: dest,
},
};
| removed aws
| gulp/config.js | removed aws | <ide><path>ulp/config.js
<ide> tests: {
<ide> src: src + '/javascript/__tests__',
<ide> },
<del> aws: {
<del> url: {
<del> staging: 'clash-achievery-staging.s3-website-us-east-1.amazonaws.com'
<del> },
<del> src: src,
<del> dest: dest,
<del> },
<ide>
<ide> }; |
|
JavaScript | mit | e161e10b905ee11c361ffc18093a35c80881161a | 0 | eb1/adapt-it-mobile,eb1/adapt-it-mobile,adapt-it/adapt-it-mobile,adapt-it/adapt-it-mobile,adapt-it/adapt-it-mobile,eb1/adapt-it-mobile | /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define(function (require) {
"use strict";
var $ = require('jquery'),
Underscore = require('underscore'),
Handlebars = require('handlebars'),
Backbone = require('backbone'),
Marionette = require('marionette'),
i18n = require('i18n'),
tplLoadingPleaseWait = require('text!tpl/LoadingPleaseWait.html'),
tplImportDoc = require('text!tpl/CopyOrImport.html'),
tplExportDoc = require('text!tpl/Export.html'),
tplExportFormat = require('text!tpl/ExportChooseFormat.html'),
projModel = require('app/models/project'),
bookModel = require('app/models/book'),
spModel = require('app/models/sourcephrase'),
chapModel = require('app/models/chapter'),
kbModels = require('app/models/targetunit'),
scrIDs = require('utils/scrIDs'),
USFM = require('utils/usfm'),
kblist = null, // populated in onShow
bookName = "",
scrID = "",
lines = [],
fileList = [],
fileCount = 0,
punctExp = "",
bookid = "",
puncts = [],
caseSource = [],
caseTarget = [],
deferreds = [],
MAX_BATCH = 10000, // maximum transaction size for SQLite
// (number can be tuned if needed - this is to avoid memory issues - see issue #138)
FileTypeEnum = {
TXT: 1,
USFM: 2,
USX: 3,
XML: 4
},
// Helper method to build an html list of documents in the AIM database.
// Used by ExportDocument.
buildDocumentList = function (pid) {
var str = "";
var i = 0;
var entries = window.Application.BookList.where({projectid: pid});
for (i = 0; i < entries.length; i++) {
str += "<li class='topcoat-list__item' id=" + entries[i].attributes.bookid + ">" + entries[i].attributes.name + "<span class='chevron'></span></li>";
}
return str;
},
// Helper method to store the specified source and target text in the KB.
saveInKB = function (sourceValue, targetValue, oldTargetValue, projectid) {
var elts = kblist.filter(function (element) {
return (element.attributes.projectid === projectid &&
element.attributes.source === sourceValue);
});
var tu = null,
curDate = new Date(),
timestamp = (curDate.getFullYear() + "-" + (curDate.getMonth() + 1) + "-" + curDate.getDay() + "T" + curDate.getUTCHours() + ":" + curDate.getUTCMinutes() + ":" + curDate.getUTCSeconds() + "z");
if (elts.length > 0) {
tu = elts[0];
}
if (tu) {
var i = 0,
found = false,
refstrings = tu.get('refstring');
// delete or decrement the old value
if (oldTargetValue.length > 0) {
// there was an old value -- try to find and remove the corresponding KB entry
for (i = 0; i < refstrings.length; i++) {
if (refstrings[i].target === oldTargetValue) {
if (refstrings[i].n !== '0') {
// more than one refcount -- decrement it
refstrings[i].n--;
}
break;
}
}
}
// add or increment the new value
for (i = 0; i < refstrings.length; i++) {
if (refstrings[i].target === targetValue) {
refstrings[i].n++;
found = true;
break;
}
}
if (found === false) {
// no entry in KB with this source/target -- add one
var newRS = {
'target': targetValue,
'n': '1'
};
refstrings.push(newRS);
}
// sort the refstrings collection on "n" (refcount)
refstrings.sort(function (a, b) {
// high to low
return parseInt(b.n, 10) - parseInt(a.n, 10);
});
// update the KB model
tu.set('refstring', refstrings, {silent: true});
tu.set('timestamp', timestamp, {silent: true});
tu.update();
} else {
// no entry in KB with this source -- add one
var newID = Underscore.uniqueId(),
newTU = new kbModels.TargetUnit({
tuid: newID,
projectid: projectid,
source: sourceValue,
refstring: [
{
target: targetValue,
n: "1"
}
],
timestamp: timestamp,
user: ""
});
kblist.add(newTU);
newTU.save();
}
},
// Helper method to import the selected file into the specified project.
// This method has sub-methods for text, usfm, usx and xml (Adapt It document) file types.
importFile = function (file, project) {
var status = "";
var reader = new FileReader();
var i = 0;
var name = "";
var doc = null;
var result = false;
var errMsg = "";
var sps = [];
// Callback for when the file is imported / saved successfully
var importSuccess = function () {
console.log("importSuccess()");
// update status
$("#status").html(i18n.t("view.dscStatusImportSuccess", {document: file.name}));
if ($("#loading").length) {
// mobile "please wait" UI
$("#loading").hide();
$("#waiting").hide();
$("#OK").show();
}
// display the OK button
$("#OK").removeAttr("disabled");
};
// Callback for when the file failed to import
var importFail = function (e) {
console.log("importFail(): " + e.message);
// update status
$("#status").html(i18n.t("view.dscCopyDocumentFailed", {document: file.name, reason: e.message}));
if ($("#loading").length) {
// mobile "please wait" UI
$("#loading").hide();
$("#waiting").hide();
$("#OK").show();
}
// display the OK button
$("#OK").removeAttr("disabled");
};
// callback method for when the FileReader has finished loading in the file
reader.onloadend = function (e) {
var value = "",
scrID = null,
bookName = "",
chap = 0,
verse = 0,
s = "",
t = "",
index = 0,
norder = 1,
markers = "",
orig = null,
prepuncts = "",
midpuncts = "",
follpuncts = "",
newSP = null,
punctIdx = 0,
chapter = null,
book = null,
books = window.Application.BookList,
chapters = window.Application.ChapterList,
sourcePhrases = new spModel.SourcePhraseCollection(),
arr = [],
bookID = "",
chapterID = "",
spID = "";
///
// FILE TYPE READERS
///
// Plain Text document
// We assume these are just text with no markup,
// in a single chapter (this could change if needed)
var readTextDoc = function (contents) {
var re = /\s+/;
var newline = new RegExp('[\n\r\f\u2028\u2029]+', 'g');
var prepunct = "";
var follpunct = "";
var needsNewLine = false;
var chaps = [];
var sp = null;
console.log("Reading text file:" + file.name);
index = 1;
bookName = file.name;
bookID = Underscore.uniqueId();
// Create the book and chapter
book = new bookModel.Book({
bookid: bookID,
projectid: project.get('projectid'),
name: bookName,
filename: file.name,
chapters: []
});
books.add(book);
// (for now, just one chapter -- eventually we could chunk this out based on file size)
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: bookName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// set the lastDocument / lastAdapted<xxx> values if not already set
if (project.get('lastDocument') === "") {
project.set('lastDocument', bookName);
}
if (project.get('lastAdaptedBookID') === 0) {
project.set('lastAdaptedBookID', bookID);
project.set('lastAdaptedChapterID', chapterID);
}
if (project.get('lastAdaptedName') === "") {
project.set('lastAdaptedName', bookName);
}
// parse the text file and create the SourcePhrases
arr = contents.replace(newline, " <p> ").split(re); // insert special <p> for linefeeds, then split on whitespace
// arr = contents.split(re);
i = 0;
while (i < arr.length) {
// check for a marker
if (arr[i].length === 0) {
// nothing in this token -- skip
i++;
} else if (arr[i] === "<p>") {
// newline -- make a note and keep going
markers = "\\p";
i++;
} else if (arr[i].length === 1 && puncts.indexOf(arr[i]) > -1) {
// punctuation token -- add to the prepuncts
prepuncts += arr[i];
i++;
} else {
// "normal" sourcephrase token
s = arr[i];
// look for leading and trailing punctuation
// leading...
if (puncts.indexOf(arr[i].charAt(0)) > -1) {
// leading punct
punctIdx = 0;
while (puncts.indexOf(arr[i].charAt(punctIdx)) > -1 && punctIdx < arr[i].length) {
prepuncts += arr[i].charAt(punctIdx);
punctIdx++;
}
// remove the punctuation from the "source" of the substring
s = s.substr(punctIdx);
}
if (s.length === 0) {
// it'a ALL punctuation -- jump to the next token
i++;
} else {
// not all punctuation -- check following punctuation, then create a sourcephrase
if (puncts.indexOf(s.charAt(s.length - 1)) > -1) {
// trailing punct
punctIdx = s.length - 1;
while (puncts.indexOf(s.charAt(punctIdx)) > -1 && punctIdx > 0) {
follpuncts += s.charAt(punctIdx);
punctIdx--;
}
// remove the punctuation from the "source" of the substring
s = s.substr(0, punctIdx + 1);
}
// Now create a new sourcephrase
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: prepuncts,
midpuncts: midpuncts,
follpuncts: follpuncts,
source: s,
target: ""
});
markers = "";
prepuncts = "";
follpuncts = "";
punctIdx = 0;
index++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
i++;
norder++;
}
}
}
// add any remaining sourcephrases
if ((sps.length % MAX_BATCH) > 0) {
$("#status").html(i18n.t("view.dscStatusSaving"));
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - (sps.length % MAX_BATCH))));
}
// track all those deferred calls to addBatch -- when they all complete, report the results to the user
$.when.apply($, deferreds).done(function (value) {
importSuccess();
}).fail(function (e) {
importFail(e);
});
// for non-scripture texts, there are no verses. Keep track of how far we are by using a
// negative value for the # of SourcePhrases in the text.
chapter.set('versecount', -(index), {silent: true});
chapter.save();
book.set('chapters', chaps, {silent: true});
book.save();
return true; // success
// END readTextDoc()
};
// Paratext USX document
// These are XML-flavored markup files exported from Paratext
var readUSXDoc = function (contents) {
var prepunct = "";
var follpunct = "";
var sp = null;
var re = /\s+/;
var chaps = [];
var xmlDoc = $.parseXML(contents);
var $xml = $(xmlDoc);
var chapterName = "";
// find the USFM ID of this book
var scrIDList = new scrIDs.ScrIDCollection();
var verseCount = 0;
var punctIdx = 0;
var lastAdapted = 0;
var firstChapterID = "";
var innerText = "";
var i = 0;
var tmpVal = null;
var closingMarker = "";
var parseNode = function (element) {
closingMarker = "";
// process the node itself
if ($(element)[0].nodeType === 1) {
switch ($(element)[0].tagName) {
case "book":
markers += "\\id " + element.attributes.item("code").nodeValue;
break;
case "chapter":
if (markers.length > 0) {
markers += " ";
}
markers += "\\c " + element.attributes.item("number").nodeValue;
if (element.attributes.item("number").nodeValue !== "1") {
// not the first chapter
// first, close out the previous chapter
chapter.set('versecount', verseCount, {silent: true});
chapter.save();
verseCount = 0; // reset for the next chapter
lastAdapted = 0; // reset for the next chapter
// now create the new chapter
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: element.attributes.item("number").nodeValue});
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
}
break;
case "verse":
verseCount++;
if (markers.length > 0) {
markers += " ";
}
markers += "\\v " + element.attributes.item("number").nodeValue;
break;
case "para":
// the para kind is in the style tag
if (markers.length > 0) {
markers += " ";
}
markers += "\\" + element.attributes.item("style").nodeValue;
break;
case "char":
// char-related markers, kept in the style attribute
if (markers.length > 0) {
markers += " ";
}
markers += "\\" + element.attributes.item("style").nodeValue;
break;
case "figure":
break;
case "note":
//caller, style
if (markers.length > 0) {
markers += " ";
}
markers += "\\" + element.attributes.item("style").nodeValue;
if (element.attributes.item("caller")) {
markers += " " + element.attributes.item("caller").nodeValue;
}
closingMarker = "\\" + element.attributes.item("style").nodeValue + "*";
break;
case "reference":
break;
default: // no processing for other nodes
break;
}
}
// If this is a text node, create any needed sourcephrases
if ($(element)[0].nodeType === 3) {
// Split the text into an array
// Note that this is analogous to the AI "strip" of text, and not the whole document
arr = ($(element)[0].nodeValue).trim().split(re);
i = 0;
while (i < arr.length) {
// check for a marker
if (arr[i].length === 0) {
// nothing in this token -- skip
i++;
} else if (arr[i].length === 1 && puncts.indexOf(arr[i]) > -1) {
// punctuation token -- add to the prepuncts
prepuncts += arr[i];
i++;
} else {
// "normal" sourcephrase token
s = arr[i];
// look for leading and trailing punctuation
// leading...
if (puncts.indexOf(arr[i].charAt(0)) > -1) {
// leading punct
punctIdx = 0;
while (puncts.indexOf(arr[i].charAt(punctIdx)) > -1 && punctIdx < arr[i].length) {
prepuncts += arr[i].charAt(punctIdx);
punctIdx++;
}
// remove the punctuation from the "source" of the substring
s = s.substr(punctIdx);
}
if (s.length === 0) {
// it'a ALL punctuation -- jump to the next token
i++;
} else {
// not all punctuation -- check following punctuation, then create a sourcephrase
if (puncts.indexOf(s.charAt(s.length - 1)) > -1) {
// trailing punct
punctIdx = s.length - 1;
while (puncts.indexOf(s.charAt(punctIdx)) > -1 && punctIdx > 0) {
follpuncts += s.charAt(punctIdx);
punctIdx--;
}
// remove the punctuation from the "source" of the substring
s = s.substr(0, punctIdx + 1);
}
// Now create a new sourcephrase
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: prepuncts,
midpuncts: midpuncts,
follpuncts: follpuncts,
source: s,
target: ""
});
markers = "";
prepuncts = "";
follpuncts = "";
punctIdx = 0;
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
i++;
}
}
}
}
// recurse into children
if ($(element).contents().length > 0) {
$(element).contents().each(function (idx, elt) {
parseNode(elt);
});
}
};
console.log("Reading USX file:" + file.name);
bookName = file.name.substr(0, file.name.indexOf("."));
scrIDList.fetch({reset: true, data: {id: ""}});
// the book ID (e.g., "MAT") is in a singleton <book> element of the USX file
scrID = scrIDList.where({id: $($xml).find("book").attr("code")})[0];
if (scrID === null) {
console.log("No ID matching this document: " + $($xml).find("book").attr("code"));
errMsg = i18n.t("view.dscErrCannotFindID");
return false;
}
arr = scrID.get('chapters');
if (books.where({scrid: (scrID.get('id'))}).length > 0) {
// this book is already in the list -- just return
errMsg = i18n.t("view.dscErrDuplicateFile");
return false;
}
index = 1;
bookID = Underscore.uniqueId();
// Create the book and chapter
book = new bookModel.Book({
bookid: bookID,
projectid: project.get('projectid'),
scrid: scrID.get('id'),
name: bookName,
filename: file.name,
chapters: []
});
books.add(book);
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: "1"});
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// set the lastDocument / lastAdapted<xxx> values if not already set
if (project.get('lastDocument') === "") {
project.set('lastDocument', bookName);
}
if (project.get('lastAdaptedBookID') === 0) {
project.set('lastAdaptedBookID', bookID);
project.set('lastAdaptedChapterID', chapterID);
}
if (project.get('lastAdaptedName') === "") {
project.set('lastAdaptedName', chapterName);
}
// now read the contents of the file
parseNode($($xml).find("usx"));
// add any remaining sourcephrases
if ((sps.length % MAX_BATCH) > 0) {
$("#status").html(i18n.t("view.dscStatusSaving"));
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - (sps.length % MAX_BATCH))));
}
// track all those deferred calls to addBatch -- when they all complete, report the results to the user
$.when.apply($, deferreds).done(function (value) {
importSuccess();
}).fail(function (e) {
importFail(e);
});
// update the last chapter's verseCount
chapter.set('versecount', verseCount, {silent: true});
chapter.save();
book.set('chapters', chaps, {silent: true});
book.save();
return true; // success
// END readUSXDoc()
};
// Adapt It XML document
// While XML is a general purpose document format, we're looking
// specifically for Adapt It XML document files; other files
// will be skipped (for now).
// This import also populates the KB and sets the last translated verse in each chapter.
var readXMLDoc = function (contents) {
var prepunct = "";
var re = /\s+/;
var follpunct = "";
var sp = null;
var chaps = [];
var xmlDoc = $.parseXML(contents);
var chapterName = "";
// find the USFM ID of this book
var scrIDList = new scrIDs.ScrIDCollection();
var verseCount = 0;
var lastAdapted = 0;
var firstChapterID = "";
var markers = "";
var firstChapterNumber = "1";
var i = 0;
var firstBook = false;
var isMergedDoc = false;
// helper method to convert html color values to the Adapt It color string:
// .html --> #rrggbb (in hex)
// Adapt It --> 0x00bbggrr (in base 10)
// var setColorValue = function (strValue) {
// var hexValue = parseInt(strValue, 16);
// var rValue = ("00" + (hexValue & 0xff).toString(16)).slice(-2);
// var gValue = ("00" + ((hexValue >> 8) & 0xff).toString(16)).slice(-2);
// var bValue = ("00" + ((hexValue >> 16) & 0xff).toString(16)).slice(-2);
// // format in html hex, padded with leading zeroes
// var theValue = "0x00" + bValue + gValue + rValue;
// return theValue;
// };
// Helper method to convert theString to lower case using either the source or target case equivalencies.
var autoRemoveCaps = function (theString, isSource) {
var i = 0,
result = "";
// If we aren't capitalizing for this project, just return theString
if (project.get('AutoCapitalization') === 'false') {
return theString;
}
// is the first letter capitalized?
if (isSource === true) {
// use source case equivalencies
for (i = 0; i < caseSource.length; i++) {
if (caseSource[i].charAt(1) === theString.charAt(0)) {
// uppercase -- convert the first character to lowercase and return the result
result = caseSource[i].charAt(0) + theString.substr(1);
return result;
}
}
} else {
// use target case equivalencies
for (i = 0; i < caseTarget.length; i++) {
if (caseTarget[i].charAt(1) === theString.charAt(0)) {
// uppercase -- convert the first character to lowercase and return the result
result = caseTarget[i].charAt(0) + theString.substr(1);
return result;
}
}
}
// If we got here, the string wasn't uppercase -- just return the same string
return theString;
};
console.log("Reading XML file:" + file.name);
bookName = ""; // reset
// Book name
// Try to get the adapted book name from the \h marker, if it exists
if (contents.indexOf("\\h ") > 0) {
// there is a \h marker -- look backwards for the nearest "a" attribute (this is the adapted name)
index = contents.indexOf("\\h ");
i = contents.lastIndexOf("s=", index) + 3;
// Sanity check -- this \\h element might not have an adaptation
// (if it doesn't, there won't be a a="" after the s="" attribute)
if (contents.lastIndexOf("a=", index) > i) {
// Okay, this looks legit. Pull out the adapted book name from the file.
index = contents.lastIndexOf("a=", index) + 3;
bookName = contents.substr(index, contents.indexOf("\"", index) - index);
}
}
// If that didn't work, use the filename
if (bookName === "") {
bookName = file.name.substr(0, file.name.indexOf("."));
if (bookName.indexOf("_Collab") > -1) {
// Collab document -- strip out the _Collab_ and _CH<#> for the name
bookName = bookName.substr(8, bookName.lastIndexOf("_CH") - 8);
}
}
// Sanity check -- this needs to be an AI XML document (we don't support other xml files right now)
scrIDList.fetch({reset: true, data: {id: ""}});
// Starting at the SourcePhrases ( <S ...> ), look for the \id element
// in the markers. We'll test this against the canonical usfm markers to learn more about this document.
i = contents.indexOf("<S ");
index = contents.indexOf("\\id", i);
if (index === -1) {
// No ID found -- this is most likely not an AI xml document.
// Return; we can't parse random xml files.
console.log("No ID element found (is this an AI XML document?) -- exiting.");
errMsg = i18n.t("view.dscErrCannotFindID");
return false;
}
// We've found the \id element in the markers -- to get the value, we have to work
// backwards until we find the nearest "s" attribute
// e.g., <S s="MAT" ...>.
index = contents.lastIndexOf("s=", index) + 3;
scrID = scrIDList.where({id: contents.substr(index, contents.indexOf("\"", index) - index)})[0];
arr = scrID.get('chapters');
if (books.where({scrid: (scrID.get('id'))}).length > 0) {
// ** COLLABORATION SUPPORT **
// This book is already in our database -
// it could either be a duplicate book / file OR a different chapter from a
// collaboration document. Figure out which by finding the first chapter marker
// and seeing if it's already in our database
book = books.where({scrid: (scrID.get('id'))})[0]; // set to the existing book
index = contents.indexOf("\\c ", 0); // first chapter marker
if (index > 0) {
// pull out the chapter number
firstChapterNumber = contents.substr(index + 3, contents.indexOf(" ", index + 3) - (index + 3));
if (firstChapterNumber === "1") {
firstBook = true;
}
// look up the chapter number -- is it something we already have?
chapterName = i18n.t("view.lblChapterName", {bookName: book.get("bookid"), chapterNumber: firstChapterNumber});
if (chapters.where({name: chapterName}).length > 0) {
// This is a duplicate -- return
errMsg = i18n.t("view.dscErrDuplicateFile");
return false;
}
// If we got this far, we're looking at a collaboration document -
// we'll be merging in the new data into the existing book
isMergedDoc = true;
if (firstBook === true) {
// The user has merged in the first chapter AFTER importing a subsequent chapter --
// this shouldn't happen (see the logic block below that disallows it). Just in case,
// try to offset the damage by updating the book name to what this chapter holds.
book.set('name', bookName);
} else {
// Not the first chapter -- use the book name in the database object.
bookName = book.get("name");
}
bookID = book.get("bookid");
chaps = book.get("chapters"); // set to the chapters already imported in the book (we'll add to this array)
} else {
// No chapter found (but there is an ID) -- return
errMsg = i18n.t("view.dscErrCannotFindChapter");
return false;
}
} else {
// This is a new book
// Make a note of the first chapter number. Disallow collab documents where the first chapter is
// NOT the first document being imported, as this creates a headache for book naming / lookups.
index = contents.indexOf("\\c ", 0); // first chapter marker
if (index > 0) {
// pull out the chapter number
firstChapterNumber = contents.substr(index + 3, contents.indexOf(" ", index + 3) - (index + 3));
if (firstChapterNumber === "1") {
firstBook = true;
} else {
// User attempting to import collab document without importing the first chapter first;
// error out
errMsg = i18n.t("view.dscErrImportFirstChapterFirst");
return false;
}
}
// Create the book and chapter
bookID = Underscore.uniqueId();
book = new bookModel.Book({
bookid: bookID,
projectid: project.get('projectid'),
scrid: scrID.get('id'),
name: bookName,
filename: file.name,
chapters: []
});
books.add(book);
}
// Reset the index to the beginning of the file
index = 1;
// Add the first chapter
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: firstChapterNumber});
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// set the lastDocument / lastAdapted<xxx> values if not already set
if (project.get('lastDocument') === "") {
project.set('lastDocument', bookName);
}
if (project.get('lastAdaptedBookID') === 0) {
project.set('lastAdaptedBookID', bookID);
project.set('lastAdaptedChapterID', chapterID);
}
if (project.get('lastAdaptedName') === "") {
project.set('lastAdaptedName', chapterName);
}
// create the sourcephrases
var $xml = $(xmlDoc);
var stridx = 0;
var chapNum = "";
$($xml).find("S").each(function (i) {
if (i === 0 && firstBook === false) {
// merged (collaboration) documents have an extra "\id" element at the beginning of subsequent chapters;
// ignore this element and continue to the next one
return true; // jquery equivalent of continue in loop
}
// If this is a new chapter (starting for ch 2 -- chapter 1 is created above),
// create a new chapter object
markers = $(this).attr('m');
if (markers && markers.indexOf("\\c ") !== -1) {
// is this the first chapter marker? If so, ignore it (we already created it above)
stridx = markers.indexOf("\\c ") + 3;
chapNum = markers.substr(stridx, markers.indexOf(" ", stridx) - stridx);
if (chapNum !== firstChapterNumber) {
// This is not our first chapter, so we can create it
// update the last adapted for the previous chapter before closing it out
chapter.set('versecount', verseCount, {silent: true});
chapter.set('lastadapted', lastAdapted, {silent: true});
chapter.save();
verseCount = 0; // reset for the next chapter
lastAdapted = 0; // reset for the next chapter
stridx = markers.indexOf("\\c ") + 3;
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: markers.substr(stridx, markers.indexOf(" ", stridx) - stridx)});
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
// create the new chapter
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// console.log(": " + $(this).attr('s') + ", " + chapterID);
}
}
if (markers && markers.indexOf("\\v ") !== -1) {
verseCount++;
// check this sourcephrase for a target - if there is one, consider this verse adapted
// (note that we're only checking the FIRST sp of each verse, not EVERY sp in the verse)
if ($(this).attr('t')) {
lastAdapted++;
}
}
// if there are filtered text items, insert them now
if ($(this).attr('fi')) {
markers = "";
$(this).attr('fi').split(re).forEach(function (elt, index, array) {
if (elt.indexOf("~FILTER") > -1) {
// do nothing -- skip first and last elements
// console.log("filter");
} else if (elt.indexOf("\\") === 0) {
// starting marker
markers += elt;
} else if (elt.indexOf("\\") > 0) {
// ending marker - it's concatenated with the preceding token, no space
// create a sourcephrase with the first part of the token, using the marker
// from the end
markers += elt.substr(elt.indexOf("\\"));
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: $(this).attr('pp'),
midpuncts: "",
follpuncts: $(this).attr('fp'),
source: elt.substr(0, elt.indexOf("\\") - 1),
target: ""
});
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
markers = ""; // reset
} else {
// regular token - add as a new sourcephrase
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: $(this).attr('pp'),
midpuncts: "",
follpuncts: $(this).attr('fp'),
source: elt,
target: ""
});
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
markers = ""; // reset
}
});
}
// create the next sourcephrase
// console.log(i + ": " + $(this).attr('s') + ", " + chapterID);
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: $(this).attr('m'),
orig: null,
prepuncts: $(this).attr('pp'),
midpuncts: "",
follpuncts: $(this).attr('fp'),
source: $(this).attr('k'), // source w/o punctuation
target: $(this).attr('t')
});
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
// add this item to the KB
// TODO: build up punctpairs
if (sp.get('target').length > 0) {
saveInKB(autoRemoveCaps(sp.get('source'), true), autoRemoveCaps($(this).attr('a'), false),
"", project.get('projectid'));
}
});
// add any remaining sourcephrases
if ((sps.length % MAX_BATCH) > 0) {
$("#status").html(i18n.t("view.dscStatusSaving"));
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - (sps.length % MAX_BATCH))));
}
// track all those deferred calls to addBatch -- when they all complete, report the results to the user
$.when.apply($, deferreds).done(function (value) {
importSuccess();
}).fail(function (e) {
importFail(e);
});
// update the last chapter's verseCount and last adapted verse
chapter.set('lastadapted', lastAdapted, {silent: true});
chapter.set('versecount', verseCount, {silent: true});
chapter.save();
if (isMergedDoc === true) {
var chapList = [];
var number = 0;
var tmpString = "";
// If this is a merged document, the chapters might be out of order --
// sort them here
for (i = 0; i < chaps.length; i++) {
tmpString = chapters.findWhere({chapterid: chaps[i]}).get("name");
number = parseInt(tmpString.substr(tmpString.lastIndexOf(" " + 1)), 10); // just the number part
chapList.push({chapid: chaps[i], number: number});
}
var result = Underscore.sortBy(chapList, function (element) {
return element.number;
});
// transfer the sorted list back into chaps
chaps.length = 0; // clear chaps
for (i = 0; i < result.length; i++) {
chaps.push(result[i].chapid);
}
}
book.set('chapters', chaps, {silent: true});
book.save();
return true; // success
// END readXMLDoc()
};
// USFM document
// This is the file format for Bibledit and Paratext
// See http://paratext.org/about/usfm for format specification
var readUSFMDoc = function (contents) {
var scrIDList = new scrIDs.ScrIDCollection();
var chapterName = "";
var sp = null;
var re = /\s+/;
var markerList = new USFM.MarkerCollection();
var marker = null;
var lastAdapted = 0;
var verseCount = 0;
var hasPunct = false;
var punctIdx = 0;
var stridx = 0;
var chaps = [];
console.log("Reading USFM file:" + file.name);
index = contents.indexOf("\\h ");
if (index > -1) {
// get the name from the usfm itself
bookName = contents.substr(index + 3, (contents.indexOf("\n", index) - (index + 3))).trim();
} else {
bookName = file.name;
}
// find the ID of this book
index = contents.indexOf("\\id");
if (index === -1) {
// no ID found -- return
errMsg = i18n.t("view.dscErrCannotFindID");
return false;
}
markerList.fetch({reset: true, data: {name: ""}});
scrIDList.fetch({reset: true, data: {id: ""}});
scrID = scrIDList.where({id: contents.substr(index + 4, 3)})[0];
// books.fetch({reset: true, data: {name: ""}});
if (books.where({scrid: (scrID.get('id'))}).length > 0) {
// this book is already in the list -- return
errMsg = i18n.t("view.dscErrDuplicateFile");
return false;
}
// add a book and chapter
bookID = Underscore.uniqueId();
book = new bookModel.Book({
bookid: bookID,
projectid: project.get('projectid'),
scrid: scrID.get('id'),
name: bookName,
filename: file.name,
chapters: [] // arr
});
books.add(book);
// Note that we're adding chapter 1 before we reach the \c 1 marker in the file --
// Usually there's a fair amount of front matter before we reach the chapter itself;
// rather than creating a chapter 0 (which would throw off the search stuff), we'll
// just add the front matter to chapter 1.
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: "1"});
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// set the lastDocument / lastAdapted<xxx> values if not already set
if (project.get('lastDocument') === "") {
project.set('lastDocument', bookName);
}
if (project.get('lastAdaptedBookID') === 0) {
project.set('lastAdaptedBookID', bookID);
project.set('lastAdaptedChapterID', chapterID);
}
if (project.get('lastAdaptedName') === "") {
project.set('lastAdaptedName', chapterName);
}
// build SourcePhrases
arr = contents.replace(/\\/gi, " \\").split(re); // add space to make sure markers get put in a separate token
i = 0;
while (i < arr.length) {
// check for a marker
if (arr[i].indexOf("\\") === 0) {
// marker token
if (markers.length > 0) {
markers += " ";
}
markers += arr[i];
// If this is the start of a new paragraph, etc., check to see if there's a "dangling"
// punctuation mark. If so, it belongs as a follPunct of the precious SourcePhrase
if ((arr[i] === "\\p" || arr[i] === "\\c" || arr[i] === "\\v") && prepuncts.length > 0) {
sp.set("follpuncts", (sp.get("follpuncts") + prepuncts), {silent: true});
prepuncts = ""; // clear out the punctuation -- it's set on the previous sp now
}
// Check for markers with more than one token (and merge the two marker tokens)
if ((arr[i] === "\\x") || (arr[i] === "\\f") ||
(arr[i] === "\\c") || (arr[i] === "\\ca") || (arr[i] === "\\cp") ||
(arr[i] === "\\v") || (arr[i] === "\\va") || (arr[i] === "\\vp")) {
// join with the next
i++;
markers += " " + arr[i];
}
i++;
} else if (arr[i].length === 0) {
// nothing in this token -- skip
i++;
} else if (arr[i].length === 1 && puncts.indexOf(arr[i]) > -1) {
// punctuation token -- add to the prepuncts
prepuncts += arr[i];
i++;
} else if (arr[i].length === 2 && puncts.indexOf(arr[i]) > -1) {
// 2-char punctuation token -- add to the prepuncts
prepuncts += arr[i];
i++;
} else {
// "normal" sourcephrase token
// Before creating the sourcephrase, look to see if we need to create a chapter element
// (note that we've already created chapter 1, so skip it if we come across it)
if (markers && markers.indexOf("\\c ") !== -1 && markers.indexOf("\\c 1 ") === -1) {
// update the last adapted for the previous chapter before closing it out
chapter.set('versecount', verseCount, {silent: true});
chapter.set('lastadapted', lastAdapted, {silent: true});
chapter.save();
verseCount = 0; // reset for the next chapter
lastAdapted = 0; // reset for the next chapter
stridx = markers.indexOf("\\c ") + 3;
if (markers.lastIndexOf(" ") < stridx) {
// no space after the chapter # (it's the ending of the string)
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: markers.substr(stridx)});
} else {
// space after the chapter #
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: markers.substr(stridx, markers.indexOf(" ", stridx) - stridx)});
}
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
// create the new chapter
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// console.log(chapterName + ": " + chapterID);
}
// also do some processing for verse markers
if (markers && markers.indexOf("\\v ") !== -1) {
verseCount++;
// check this sourcephrase for a target - if there is one, consider this verse adapted
// (note that we're only checking the FIRST sp of each verse, not EVERY sp in the verse)
if ($(this).attr('t')) {
lastAdapted++;
}
}
s = arr[i];
// look for leading and trailing punctuation
// leading...
if (puncts.indexOf(arr[i].charAt(0)) > -1) {
// leading punct
punctIdx = 0;
while (puncts.indexOf(arr[i].charAt(punctIdx)) > -1 && punctIdx < arr[i].length) {
prepuncts += arr[i].charAt(punctIdx);
punctIdx++;
}
// remove the punctuation from the "source" of the substring
s = s.substr(punctIdx);
}
if (s.length === 0) {
// it'a ALL punctuation -- jump to the next token
i++;
} else {
// not all punctuation -- check following punctuation, then create a sourcephrase
if (puncts.indexOf(s.charAt(s.length - 1)) > -1) {
// trailing punct
punctIdx = s.length - 1;
while (puncts.indexOf(s.charAt(punctIdx)) > -1 && punctIdx > 0) {
follpuncts = s.charAt(punctIdx) + follpuncts;
punctIdx--;
}
// remove the punctuation from the "source" of the substring
s = s.substr(0, punctIdx + 1);
}
// Now create a new sourcephrase
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: prepuncts,
midpuncts: midpuncts,
follpuncts: follpuncts,
source: s,
target: ""
});
markers = "";
prepuncts = "";
follpuncts = "";
punctIdx = 0;
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
i++;
}
}
}
// add any remaining sourcephrases
if ((sps.length % MAX_BATCH) > 0) {
$("#status").html(i18n.t("view.dscStatusSaving"));
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - (sps.length % MAX_BATCH))));
}
// track all those deferred calls to addBatch -- when they all complete, report the results to the user
$.when.apply($, deferreds).done(function (value) {
importSuccess();
}).fail(function (e) {
importFail(e);
});
// update the last chapter's verseCount
chapter.set('versecount', verseCount, {silent: true});
chapter.save();
book.set('chapters', chaps, {silent: true});
book.save();
return true; // success
// END readUSFMDoc()
};
///
// END FILE TYPE READERS
///
// read doc as appropriate
if ((file.name.indexOf(".usfm") > 0) || (file.name.indexOf(".sfm") > 0)) {
result = readUSFMDoc(this.result);
} else if (file.name.indexOf(".usx") > 0) {
result = readUSXDoc(this.result);
} else if (file.name.indexOf(".xml") > 0) {
result = readXMLDoc(this.result);
} else if (file.name.indexOf(".txt") > 0) {
// .txt -- check to see if it's really USFM under the hood
// find the ID of this book
index = this.result.indexOf("\\id");
if (index >= 0) {
// _probably_ USFM under the hood -- at least try to read it as USFM
result = readUSFMDoc(this.result);
} else {
// not USFM -- try reading it as a text document
result = readTextDoc(this.result);
}
} else {
// some other extension -- try reading it as a text document
result = readTextDoc(this.result);
}
if (result === false) {
importFail(new Error(errMsg));
}
};
reader.readAsText(file);
},
// Helper method to export the given bookid to the specified file format.
// Called from ExportDocumentView::onOK once the book, format and filename have been chosen.
exportDocument = function (bookid, format, filename) {
var status = "";
var writer = null;
var errMsg = "";
var sourcephrases = null;
var exportDirectory = "";
var tabLevel = 0;
// Callback for when the file is imported / saved successfully
var exportSuccess = function () {
console.log("exportSuccess()");
// update status
$("#status").html(i18n.t("view.dscStatusExportSuccess", {document: filename}));
// display the OK button
$("#loading").hide();
$("#waiting").hide();
$("#OK").show();
$("#OK").removeAttr("disabled");
};
// Callback for when the file failed to import
var exportFail = function (e) {
console.log("exportFail(): " + e.message);
// update status
$("#status").html(i18n.t("view.dscExportFailed", {document: filename, reason: e.message}));
$("#loading").hide();
$("#waiting").hide();
// display the OK button
$("#OK").show();
$("#OK").removeAttr("disabled");
};
///
// FILE TYPE WRITERS
// 2 loops for each file type -- a chapter and source phrase loop.
// The AI XML export will dump out the entire book; the others use the following logic:
// - If the chapter has at least some adaptations in it, we'll export it
// - If we encounter the lastSPID, we'll break out of the export loop of the chapter.
// This logic works well if the user is adapting sequentially. If the user is jumping around in their adaptations,
// some chapters might have extraneous punctuation from areas where they haven't adapted.
///
// Plain Text document
// We assume these are just text with no markup,
// in a single chapter (this could change if needed)
var exportText = function () {
var chapters = window.Application.ChapterList.where({bookid: bookid});
var content = "";
var spList = new spModel.SourcePhraseCollection();
var markerList = new USFM.MarkerCollection();
var i = 0;
var idxFilters = 0;
var value = null;
var filterAry = window.Application.currentProject.get('FilterMarkers').split("\\");
var lastSPID = window.Application.currentProject.get('lastAdaptedSPID');
var chaptersLeft = chapters.length;
var filtered = false;
var needsEndMarker = "";
var mkr = "";
writer.onwriteend = function (e) {
console.log("write completed.");
if (chaptersLeft === 0) {
exportSuccess();
}
};
writer.onerror = function (e) {
console.log("write failed: " + e.toString());
exportFail(e);
};
// get the chapters belonging to our book
markerList.fetch({reset: true, data: {name: ""}});
console.log("markerList count: " + markerList.length);
lastSPID = lastSPID.substring(lastSPID.lastIndexOf("-") + 1);
console.log("filterAry: " + filterAry.toString());
chapters.forEach(function (entry) {
// for each chapter with some adaptation done, get the sourcephrases
if (entry.get('lastadapted') !== 0) {
spList.fetch({reset: true, data: {chapterid: entry.get("chapterid")}}).done(function () {
console.log("spList: " + spList.length + " items, last id = " + lastSPID);
for (i = 0; i < spList.length; i++) {
value = spList.at(i);
// plain text -- we're not all that interested in formatting, but do add some
// line breaks for chapter, verse, paragraph marks
if ((value.get("markers").indexOf("\\c") > -1) || (value.get("markers").indexOf("\\v") > -1) ||
(value.get("markers").indexOf("\\h") > -1) || (value.get("markers").indexOf("\\p") > -1)) {
content += "\n"; // newline
}
// check to see if this sourcephrase is filtered (only looking at the top level)
if (filtered === false) {
for (idxFilters = 0; idxFilters < filterAry.length; idxFilters++) {
// sanity check for blank filter strings
if (filterAry[idxFilters].trim().length > 0) {
if (value.get("markers").indexOf(filterAry[idxFilters]) >= 0) {
// this is a filtered sourcephrase -- do not export it
console.log("filtered: " + value.get("markers"));
// if there is an end marker associated with this marker,
// do not export any source phrases until we come across the end marker
mkr = markerList.where({name: filterAry[idxFilters].trim()});
if (mkr[0].get("endMarker")) {
needsEndMarker = mkr[0].get("endMarker");
}
filtered = true;
}
}
}
}
if (value.get("markers").indexOf(needsEndMarker) >= 0) {
// found our ending marker -- this sourcephrase is not filtered
needsEndMarker = "";
filtered = false;
}
if (filtered === false) {
content += value.get("prepuncts") + value.get("target") + value.get("follpuncts") + " ";
}
if (value.get('spid') === lastSPID) {
// done -- quit after this sourcePhrase
console.log("Found last SPID: " + lastSPID);
break;
}
}
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
});
}
chaptersLeft--;
});
};
// USFM document
var exportUSFM = function () {
var chapters = window.Application.ChapterList.where({bookid: bookid});
var content = "";
var spList = new spModel.SourcePhraseCollection();
var markerList = new USFM.MarkerCollection();
var markers = "";
var i = 0;
var idxFilters = 0;
var value = null;
var chaptersLeft = chapters.length;
var filtered = false;
var needsEndMarker = "";
var mkr = "";
var filterAry = window.Application.currentProject.get('FilterMarkers').split("\\");
var lastSPID = window.Application.currentProject.get('lastAdaptedSPID');
writer.onwriteend = function (e) {
console.log("write completed.");
if (chaptersLeft === 0) {
exportSuccess();
}
};
writer.onerror = function (e) {
console.log("write failed: " + e.toString());
exportFail(e);
};
markerList.fetch({reset: true, data: {name: ""}});
console.log("markerList count: " + markerList.length);
lastSPID = lastSPID.substring(lastSPID.lastIndexOf("-") + 1);
chapters.forEach(function (entry) {
// for each chapter with some adaptation done, get the sourcephrases
if (entry.get('lastadapted') !== 0) {
spList.fetch({reset: true, data: {chapterid: entry.get("chapterid")}}).done(function () {
console.log("spList: " + spList.length + " items, last id = " + lastSPID);
for (i = 0; i < spList.length; i++) {
value = spList.at(i);
markers = value.get("markers");
// check to see if this sourcephrase is filtered (only looking at the top level)
if (filtered === false) {
for (idxFilters = 0; idxFilters < filterAry.length; idxFilters++) {
// sanity check for blank filter strings
if (filterAry[idxFilters].trim().length > 0) {
if (markers.indexOf(filterAry[idxFilters]) >= 0) {
// this is a filtered sourcephrase -- do not export it
console.log("filtered: " + markers);
// however, if there are some markers before we hit our filtered one,
// make sure they get exported now
markers = markers.substr(0, markers.indexOf(filterAry[idxFilters]) - 1);
if (markers.length > 0) {
if ((markers.indexOf("\\v") > -1) || (markers.indexOf("\\c") > -1) ||
(markers.indexOf("\\p") > -1) || (markers.indexOf("\\id") > -1) ||
(markers.indexOf("\\h") > -1) || (markers.indexOf("\\toc") > -1) || (markers.indexOf("\\mt") > -1)) {
// pretty-printing -- add a newline so the output looks better
content += "\n"; // newline
}
// now add the markers and a space
content += markers + " ";
}
content += (markers.substr(0, markers.indexOf(filterAry[idxFilters]))) + " ";
// if there is an end marker associated with this marker,
// do not export any source phrases until we come across the end marker
mkr = markerList.where({name: filterAry[idxFilters].trim()});
if (mkr[0].get("endMarker")) {
needsEndMarker = mkr[0].get("endMarker");
}
filtered = true;
}
}
}
}
if ((needsEndMarker.length > 0) && (markers.indexOf(needsEndMarker) >= 0)) {
// found our ending marker -- this sourcephrase is not filtered
// first, remove the marker from the markers string so it doesn't print out
markers = markers.replace(("\\" + needsEndMarker), '');
// now clear our flags so the sourcephrase exports
needsEndMarker = "";
filtered = false;
}
if (filtered === false) {
// add markers, and if needed, pretty-print the text on a newline
if (markers.trim().length > 0) {
if ((markers.indexOf("\\v") > -1) || (markers.indexOf("\\c") > -1) || (markers.indexOf("\\p") > -1) || (markers.indexOf("\\id") > -1) || (markers.indexOf("\\h") > -1) || (markers.indexOf("\\toc") > -1) || (markers.indexOf("\\mt") > -1)) {
// pretty-printing -- add a newline so the output looks better
content += "\n"; // newline
}
// now add the markers and a space
content += markers + " ";
}
content += value.get("prepuncts") + value.get("target") + value.get("follpuncts") + " ";
}
if (value.get('spid') === lastSPID) {
// done -- quit after this sourcePhrase
console.log("Found last SPID: " + lastSPID);
break;
}
}
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
});
}
chaptersLeft--;
});
};
// USX document
var exportUSX = function () {
var chapters = window.Application.ChapterList.where({bookid: bookid});
var book = window.Application.BookList.where({bookid: bookid})[0];
var bookID = book.get('scrid');
var content = "";
var XML_PROLOG = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
var spList = new spModel.SourcePhraseCollection();
var markerList = new USFM.MarkerCollection();
var filterAry = window.Application.currentProject.get('FilterMarkers').split("\\");
var lastSPID = window.Application.currentProject.get('lastAdaptedSPID');
var filtered = false;
var needsEndMarker = "";
var markers = "";
var i = 0;
var idxFilters = 0;
var versenum = 1;
var closeNode = ""; // holds ending string for <para> and <book> XML nodes
var value = null;
var mkr = "";
var chaptersLeft = chapters.length;
writer.onwriteend = function (e) {
console.log("write completed.");
if (chaptersLeft === 0) {
exportSuccess();
}
};
writer.onerror = function (e) {
console.log("write failed: " + e.toString());
exportFail(e);
};
// starting material -- xml prolog and usx tag
content = XML_PROLOG + "\n<usx version=\"2.0\">\n";
// get the chapters belonging to our book
markerList.fetch({reset: true, data: {name: ""}});
console.log("markerList count: " + markerList.length);
lastSPID = lastSPID.substring(lastSPID.lastIndexOf("-") + 1);
chapters.forEach(function (entry) {
// for each chapter with some adaptation done, get the sourcephrases
if (entry.get('lastadapted') !== 0) {
// add a placeholder string for this chapter, so that it ends up in order (the call to
// fetch() is async, and sometimes the chapters are returned out of order)
content += "**" + entry.get("chapterid") + "**";
spList.fetch({reset: true, data: {chapterid: entry.get("chapterid")}}).done(function () {
var chapterString = "";
console.log("spList: " + spList.length + " items, last id = " + lastSPID);
for (i = 0; i < spList.length; i++) {
value = spList.at(i);
markers = value.get("markers");
// check to see if this sourcephrase is filtered (only looking at the top level)
if (filtered === false) {
for (idxFilters = 0; idxFilters < filterAry.length; idxFilters++) {
// sanity check for blank filter strings
if (filterAry[idxFilters].trim().length > 0) {
if (markers.indexOf(filterAry[idxFilters]) >= 0) {
// this is a filtered sourcephrase -- do not export it
console.log("filtered: " + markers);
// if there is an end marker associated with this marker,
// do not export any source phrases until we come across the end marker
mkr = markerList.where({name: filterAry[idxFilters].trim()});
if (mkr[0].get("endMarker")) {
needsEndMarker = mkr[0].get("endMarker");
}
filtered = true;
}
}
}
}
if ((needsEndMarker.length > 0) && (markers.indexOf(needsEndMarker) >= 0)) {
// found our ending marker -- this sourcephrase is not filtered
// first, remove the marker from the markers string so it doesn't print out
markers = markers.replace(("\\" + needsEndMarker), '');
// now clear our flags so the sourcephrase exports
needsEndMarker = "";
filtered = false;
}
if (filtered === false) {
// not filtered -- print out the text and markers
if (markers.length > 0) {
if ((markers.indexOf("\\id ")) > -1) {
chapterString += "<book code=\"" + bookID + "\" style=\"id\">";
chapterString += value.get("target");
closeNode = "</book>";
continue; // skip to the next entry
}
// TODO -- list of markers...
if (markers.indexOf("\\c ") > -1) {
if (closeNode.length > 0) {
chapterString += closeNode;
closeNode = ""; // clear it out
}
var chpos = markers.indexOf("\\c");
chapterString += "\n<chapter number=\"";
chapterString += markers.substr(chpos + 3, (markers.indexOf(" ", chpos + 3) - (chpos + 3)));
chapterString += "\" style=\"c\" />";
}
if (markers.indexOf("\\b ") > -1) {
if (closeNode.length > 0) {
chapterString += closeNode;
closeNode = ""; // clear it out
}
chapterString += "\n<para style=\"b\" />";
}
if ((markers.indexOf("\\p") > -1) || (markers.indexOf("\\q") > -1) || (markers.indexOf("\\ide") > -1) || (markers.indexOf("\\h") > -1) || (markers.indexOf("\\mt") > -1) || (markers.indexOf("\\imt") > -1) || (markers.indexOf("\\rem") > -1) || (markers.indexOf("\\toc") > -1)) {
if (closeNode.length > 0) {
chapterString += closeNode;
}
chapterString += "\n<para style=\"";
if (markers.indexOf("\\p") > -1) {
var ppos = markers.indexOf("\\p");
if (markers.indexOf(" ", hpos) > -1) {
chapterString += markers.substring(ppos + 1, (markers.indexOf(" ", ppos)));
} else {
chapterString += markers.substr(ppos + 1);
}
} else if (markers.indexOf("\\q") > -1) {
// extract out what kind of quote this is (e.g., "q2") - this goes in the style attribute
var qpos = markers.indexOf("\\q");
if (markers.indexOf(" ", qpos) > -1) {
chapterString += markers.substring(qpos + 1, (markers.indexOf(" ", qpos)));
} else {
chapterString += markers.substr(qpos + 1);
}
} else if (markers.indexOf("\\ide") > -1) {
chapterString += "ide";
} else if (markers.indexOf("\\h") > -1) {
var hpos = markers.indexOf("\\h");
if (markers.indexOf(" ", hpos) > -1) {
chapterString += markers.substring(hpos + 1, (markers.indexOf(" ", hpos)));
} else {
chapterString += markers.substr(hpos + 1);
}
} else if (markers.indexOf("\\rem") > -1) {
chapterString += "rem";
} else if (markers.indexOf("\\imt") > -1) {
// extract out what kind this is (e.g., "imt2") -
// this goes in the style attribute
var imtpos = markers.indexOf("\\imt");
if (markers.indexOf(" ", imtpos) > -1) { chapterString += markers.substring(imtpos + 1, (markers.indexOf(" ", imtpos)));
} else {
chapterString += markers.substr(imtpos + 1);
}
} else if (markers.indexOf("\\mt") > -1) {
// extract out what kind this is (e.g., "mt2") -
// this goes in the style attribute
var mtpos = markers.indexOf("\\mt");
if (markers.indexOf(" ", mtpos) > -1) { chapterString += markers.substring(mtpos + 1, (markers.indexOf(" ", mtpos)));
} else {
chapterString += markers.substr(mtpos + 1);
}
} else if (markers.indexOf("\\toc") > -1) {
// extract out what kind this is (e.g., "toc2") -
// this goes in the style attribute
var tocpos = markers.indexOf("\\toc");
if (markers.indexOf(" ", tocpos) > -1) { chapterString += markers.substring(tocpos + 1, (markers.indexOf(" ", tocpos)));
} else {
chapterString += markers.substr(tocpos + 1);
}
}
chapterString += "\">";
closeNode = "</para>";
}
// if (markers.indexOf("\\+ ") > -1) {
// chapterString += "<note caller=\"+\" style=\"f\">";
// }
if (markers.indexOf("\\v ") > -1) {
var vpos = markers.indexOf("\\v ");
chapterString += "<verse number=\"";
if (markers.indexOf(" ", vpos + 3) > -1) {
chapterString += markers.substring(vpos + 3, (markers.indexOf(" ", vpos + 3)));
} else {
chapterString += markers.substr(vpos + 3);
}
chapterString += "\" style=\"v\" />";
}
}
chapterString += value.get("prepuncts") + value.get("target") + value.get("follpuncts") + " ";
}
// done dealing with the source phrase -- is it the last one?
if (value.get('spid') === lastSPID) {
// last phrase -- exit
console.log("Found last SPID: " + lastSPID);
break;
}
}
// Now take the string from this chapter's sourcephrases that we've just built and
// insert them into the correct location in the file's content string
content = content.replace(("**" + entry.get("chapterid") + "**"), chapterString);
// decrement the chapter count, closing things out if needed
chaptersLeft--;
if (chaptersLeft === 0) {
console.log("finished within sp block");
// done with the chapters
// add a closing paragraph if necessary
if (closeNode.length > 0) {
content += closeNode;
}
// add the ending node
content += "\n</usx>\n";
// ** we are now done with all the chapters -- write out the file
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
}
});
} else {
// BUGBUG: can we end up here if there are chapters?
// no sourcephrases to export -- just decrement the chapters, and close things out if needed
chaptersLeft--;
if (chaptersLeft === 0) {
console.log("finished in a blank block");
// done with the chapters
// add a closing paragraph if necessary
if (closeNode.length > 0) {
content += closeNode;
}
// add the ending node
content += "\n</usx>\n";
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
}
}
});
};
// XML document
// Note that this export is a full dump of the document, not just the parts that have been adapted.
// This is because we're exporting the source as well as the target text.
// EDB 8/13/16: partially working. Still need:
// - colors in settings node converted to AI doc format (WXWidgets) from RGB
// ..and for each SP
// - Flag bitss generated (implement buildFlags() below)
// - type enum generated (implement buildTY() below)
// - "inform" bits copied over
// -- lower priority, but need for AI compatibility: other bits implemented
var exportXML = function () {
var chapters = window.Application.ChapterList.where({bookid: bookid});
var book = window.Application.BookList.where({bookid: bookid});
var content = "";
var words = [];
var XML_PROLOG = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>";
var spList = new spModel.SourcePhraseCollection();
var markers = "";
var i = 0;
var value = null;
var atts = {
name: [],
value: []
};
var project = window.Application.currentProject;
var chaptersLeft = chapters.length;
var buildFlags = function (sourcephrase) {
// (code in XML.cpp ~ line 5568)
var val = "";
return val;
};
var buildTY = function (sourcephrase) {
// (code in SourcePhrase.h ~ line 55)
var val = "";
val = "0"; // none
return val;
};
writer.onwriteend = function (e) {
console.log("write completed.");
if (chaptersLeft === 0) {
exportSuccess();
}
};
writer.onerror = function (e) {
console.log("write failed: " + e.toString());
exportFail(e);
};
// opening content
content = XML_PROLOG;
content += "\n<!--\n Note: Using Microsoft WORD 2003 or later is not a good way to edit this xml file.\n Instead, use NotePad or WordPad. -->\n<AdaptItDoc>\n";
// Settings: AIM doesn't do per-document settings; just copy over the project settings
content += "<Settings docVersion=\"9\" bookName=\"" + bookName + "\" owner=\"";
if (window.sqlitePlugin) {
content += device.uuid;
} else {
content += "Browser";
}
content += "\" commitcnt=\"****\" revdate=\"\" actseqnum=\"0\" sizex=\"553\" sizey=\"62464\" ftsbp=\"1\"";
// colors
content += " specialcolor=\"" + project.get('SpecialTextColor') + "\" retranscolor=\"" + project.get('RetranslationColor') + "\" navcolor=\"" + project.get('NavigationColor') + "\"";
// project info
content += " curchap=\"1:\" srcname=\"" + project.get('SourceLanguageName') + "\" tgtname=\"" + project.get('TargetLanguageName') + "\" srccode=\"" + project.get('SourceLanguageCode') + "\" tgtcode=\"" + project.get('TargetLanguageCode') + "\"";
// filtering
content += " others=\"@#@#:F:-1:0:";
content += project.get('FilterMarkers');
content += "::\"/>\n";
// END settings xml node
// CONTENT PART: get the chapters belonging to our book
chapters.forEach(function (entry) {
// for each chapter (regardless of whether there's some adaptation done), get the sourcephrases
spList.fetch({reset: true, data: {chapterid: entry.get("chapterid")}}).done(function () {
for (i = 0; i < spList.length; i++) {
value = spList.at(i);
// format for <S> nodes found in CSourcePhrase::MakeXML (SourcePhrase.cpp)
// line 1 -- source, key, target, adaptation
content += "<S s=\"";
if (value.get("prepuncts").length > 0) {
content += value.get("prepuncts");
}
content += value.get("source");
if (value.get("follpuncts").length > 0) {
content += value.get("follpuncts");
}
content += "\" k=\"" + value.get("source") + "\"";
if (value.get("target").length > 0) {
content += " t=\"" + value.get("target") + "\" a=\"" + value.get("target") + "\"";
}
// line 2 -- flags, sequNumber, SrcWords, TextType
content += " f=\"" + buildFlags(value) + "\" sn=\"" + (value.get('norder') - 1);
words = value.get("source").match(/\S+/g);
if (words) {
content += "\" w=\"" + words.length + "\"";
} else {
content += "\" w=\"1\"";
}
content += " ty=\"" + buildTY(value) + "\"";
// line 3 -- 6 atts (optional)
if (value.get("prepuncts").length > 0) {
content += " pp=\"" + value.get("prepuncts") + "\"";
}
if (value.get("follpuncts").length > 0) {
content += " fp=\"" + value.get("follpuncts") + "\"";
}
markers = value.get("markers");
// inform
if (markers.indexof("\\h ") > -1) {
content += " i=\"hdr\"";
}
// if (markers.indexof("\\mt1") > -1) {
// content += " i=\"main title L1\"";
// }
// if (markers.indexof("\\imt1") > -1) {
// content += " i=\"intro major title L1\"";
// }
// if (markers.indexof("\\ip") > -1) {
// content += " i=\"intro paragraph\"";
// }
// add markers, and if needed, pretty-print the text on a newline
if (markers.indexOf("\\v") > -1) {
// add chapter/verse
content += " c=\"" + entry.get('name') + ":" + "\"";
}
// line 4 -- markers, end markers, inline binding markers, inline binding end markers,
// inline nonbinding markers, inline nonbinding end barkers
if (markers.length > 0) {
content += " m=\"" + markers + "\"";
}
// line 5-8 -- free translation, note, back translation, filtered info
// line 9 -- lapat, tmpat, gmpat, pupat
content += ">\n";
// 3 more possible info types
// medial puncts, medial markers, saved words (another <s>)
if (value.get("midpuncts").length > 0) {
content += "<MP mp=\"" + value.get("midpuncts") + "\"/>";
}
content += "</S>\n";
}
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
chaptersLeft--;
if (chaptersLeft === 0) {
// done with the chapters -- add the ending node
content += "\n</AdaptItDoc>\n";
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
}
});
});
};
if (window.sqlitePlugin) {
// mobile device
if (cordova.file.documentsDirectory !== null) {
// iOS, OSX
exportDirectory = cordova.file.documentsDirectory;
} else if (cordova.file.sharedDirectory !== null) {
// BB10
exportDirectory = cordova.file.sharedDirectory;
} else if (cordova.file.externalRootDirectory !== null) {
// Android, BB10
exportDirectory = cordova.file.externalRootDirectory;
} else {
// Android
exportDirectory = cordova.file.externalDataDirectory;
}
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.resolveLocalFileSystemURL(exportDirectory, function (directoryEntry) {
console.log("Got directoryEntry.");
directoryEntry.getFile(filename, {create: true}, function (fileEntry) {
console.log("Got fileEntry for: " + filename);
fileEntry.createWriter(function (fileWriter) {
console.log("Got fileWriter");
writer = fileWriter;
// now export based on the specified format
switch (format) {
case FileTypeEnum.TXT:
exportText();
break;
case FileTypeEnum.USFM:
exportUSFM();
break;
case FileTypeEnum.USX:
exportUSX();
break;
case FileTypeEnum.XML:
exportXML();
break;
}
}, exportFail);
}, exportFail);
}, exportFail);
} else {
// browser
var requestedBytes = 10 * 1024 * 1024; // 10MB
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
navigator.webkitPersistentStorage.requestQuota(requestedBytes, function (grantedBytes) {
window.requestFileSystem(window.PERSISTENT, grantedBytes, function (fs) {
fs.root.getFile(filename, {create: true}, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
console.log("Got fileWriter");
writer = fileWriter;
// now export based on the specified format
switch (format) {
case FileTypeEnum.TXT:
exportText();
break;
case FileTypeEnum.USFM:
exportUSFM();
break;
case FileTypeEnum.USX:
exportUSX();
break;
case FileTypeEnum.XML:
exportXML();
break;
}
}, exportFail);
}, exportFail);
}, exportFail);
}, exportFail);
}
},
// ****************************************
// END static methods
// ****************************************
// ImportDocumentView
// Select and import documents (txt, usfm, sfm, usx, xml) into
// AIM from the device or PC, depending on where AIM is run from.
ImportDocumentView = Marionette.ItemView.extend({
template: Handlebars.compile(tplImportDoc),
initialize: function () {
document.addEventListener("resume", this.onResume, false);
this.bookList = new bookModel.BookCollection();
},
////
// Event Handlers
////
events: {
"change #selFile": "browserImportDocs",
"click .topcoat-list__item": "mobileImportDocs",
"click #OK": "onOK"
},
// Resume handler -- user placed the app in the background, then resumed.
// Assume the file list could have changed, and reload this page
onResume: function () {
// refresh the view
Backbone.history.loadUrl(Backbone.history.fragment);
},
// Handler for when the user clicks the Select button (browser only) -
// (this is the html <input type=file> element displayed for the browser only) --
// file selections are returned by the browser in the event.currentTarget.files array
browserImportDocs: function (event) {
var fileindex = 0;
var files = event.currentTarget.files;
fileCount = files.length;
// each of the files items is a file object already; there's no need to use
// the file plugin like we need to below. Just call importFile() directly.
while (fileindex < fileCount) {
importFile(files[fileindex], this.model);
fileindex++;
}
},
// Handler for the when the user clicks a document in the list to import (mobile only) -
// we gather the file path from the selection, then reconstitute file objects
// from the path using the cordova-plugin-file / filesystem API.
mobileImportDocs: function (event) {
// replace the selection UI with the import UI
$("#mobileSelect").html(Handlebars.compile(tplLoadingPleaseWait));
$("#OK").hide();
// find all the selected file
var index = $(event.currentTarget).attr('id').trim();
var model = this.model;
console.log("index: " + index + ", FileList[index]: " + fileList[index]);
// request the persistent file system
window.resolveLocalFileSystemURL(fileList[index],
function (entry) {
entry.file(
function (file) {
$("#status").html(i18n.t("view.dscStatusReading", {document: file.name}));
importFile(file, model);
},
function (error) {
console.log("FileEntry.file error: " + error.code);
}
);
},
function (error) {
console.log("resolveLocalFileSystemURL error: " + error.code);
});
},
// Handler for the OK button -- just returns to the home screen.
onOK: function (event) {
// save the model
this.model.save();
window.Application.currentProject = this.model;
// head back to the home page
window.history.back();
},
// Show event handler (from MarionetteJS):
// - if we're running in a mobile device, we'll use the cordova-plugin-file
// API to search through the device directories and add any valid files
// to a table grid
// - If we're in a browser, just show the html <input type=file> to allow
// for file selection
onShow: function () {
// $("#selFile").attr("accept", ".xml,.usfm");
$("#title").html(i18n.t('view.lblImportDocuments'));
$("#lblDirections").html(i18n.t('view.dscImportDocuments'));
$(".topcoat-progress-bar").hide();
$("#OK").attr("disabled", true);
// build the regular expression to identify punctuation
// (this allows us to split out punctuation as separate tokens when importing
punctExp = "[\\s";
this.model.get('PunctPairs').forEach(function (elt, idx, array) {
// Unicode-encoded punctuation, formatted to get leading 00 padding (e.g., \U0065 for "a"),
// each punctuation marker is bound in "capturing parentheses", meaning that
// the punctuation itself is kept as a separate token in the array when we perform our split() call.
// Note that we have to do a charCodeAt(), which returns the decimal value of the unicode char,
// then convert it to hex using toString(16).
puncts.push(elt.s);
punctExp += "(\\u" + ("000" + elt.s.charCodeAt(0).toString(16)).slice(-4) + ")";
});
punctExp += "]+"; // one or more of ANY of the above will trigger a new token
// load the source / target case pairs
this.model.get('CasePairs').forEach(function (elt, idx, array) {
caseSource.push(elt.s);
caseTarget.push(elt.t);
});
// instantiate the KB in case we import an AI XML document (we'll populate the KB if that happens)
kblist = new kbModels.TargetUnitCollection();
kblist.fetch({reset: true, data: {source: ""}});
// cheater way to tell if running on mobile device
if (window.sqlitePlugin) {
// running on device -- use cordova file plugin to select file
$("#browserGroup").hide();
$("#mobileSelect").html(Handlebars.compile(tplLoadingPleaseWait));
var localURLs = [
cordova.file.dataDirectory,
cordova.file.documentsDirectory,
cordova.file.externalRootDirectory,
cordova.file.sharedDirectory,
cordova.file.syncedDataDirectory
];
var DirsRemaining = localURLs.length;
var index = 0;
var i;
var statusStr = "";
var addFileEntry = function (entry) {
var dirReader = entry.createReader();
dirReader.readEntries(
function (entries) {
var fileStr = "";
var i;
for (i = 0; i < entries.length; i++) {
if (entries[i].isDirectory === true) {
// Recursive -- call back into this subdirectory
addFileEntry(entries[i]);
} else {
console.log(entries[i].fullPath);
if (entries[i].fullPath.indexOf("Download") > 0 || entries[i].fullPath.indexOf("Document") > 0 || entries[i].fullPath.lastIndexOf('/') === 0) {
// only take files from the Download or Document directories
if ((entries[i].name.indexOf(".txt") > 0) ||
(entries[i].name.indexOf(".usx") > 0) ||
(entries[i].name.indexOf(".usfm") > 0) ||
(entries[i].name.indexOf(".sfm") > 0) ||
(entries[i].name.indexOf(".xml") > 0)) {
fileList[index] = entries[i].toURL();
fileStr += "<li class='topcoat-list__item' id=" + index + ">" + entries[i].fullPath + "<span class='chevron'></span></li>";
// fileStr += "<tr><td><label class='topcoat-checkbox'><input class='c' type='checkbox' id='" + index + "'><div class='topcoat-checkbox__checkmark'></div></label><td><span class='n'>" + entries[i].fullPath + "</span></td></tr>";
index++;
}
}
}
}
statusStr += fileStr;
DirsRemaining--;
if (DirsRemaining <= 0) {
if (statusStr.length > 0) {
$("#mobileSelect").html("<div class='wizard-instructions'>" + i18n.t('view.dscImportDocuments') + "</div><div class='topcoat-list__container chapter-list'><ul class='topcoat-list__container chapter-list'>" + statusStr + "</ul></div>");
// $("#mobileSelect").html("<table class=\"topcoat-table\"><colgroup><col style=\"width:2.5rem;\"><col></colgroup><thead><tr><th></th><th>" + i18n.t('view.lblName') + "</th></tr></thead><tbody id=\"tb\"></tbody></table><div><button class=\"topcoat-button\" id=\"Import\" disabled>" + i18n.t('view.lblImport') + "</button></div>");
$("#tb").html(statusStr);
$("#OK").attr("disabled", true);
} else {
// nothing to select -- inform the user
$("#mobileSelect").html("<span class=\"topcoat-notification\">!</span> <em>" + i18n.t('view.dscNoDocumentsFound') + "</em>");
$("#OK").removeAttr("disabled");
}
}
},
function (error) {
console.log("readEntries error: " + error.code);
statusStr += "<p>readEntries error: " + error.code + "</p>";
}
);
};
var addError = function (error) {
console.log("getDirectory error: " + error.code);
statusStr += "<p>getDirectory error: " + error.code + ", " + error.message + "</p>";
};
for (i = 0; i < localURLs.length; i++) {
if (localURLs[i] !== null && localURLs[i].length > 0) {
window.resolveLocalFileSystemURL(localURLs[i], addFileEntry, addError);
} else {
DirsRemaining--;
}
}
} else {
// running in browser -- use html <input> to select file
$("#mobileSelect").hide();
}
}
}),
ExportDocumentView = Marionette.ItemView.extend({
template: Handlebars.compile(tplExportDoc),
initialize: function () {
document.addEventListener("resume", this.onResume, false);
},
////
// Event Handlers
////
events: {
"click .topcoat-list__item": "selectDoc",
"change .topcoat-radio-button": "changeType",
"click #OK": "onOK",
"click #Cancel": "onCancel"
},
// Resume handler -- user placed the app in the background, then resumed.
// Assume the file list could have changed, and reload this page
onResume: function () {
// refresh the view
Backbone.history.loadUrl(Backbone.history.fragment);
},
// User changed the export format type. Add the appropriate extension
changeType: function (event) {
// strip any existing trailing extension from the filename
var filename = $("#Filename").val().trim();
if (filename.length > 0) {
if ((filename.indexOf(".xml") > -1) || (filename.indexOf(".txt") > -1) || (filename.indexOf(".sfm") > -1) || (filename.indexOf(".usx") > -1)) {
filename = filename.substr(0, filename.length - 4);
}
}
// get the desired format
if ($("#exportXML").is(":checked")) {
filename += ".xml";
} else if ($("#exportUSX").is(":checked")) {
filename += ".usx";
} else if ($("#exportUSFM").is(":checked")) {
filename += ".sfm";
} else {
// fallback to plain text
filename += ".txt";
}
// replace the filename text
$("#Filename").val(filename);
},
// User clicked the OK button. Export the selected document to the specified format.
onOK: function (event) {
if ($("#exportXML").length === 0) {
// if this is the export complete page,
// go back to the previous page
window.history.go(-1);
} else {
var format = FileTypeEnum.TXT;
var filename = $("#Filename").val().trim();
// validate input
if (filename.length === 0) {
// user didn't type anything in
// just tell them to enter something
if (navigator.notification) {
// on mobile device -- use notification plugin API
navigator.notification.alert(i18n.t('view.errNoFilename'));
} else {
// in browser -- use window.confirm / window.alert
alert(i18n.t('view.errNoFilename'));
}
$("#Filename").focus();
} else {
// get the desired format
if ($("#exportXML").is(":checked")) {
format = FileTypeEnum.XML;
} else if ($("#exportUSX").is(":checked")) {
format = FileTypeEnum.USX;
} else if ($("#exportUSFM").is(":checked")) {
format = FileTypeEnum.USFM;
} else {
// fallback to plain text
format = FileTypeEnum.TXT;
}
// update the UI
$("#mobileSelect").html(Handlebars.compile(tplLoadingPleaseWait));
$("#loading").html(i18n.t("view.lblExportingPleaseWait"));
$("#status").html(i18n.t("view.dscExporting", {file: filename}));
$("#OK").hide();
// perform the export
exportDocument(bookid, format, filename);
}
}
},
// User clicked the Cancel button. Here we don't do anything -- just return
onCancel: function (event) {
// go back to the previous page
window.history.go(-1);
},
selectDoc: function (event) {
// get the info for this document
bookName = event.currentTarget.innerText;
bookid = $(event.currentTarget).attr('id').trim();
// show the next screen
$("#lblDirections").html(i18n.t('view.lblDocSelected') + bookName);
$("#Container").html(Handlebars.compile(tplExportFormat));
// select a default of TXT for the export format (for now)
$("#exportTXT").prop("checked", true);
$("#Filename").val(bookName + ".txt");
},
onShow: function () {
var list = "";
var pid = this.model.get('projectid');
$.when(window.Application.BookList.fetch({reset: true, data: {name: ""}}).done(function () {
list = buildDocumentList(pid);
$("#Container").html("<ul class='topcoat-list__container chapter-list'>" + list + "</ul>");
$('#lblDirections').html(i18n.t('view.lblExportSelectDocument'));
}));
}
});
return {
ImportDocumentView: ImportDocumentView,
ExportDocumentView: ExportDocumentView
};
});
| www/js/views/DocumentViews.js | /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define(function (require) {
"use strict";
var $ = require('jquery'),
Underscore = require('underscore'),
Handlebars = require('handlebars'),
Backbone = require('backbone'),
Marionette = require('marionette'),
i18n = require('i18n'),
tplLoadingPleaseWait = require('text!tpl/LoadingPleaseWait.html'),
tplImportDoc = require('text!tpl/CopyOrImport.html'),
tplExportDoc = require('text!tpl/Export.html'),
tplExportFormat = require('text!tpl/ExportChooseFormat.html'),
projModel = require('app/models/project'),
bookModel = require('app/models/book'),
spModel = require('app/models/sourcephrase'),
chapModel = require('app/models/chapter'),
kbModels = require('app/models/targetunit'),
scrIDs = require('utils/scrIDs'),
USFM = require('utils/usfm'),
kblist = null, // populated in onShow
bookName = "",
scrID = "",
lines = [],
fileList = [],
fileCount = 0,
punctExp = "",
bookid = "",
puncts = [],
caseSource = [],
caseTarget = [],
deferreds = [],
MAX_BATCH = 10000, // maximum transaction size for SQLite
// (number can be tuned if needed - this is to avoid memory issues - see issue #138)
FileTypeEnum = {
TXT: 1,
USFM: 2,
USX: 3,
XML: 4
},
// Helper method to build an html list of documents in the AIM database.
// Used by ExportDocument.
buildDocumentList = function (pid) {
var str = "";
var i = 0;
var entries = window.Application.BookList.where({projectid: pid});
for (i = 0; i < entries.length; i++) {
str += "<li class='topcoat-list__item' id=" + entries[i].attributes.bookid + ">" + entries[i].attributes.name + "<span class='chevron'></span></li>";
}
return str;
},
// Helper method to store the specified source and target text in the KB.
saveInKB = function (sourceValue, targetValue, oldTargetValue, projectid) {
var elts = kblist.filter(function (element) {
return (element.attributes.projectid === projectid &&
element.attributes.source === sourceValue);
});
var tu = null,
curDate = new Date(),
timestamp = (curDate.getFullYear() + "-" + (curDate.getMonth() + 1) + "-" + curDate.getDay() + "T" + curDate.getUTCHours() + ":" + curDate.getUTCMinutes() + ":" + curDate.getUTCSeconds() + "z");
if (elts.length > 0) {
tu = elts[0];
}
if (tu) {
var i = 0,
found = false,
refstrings = tu.get('refstring');
// delete or decrement the old value
if (oldTargetValue.length > 0) {
// there was an old value -- try to find and remove the corresponding KB entry
for (i = 0; i < refstrings.length; i++) {
if (refstrings[i].target === oldTargetValue) {
if (refstrings[i].n !== '0') {
// more than one refcount -- decrement it
refstrings[i].n--;
}
break;
}
}
}
// add or increment the new value
for (i = 0; i < refstrings.length; i++) {
if (refstrings[i].target === targetValue) {
refstrings[i].n++;
found = true;
break;
}
}
if (found === false) {
// no entry in KB with this source/target -- add one
var newRS = {
'target': targetValue,
'n': '1'
};
refstrings.push(newRS);
}
// sort the refstrings collection on "n" (refcount)
refstrings.sort(function (a, b) {
// high to low
return parseInt(b.n, 10) - parseInt(a.n, 10);
});
// update the KB model
tu.set('refstring', refstrings, {silent: true});
tu.set('timestamp', timestamp, {silent: true});
tu.update();
} else {
// no entry in KB with this source -- add one
var newID = Underscore.uniqueId(),
newTU = new kbModels.TargetUnit({
tuid: newID,
projectid: projectid,
source: sourceValue,
refstring: [
{
target: targetValue,
n: "1"
}
],
timestamp: timestamp,
user: ""
});
kblist.add(newTU);
newTU.save();
}
},
// Helper method to import the selected file into the specified project.
// This method has sub-methods for text, usfm, usx and xml (Adapt It document) file types.
importFile = function (file, project) {
var status = "";
var reader = new FileReader();
var i = 0;
var name = "";
var doc = null;
var result = false;
var errMsg = "";
var sps = [];
// Callback for when the file is imported / saved successfully
var importSuccess = function () {
console.log("importSuccess()");
// update status
$("#status").html(i18n.t("view.dscStatusImportSuccess", {document: file.name}));
if ($("#loading").length) {
// mobile "please wait" UI
$("#loading").hide();
$("#waiting").hide();
$("#OK").show();
}
// display the OK button
$("#OK").removeAttr("disabled");
};
// Callback for when the file failed to import
var importFail = function (e) {
console.log("importFail(): " + e.message);
// update status
$("#status").html(i18n.t("view.dscCopyDocumentFailed", {document: file.name, reason: e.message}));
if ($("#loading").length) {
// mobile "please wait" UI
$("#loading").hide();
$("#waiting").hide();
$("#OK").show();
}
// display the OK button
$("#OK").removeAttr("disabled");
};
// callback method for when the FileReader has finished loading in the file
reader.onloadend = function (e) {
var value = "",
scrID = null,
bookName = "",
chap = 0,
verse = 0,
s = "",
t = "",
index = 0,
norder = 1,
markers = "",
orig = null,
prepuncts = "",
midpuncts = "",
follpuncts = "",
newSP = null,
punctIdx = 0,
chapter = null,
book = null,
books = window.Application.BookList,
chapters = window.Application.ChapterList,
sourcePhrases = new spModel.SourcePhraseCollection(),
arr = [],
bookID = "",
chapterID = "",
spID = "";
///
// FILE TYPE READERS
///
// Plain Text document
// We assume these are just text with no markup,
// in a single chapter (this could change if needed)
var readTextDoc = function (contents) {
var re = /\s+/;
var newline = new RegExp('[\n\r\f\u2028\u2029]+', 'g');
var prepunct = "";
var follpunct = "";
var needsNewLine = false;
var chaps = [];
var sp = null;
console.log("Reading text file:" + file.name);
index = 1;
bookName = file.name;
bookID = Underscore.uniqueId();
// Create the book and chapter
book = new bookModel.Book({
bookid: bookID,
projectid: project.get('projectid'),
name: bookName,
filename: file.name,
chapters: []
});
books.add(book);
// (for now, just one chapter -- eventually we could chunk this out based on file size)
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: bookName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// set the lastDocument / lastAdapted<xxx> values if not already set
if (project.get('lastDocument') === "") {
project.set('lastDocument', bookName);
}
if (project.get('lastAdaptedBookID') === 0) {
project.set('lastAdaptedBookID', bookID);
project.set('lastAdaptedChapterID', chapterID);
}
if (project.get('lastAdaptedName') === "") {
project.set('lastAdaptedName', bookName);
}
// parse the text file and create the SourcePhrases
arr = contents.replace(newline, " <p> ").split(re); // insert special <p> for linefeeds, then split on whitespace
// arr = contents.split(re);
i = 0;
while (i < arr.length) {
// check for a marker
if (arr[i].length === 0) {
// nothing in this token -- skip
i++;
} else if (arr[i] === "<p>") {
// newline -- make a note and keep going
markers = "\\p";
i++;
} else if (arr[i].length === 1 && puncts.indexOf(arr[i]) > -1) {
// punctuation token -- add to the prepuncts
prepuncts += arr[i];
i++;
} else {
// "normal" sourcephrase token
s = arr[i];
// look for leading and trailing punctuation
// leading...
if (puncts.indexOf(arr[i].charAt(0)) > -1) {
// leading punct
punctIdx = 0;
while (puncts.indexOf(arr[i].charAt(punctIdx)) > -1 && punctIdx < arr[i].length) {
prepuncts += arr[i].charAt(punctIdx);
punctIdx++;
}
// remove the punctuation from the "source" of the substring
s = s.substr(punctIdx);
}
if (s.length === 0) {
// it'a ALL punctuation -- jump to the next token
i++;
} else {
// not all punctuation -- check following punctuation, then create a sourcephrase
if (puncts.indexOf(s.charAt(s.length - 1)) > -1) {
// trailing punct
punctIdx = s.length - 1;
while (puncts.indexOf(s.charAt(punctIdx)) > -1 && punctIdx > 0) {
follpuncts += s.charAt(punctIdx);
punctIdx--;
}
// remove the punctuation from the "source" of the substring
s = s.substr(0, punctIdx + 1);
}
// Now create a new sourcephrase
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: prepuncts,
midpuncts: midpuncts,
follpuncts: follpuncts,
source: s,
target: ""
});
markers = "";
prepuncts = "";
follpuncts = "";
punctIdx = 0;
index++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
i++;
norder++;
}
}
}
// add any remaining sourcephrases
if ((sps.length % MAX_BATCH) > 0) {
$("#status").html(i18n.t("view.dscStatusSaving"));
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - (sps.length % MAX_BATCH))));
}
// track all those deferred calls to addBatch -- when they all complete, report the results to the user
$.when.apply($, deferreds).done(function (value) {
importSuccess();
}).fail(function (e) {
importFail(e);
});
// for non-scripture texts, there are no verses. Keep track of how far we are by using a
// negative value for the # of SourcePhrases in the text.
chapter.set('versecount', -(index), {silent: true});
chapter.save();
book.set('chapters', chaps, {silent: true});
book.save();
return true; // success
// END readTextDoc()
};
// Paratext USX document
// These are XML-flavored markup files exported from Paratext
var readUSXDoc = function (contents) {
var prepunct = "";
var follpunct = "";
var sp = null;
var re = /\s+/;
var chaps = [];
var xmlDoc = $.parseXML(contents);
var $xml = $(xmlDoc);
var chapterName = "";
// find the USFM ID of this book
var scrIDList = new scrIDs.ScrIDCollection();
var verseCount = 0;
var punctIdx = 0;
var lastAdapted = 0;
var firstChapterID = "";
var innerText = "";
var i = 0;
var tmpVal = null;
var closingMarker = "";
var parseNode = function (element) {
closingMarker = "";
// process the node itself
if ($(element)[0].nodeType === 1) {
switch ($(element)[0].tagName) {
case "book":
markers += "\\id " + element.attributes.item("code").nodeValue;
break;
case "chapter":
if (markers.length > 0) {
markers += " ";
}
markers += "\\c " + element.attributes.item("number").nodeValue;
if (element.attributes.item("number").nodeValue !== "1") {
// not the first chapter
// first, close out the previous chapter
chapter.set('versecount', verseCount, {silent: true});
chapter.save();
verseCount = 0; // reset for the next chapter
lastAdapted = 0; // reset for the next chapter
// now create the new chapter
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: element.attributes.item("number").nodeValue});
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
}
break;
case "verse":
verseCount++;
if (markers.length > 0) {
markers += " ";
}
markers += "\\v " + element.attributes.item("number").nodeValue;
break;
case "para":
// the para kind is in the style tag
if (markers.length > 0) {
markers += " ";
}
markers += "\\" + element.attributes.item("style").nodeValue;
break;
case "char":
// char-related markers, kept in the style attribute
if (markers.length > 0) {
markers += " ";
}
markers += "\\" + element.attributes.item("style").nodeValue;
break;
case "figure":
break;
case "note":
//caller, style
if (markers.length > 0) {
markers += " ";
}
markers += "\\" + element.attributes.item("style").nodeValue;
if (element.attributes.item("caller")) {
markers += " " + element.attributes.item("caller").nodeValue;
}
closingMarker = "\\" + element.attributes.item("style").nodeValue + "*";
break;
case "reference":
break;
default: // no processing for other nodes
break;
}
}
// If this is a text node, create any needed sourcephrases
if ($(element)[0].nodeType === 3) {
// Split the text into an array
// Note that this is analogous to the AI "strip" of text, and not the whole document
arr = ($(element)[0].nodeValue).trim().split(re);
i = 0;
while (i < arr.length) {
// check for a marker
if (arr[i].length === 0) {
// nothing in this token -- skip
i++;
} else if (arr[i].length === 1 && puncts.indexOf(arr[i]) > -1) {
// punctuation token -- add to the prepuncts
prepuncts += arr[i];
i++;
} else {
// "normal" sourcephrase token
s = arr[i];
// look for leading and trailing punctuation
// leading...
if (puncts.indexOf(arr[i].charAt(0)) > -1) {
// leading punct
punctIdx = 0;
while (puncts.indexOf(arr[i].charAt(punctIdx)) > -1 && punctIdx < arr[i].length) {
prepuncts += arr[i].charAt(punctIdx);
punctIdx++;
}
// remove the punctuation from the "source" of the substring
s = s.substr(punctIdx);
}
if (s.length === 0) {
// it'a ALL punctuation -- jump to the next token
i++;
} else {
// not all punctuation -- check following punctuation, then create a sourcephrase
if (puncts.indexOf(s.charAt(s.length - 1)) > -1) {
// trailing punct
punctIdx = s.length - 1;
while (puncts.indexOf(s.charAt(punctIdx)) > -1 && punctIdx > 0) {
follpuncts += s.charAt(punctIdx);
punctIdx--;
}
// remove the punctuation from the "source" of the substring
s = s.substr(0, punctIdx + 1);
}
// Now create a new sourcephrase
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: prepuncts,
midpuncts: midpuncts,
follpuncts: follpuncts,
source: s,
target: ""
});
markers = "";
prepuncts = "";
follpuncts = "";
punctIdx = 0;
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
i++;
}
}
}
}
// recurse into children
if ($(element).contents().length > 0) {
$(element).contents().each(function (idx, elt) {
parseNode(elt);
});
}
};
console.log("Reading USX file:" + file.name);
bookName = file.name.substr(0, file.name.indexOf("."));
scrIDList.fetch({reset: true, data: {id: ""}});
// the book ID (e.g., "MAT") is in a singleton <book> element of the USX file
scrID = scrIDList.where({id: $($xml).find("book").attr("code")})[0];
if (scrID === null) {
console.log("No ID matching this document: " + $($xml).find("book").attr("code"));
errMsg = i18n.t("view.dscErrCannotFindID");
return false;
}
arr = scrID.get('chapters');
if (books.where({scrid: (scrID.get('id'))}).length > 0) {
// this book is already in the list -- just return
errMsg = i18n.t("view.dscErrDuplicateFile");
return false;
}
index = 1;
bookID = Underscore.uniqueId();
// Create the book and chapter
book = new bookModel.Book({
bookid: bookID,
projectid: project.get('projectid'),
scrid: scrID.get('id'),
name: bookName,
filename: file.name,
chapters: []
});
books.add(book);
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: "1"});
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// set the lastDocument / lastAdapted<xxx> values if not already set
if (project.get('lastDocument') === "") {
project.set('lastDocument', bookName);
}
if (project.get('lastAdaptedBookID') === 0) {
project.set('lastAdaptedBookID', bookID);
project.set('lastAdaptedChapterID', chapterID);
}
if (project.get('lastAdaptedName') === "") {
project.set('lastAdaptedName', chapterName);
}
// now read the contents of the file
parseNode($($xml).find("usx"));
// add any remaining sourcephrases
if ((sps.length % MAX_BATCH) > 0) {
$("#status").html(i18n.t("view.dscStatusSaving"));
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - (sps.length % MAX_BATCH))));
}
// track all those deferred calls to addBatch -- when they all complete, report the results to the user
$.when.apply($, deferreds).done(function (value) {
importSuccess();
}).fail(function (e) {
importFail(e);
});
// update the last chapter's verseCount
chapter.set('versecount', verseCount, {silent: true});
chapter.save();
book.set('chapters', chaps, {silent: true});
book.save();
return true; // success
// END readUSXDoc()
};
// Adapt It XML document
// While XML is a general purpose document format, we're looking
// specifically for Adapt It XML document files; other files
// will be skipped (for now).
// This import also populates the KB and sets the last translated verse in each chapter.
var readXMLDoc = function (contents) {
var prepunct = "";
var re = /\s+/;
var follpunct = "";
var sp = null;
var chaps = [];
var xmlDoc = $.parseXML(contents);
var chapterName = "";
// find the USFM ID of this book
var scrIDList = new scrIDs.ScrIDCollection();
var verseCount = 0;
var lastAdapted = 0;
var firstChapterID = "";
var markers = "";
var firstChapterNumber = "1";
var i = 0;
var firstBook = false;
var isMergedDoc = false;
// helper method to convert html color values to the Adapt It color string:
// .html --> #rrggbb (in hex)
// Adapt It --> 0x00bbggrr (in base 10)
// var setColorValue = function (strValue) {
// var hexValue = parseInt(strValue, 16);
// var rValue = ("00" + (hexValue & 0xff).toString(16)).slice(-2);
// var gValue = ("00" + ((hexValue >> 8) & 0xff).toString(16)).slice(-2);
// var bValue = ("00" + ((hexValue >> 16) & 0xff).toString(16)).slice(-2);
// // format in html hex, padded with leading zeroes
// var theValue = "0x00" + bValue + gValue + rValue;
// return theValue;
// };
// Helper method to convert theString to lower case using either the source or target case equivalencies.
var autoRemoveCaps = function (theString, isSource) {
var i = 0,
result = "";
// If we aren't capitalizing for this project, just return theString
if (project.get('AutoCapitalization') === 'false') {
return theString;
}
// is the first letter capitalized?
if (isSource === true) {
// use source case equivalencies
for (i = 0; i < caseSource.length; i++) {
if (caseSource[i].charAt(1) === theString.charAt(0)) {
// uppercase -- convert the first character to lowercase and return the result
result = caseSource[i].charAt(0) + theString.substr(1);
return result;
}
}
} else {
// use target case equivalencies
for (i = 0; i < caseTarget.length; i++) {
if (caseTarget[i].charAt(1) === theString.charAt(0)) {
// uppercase -- convert the first character to lowercase and return the result
result = caseTarget[i].charAt(0) + theString.substr(1);
return result;
}
}
}
// If we got here, the string wasn't uppercase -- just return the same string
return theString;
};
console.log("Reading XML file:" + file.name);
bookName = ""; // reset
// Book name
// Try to get the adapted book name from the \h marker, if it exists
if (contents.indexOf("\\h ") > 0) {
// there is a \h marker -- look backwards for the nearest "a" attribute (this is the adapted name)
index = contents.indexOf("\\h ");
i = contents.lastIndexOf("s=", index) + 3;
// Sanity check -- this \\h element might not have an adaptation
// (if it doesn't, there won't be a a="" after the s="" attribute)
if (contents.lastIndexOf("a=", index) > i) {
// Okay, this looks legit. Pull out the adapted book name from the file.
index = contents.lastIndexOf("a=", index) + 3;
bookName = contents.substr(index, contents.indexOf("\"", index) - index);
}
}
// If that didn't work, use the filename
if (bookName === "") {
bookName = file.name.substr(0, file.name.indexOf("."));
if (bookName.indexOf("_Collab") > -1) {
// Collab document -- strip out the _Collab_ and _CH<#> for the name
bookName = bookName.substr(8, bookName.lastIndexOf("_CH") - 8);
}
}
// Sanity check -- this needs to be an AI XML document (we don't support other xml files right now)
scrIDList.fetch({reset: true, data: {id: ""}});
// Starting at the SourcePhrases ( <S ...> ), look for the \id element
// in the markers. We'll test this against the canonical usfm markers to learn more about this document.
i = contents.indexOf("<S ");
index = contents.indexOf("\\id", i);
if (index === -1) {
// No ID found -- this is most likely not an AI xml document.
// Return; we can't parse random xml files.
console.log("No ID element found (is this an AI XML document?) -- exiting.");
errMsg = i18n.t("view.dscErrCannotFindID");
return false;
}
// We've found the \id element in the markers -- to get the value, we have to work
// backwards until we find the nearest "s" attribute
// e.g., <S s="MAT" ...>.
index = contents.lastIndexOf("s=", index) + 3;
scrID = scrIDList.where({id: contents.substr(index, contents.indexOf("\"", index) - index)})[0];
arr = scrID.get('chapters');
if (books.where({scrid: (scrID.get('id'))}).length > 0) {
// ** COLLABORATION SUPPORT **
// This book is already in our database -
// it could either be a duplicate book / file OR a different chapter from a
// collaboration document. Figure out which by finding the first chapter marker
// and seeing if it's already in our database
book = books.where({scrid: (scrID.get('id'))})[0]; // set to the existing book
index = contents.indexOf("\\c ", 0); // first chapter marker
if (index > 0) {
// pull out the chapter number
firstChapterNumber = contents.substr(index + 3, contents.indexOf(" ", index + 3) - (index + 3));
if (firstChapterNumber === "1") {
firstBook = true;
}
// look up the chapter number -- is it something we already have?
chapterName = i18n.t("view.lblChapterName", {bookName: book.get("bookid"), chapterNumber: firstChapterNumber});
if (chapters.where({name: chapterName}).length > 0) {
// This is a duplicate -- return
errMsg = i18n.t("view.dscErrDuplicateFile");
return false;
}
// If we got this far, we're looking at a collaboration document -
// we'll be merging in the new data into the existing book
isMergedDoc = true;
if (firstBook === true) {
// The user has merged in the first chapter AFTER importing a subsequent chapter --
// this shouldn't happen (see the logic block below that disallows it). Just in case,
// try to offset the damage by updating the book name to what this chapter holds.
book.set('name', bookName);
} else {
// Not the first chapter -- use the book name in the database object.
bookName = book.get("name");
}
bookID = book.get("bookid");
chaps = book.get("chapters"); // set to the chapters already imported in the book (we'll add to this array)
} else {
// No chapter found (but there is an ID) -- return
errMsg = i18n.t("view.dscErrCannotFindChapter");
return false;
}
} else {
// This is a new book
// Make a note of the first chapter number. Disallow collab documents where the first chapter is
// NOT the first document being imported, as this creates a headache for book naming / lookups.
index = contents.indexOf("\\c ", 0); // first chapter marker
if (index > 0) {
// pull out the chapter number
firstChapterNumber = contents.substr(index + 3, contents.indexOf(" ", index + 3) - (index + 3));
if (firstChapterNumber === "1") {
firstBook = true;
} else {
// User attempting to import collab document without importing the first chapter first;
// error out
errMsg = i18n.t("view.dscErrImportFirstChapterFirst");
return false;
}
}
// Create the book and chapter
bookID = Underscore.uniqueId();
book = new bookModel.Book({
bookid: bookID,
projectid: project.get('projectid'),
scrid: scrID.get('id'),
name: bookName,
filename: file.name,
chapters: []
});
books.add(book);
}
// Reset the index to the beginning of the file
index = 1;
// Add the first chapter
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: firstChapterNumber});
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// set the lastDocument / lastAdapted<xxx> values if not already set
if (project.get('lastDocument') === "") {
project.set('lastDocument', bookName);
}
if (project.get('lastAdaptedBookID') === 0) {
project.set('lastAdaptedBookID', bookID);
project.set('lastAdaptedChapterID', chapterID);
}
if (project.get('lastAdaptedName') === "") {
project.set('lastAdaptedName', chapterName);
}
// create the sourcephrases
var $xml = $(xmlDoc);
var stridx = 0;
var chapNum = "";
$($xml).find("S").each(function (i) {
if (i === 0 && firstBook === false) {
// merged (collaboration) documents have an extra "\id" element at the beginning of subsequent chapters;
// ignore this element and continue to the next one
return true; // jquery equivalent of continue in loop
}
// If this is a new chapter (starting for ch 2 -- chapter 1 is created above),
// create a new chapter object
markers = $(this).attr('m');
if (markers && markers.indexOf("\\c ") !== -1) {
// is this the first chapter marker? If so, ignore it (we already created it above)
stridx = markers.indexOf("\\c ") + 3;
chapNum = markers.substr(stridx, markers.indexOf(" ", stridx) - stridx);
if (chapNum !== firstChapterNumber) {
// This is not our first chapter, so we can create it
// update the last adapted for the previous chapter before closing it out
chapter.set('versecount', verseCount, {silent: true});
chapter.set('lastadapted', lastAdapted, {silent: true});
chapter.save();
verseCount = 0; // reset for the next chapter
lastAdapted = 0; // reset for the next chapter
stridx = markers.indexOf("\\c ") + 3;
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: markers.substr(stridx, markers.indexOf(" ", stridx) - stridx)});
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
// create the new chapter
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// console.log(": " + $(this).attr('s') + ", " + chapterID);
}
}
if (markers && markers.indexOf("\\v ") !== -1) {
verseCount++;
// check this sourcephrase for a target - if there is one, consider this verse adapted
// (note that we're only checking the FIRST sp of each verse, not EVERY sp in the verse)
if ($(this).attr('t')) {
lastAdapted++;
}
}
// if there are filtered text items, insert them now
if ($(this).attr('fi')) {
markers = "";
$(this).attr('fi').split(re).forEach(function (elt, index, array) {
if (elt.indexOf("~FILTER") > -1) {
// do nothing -- skip first and last elements
// console.log("filter");
} else if (elt.indexOf("\\") === 0) {
// starting marker
markers += elt;
} else if (elt.indexOf("\\") > 0) {
// ending marker - it's concatenated with the preceding token, no space
// create a sourcephrase with the first part of the token, using the marker
// from the end
markers += elt.substr(elt.indexOf("\\"));
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: $(this).attr('pp'),
midpuncts: "",
follpuncts: $(this).attr('fp'),
source: elt.substr(0, elt.indexOf("\\") - 1),
target: ""
});
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
markers = ""; // reset
} else {
// regular token - add as a new sourcephrase
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: $(this).attr('pp'),
midpuncts: "",
follpuncts: $(this).attr('fp'),
source: elt,
target: ""
});
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
markers = ""; // reset
}
});
}
// create the next sourcephrase
// console.log(i + ": " + $(this).attr('s') + ", " + chapterID);
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: $(this).attr('m'),
orig: null,
prepuncts: $(this).attr('pp'),
midpuncts: "",
follpuncts: $(this).attr('fp'),
source: $(this).attr('k'), // source w/o punctuation
target: $(this).attr('t')
});
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
// add this item to the KB
// TODO: build up punctpairs
if (sp.get('target').length > 0) {
saveInKB(autoRemoveCaps(sp.get('source'), true), autoRemoveCaps($(this).attr('a'), false),
"", project.get('projectid'));
}
});
// add any remaining sourcephrases
if ((sps.length % MAX_BATCH) > 0) {
$("#status").html(i18n.t("view.dscStatusSaving"));
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - (sps.length % MAX_BATCH))));
}
// track all those deferred calls to addBatch -- when they all complete, report the results to the user
$.when.apply($, deferreds).done(function (value) {
importSuccess();
}).fail(function (e) {
importFail(e);
});
// update the last chapter's verseCount and last adapted verse
chapter.set('lastadapted', lastAdapted, {silent: true});
chapter.set('versecount', verseCount, {silent: true});
chapter.save();
if (isMergedDoc === true) {
var chapList = [];
var number = 0;
var tmpString = "";
// If this is a merged document, the chapters might be out of order --
// sort them here
for (i = 0; i < chaps.length; i++) {
tmpString = chapters.findWhere({chapterid: chaps[i]}).get("name");
number = parseInt(tmpString.substr(tmpString.lastIndexOf(" " + 1)), 10); // just the number part
chapList.push({chapid: chaps[i], number: number});
}
var result = Underscore.sortBy(chapList, function (element) {
return element.number;
});
// transfer the sorted list back into chaps
chaps.length = 0; // clear chaps
for (i = 0; i < result.length; i++) {
chaps.push(result[i].chapid);
}
}
book.set('chapters', chaps, {silent: true});
book.save();
return true; // success
// END readXMLDoc()
};
// USFM document
// This is the file format for Bibledit and Paratext
// See http://paratext.org/about/usfm for format specification
var readUSFMDoc = function (contents) {
var scrIDList = new scrIDs.ScrIDCollection();
var chapterName = "";
var sp = null;
var re = /\s+/;
var markerList = new USFM.MarkerCollection();
var marker = null;
var lastAdapted = 0;
var verseCount = 0;
var hasPunct = false;
var punctIdx = 0;
var stridx = 0;
var chaps = [];
console.log("Reading USFM file:" + file.name);
index = contents.indexOf("\\h ");
if (index > -1) {
// get the name from the usfm itself
bookName = contents.substr(index + 3, (contents.indexOf("\n", index) - (index + 3))).trim();
} else {
bookName = file.name;
}
// find the ID of this book
index = contents.indexOf("\\id");
if (index === -1) {
// no ID found -- return
errMsg = i18n.t("view.dscErrCannotFindID");
return false;
}
markerList.fetch({reset: true, data: {name: ""}});
scrIDList.fetch({reset: true, data: {id: ""}});
scrID = scrIDList.where({id: contents.substr(index + 4, 3)})[0];
// books.fetch({reset: true, data: {name: ""}});
if (books.where({scrid: (scrID.get('id'))}).length > 0) {
// this book is already in the list -- return
errMsg = i18n.t("view.dscErrDuplicateFile");
return false;
}
// add a book and chapter
bookID = Underscore.uniqueId();
book = new bookModel.Book({
bookid: bookID,
projectid: project.get('projectid'),
scrid: scrID.get('id'),
name: bookName,
filename: file.name,
chapters: [] // arr
});
books.add(book);
// Note that we're adding chapter 1 before we reach the \c 1 marker in the file --
// Usually there's a fair amount of front matter before we reach the chapter itself;
// rather than creating a chapter 0 (which would throw off the search stuff), we'll
// just add the front matter to chapter 1.
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: "1"});
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// set the lastDocument / lastAdapted<xxx> values if not already set
if (project.get('lastDocument') === "") {
project.set('lastDocument', bookName);
}
if (project.get('lastAdaptedBookID') === 0) {
project.set('lastAdaptedBookID', bookID);
project.set('lastAdaptedChapterID', chapterID);
}
if (project.get('lastAdaptedName') === "") {
project.set('lastAdaptedName', chapterName);
}
// build SourcePhrases
arr = contents.replace(/\\/gi, " \\").split(re); // add space to make sure markers get put in a separate token
i = 0;
while (i < arr.length) {
// check for a marker
if (arr[i].indexOf("\\") === 0) {
// marker token
if (markers.length > 0) {
markers += " ";
}
markers += arr[i];
// If this is the start of a new paragraph, etc., check to see if there's a "dangling"
// punctuation mark. If so, it belongs as a follPunct of the precious SourcePhrase
if ((arr[i] === "\\p" || arr[i] === "\\c" || arr[i] === "\\v") && prepuncts.length > 0) {
sp.set("follpuncts", (sp.get("follpuncts") + prepuncts), {silent: true});
prepuncts = ""; // clear out the punctuation -- it's set on the previous sp now
}
// Check for markers with more than one token (and merge the two marker tokens)
if ((arr[i] === "\\x") || (arr[i] === "\\f") ||
(arr[i] === "\\c") || (arr[i] === "\\ca") || (arr[i] === "\\cp") ||
(arr[i] === "\\v") || (arr[i] === "\\va") || (arr[i] === "\\vp")) {
// join with the next
i++;
markers += " " + arr[i];
}
i++;
} else if (arr[i].length === 0) {
// nothing in this token -- skip
i++;
} else if (arr[i].length === 1 && puncts.indexOf(arr[i]) > -1) {
// punctuation token -- add to the prepuncts
prepuncts += arr[i];
i++;
} else if (arr[i].length === 2 && puncts.indexOf(arr[i]) > -1) {
// 2-char punctuation token -- add to the prepuncts
prepuncts += arr[i];
i++;
} else {
// "normal" sourcephrase token
// Before creating the sourcephrase, look to see if we need to create a chapter element
// (note that we've already created chapter 1, so skip it if we come across it)
if (markers && markers.indexOf("\\c ") !== -1 && markers.indexOf("\\c 1 ") === -1) {
// update the last adapted for the previous chapter before closing it out
chapter.set('versecount', verseCount, {silent: true});
chapter.set('lastadapted', lastAdapted, {silent: true});
chapter.save();
verseCount = 0; // reset for the next chapter
lastAdapted = 0; // reset for the next chapter
stridx = markers.indexOf("\\c ") + 3;
if (markers.lastIndexOf(" ") < stridx) {
// no space after the chapter # (it's the ending of the string)
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: markers.substr(stridx)});
} else {
// space after the chapter #
chapterName = i18n.t("view.lblChapterName", {bookName: bookName, chapterNumber: markers.substr(stridx, markers.indexOf(" ", stridx) - stridx)});
}
chapterID = Underscore.uniqueId();
chaps.push(chapterID);
// create the new chapter
chapter = new chapModel.Chapter({
chapterid: chapterID,
bookid: bookID,
projectid: project.get('projectid'),
name: chapterName,
lastadapted: 0,
versecount: 0
});
chapters.add(chapter);
// console.log(chapterName + ": " + chapterID);
}
// also do some processing for verse markers
if (markers && markers.indexOf("\\v ") !== -1) {
verseCount++;
// check this sourcephrase for a target - if there is one, consider this verse adapted
// (note that we're only checking the FIRST sp of each verse, not EVERY sp in the verse)
if ($(this).attr('t')) {
lastAdapted++;
}
}
s = arr[i];
// look for leading and trailing punctuation
// leading...
if (puncts.indexOf(arr[i].charAt(0)) > -1) {
// leading punct
punctIdx = 0;
while (puncts.indexOf(arr[i].charAt(punctIdx)) > -1 && punctIdx < arr[i].length) {
prepuncts += arr[i].charAt(punctIdx);
punctIdx++;
}
// remove the punctuation from the "source" of the substring
s = s.substr(punctIdx);
}
if (s.length === 0) {
// it'a ALL punctuation -- jump to the next token
i++;
} else {
// not all punctuation -- check following punctuation, then create a sourcephrase
if (puncts.indexOf(s.charAt(s.length - 1)) > -1) {
// trailing punct
punctIdx = s.length - 1;
while (puncts.indexOf(s.charAt(punctIdx)) > -1 && punctIdx > 0) {
follpuncts = s.charAt(punctIdx) + follpuncts;
punctIdx--;
}
// remove the punctuation from the "source" of the substring
s = s.substr(0, punctIdx + 1);
}
// Now create a new sourcephrase
spID = Underscore.uniqueId();
sp = new spModel.SourcePhrase({
spid: spID,
norder: norder,
chapterid: chapterID,
markers: markers,
orig: null,
prepuncts: prepuncts,
midpuncts: midpuncts,
follpuncts: follpuncts,
source: s,
target: ""
});
markers = "";
prepuncts = "";
follpuncts = "";
punctIdx = 0;
index++;
norder++;
sps.push(sp);
// if necessary, send the next batch of SourcePhrase INSERT transactions
if ((sps.length % MAX_BATCH) === 0) {
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - MAX_BATCH)));
}
i++;
}
}
}
// add any remaining sourcephrases
if ((sps.length % MAX_BATCH) > 0) {
$("#status").html(i18n.t("view.dscStatusSaving"));
deferreds.push(sourcePhrases.addBatch(sps.slice(sps.length - (sps.length % MAX_BATCH))));
}
// track all those deferred calls to addBatch -- when they all complete, report the results to the user
$.when.apply($, deferreds).done(function (value) {
importSuccess();
}).fail(function (e) {
importFail(e);
});
// update the last chapter's verseCount
chapter.set('versecount', verseCount, {silent: true});
chapter.save();
book.set('chapters', chaps, {silent: true});
book.save();
return true; // success
// END readUSFMDoc()
};
///
// END FILE TYPE READERS
///
// read doc as appropriate
if ((file.name.indexOf(".usfm") > 0) || (file.name.indexOf(".sfm") > 0)) {
result = readUSFMDoc(this.result);
} else if (file.name.indexOf(".usx") > 0) {
result = readUSXDoc(this.result);
} else if (file.name.indexOf(".xml") > 0) {
result = readXMLDoc(this.result);
} else if (file.name.indexOf(".txt") > 0) {
// .txt -- check to see if it's really USFM under the hood
// find the ID of this book
index = this.result.indexOf("\\id");
if (index >= 0) {
// _probably_ USFM under the hood -- at least try to read it as USFM
result = readUSFMDoc(this.result);
} else {
// not USFM -- try reading it as a text document
result = readTextDoc(this.result);
}
} else {
// some other extension -- try reading it as a text document
result = readTextDoc(this.result);
}
if (result === false) {
importFail(new Error(errMsg));
}
};
reader.readAsText(file);
},
// Helper method to export the given bookid to the specified file format.
// Called from ExportDocumentView::onOK once the book, format and filename have been chosen.
exportDocument = function (bookid, format, filename) {
var status = "";
var writer = null;
var errMsg = "";
var sourcephrases = null;
var exportDirectory = "";
var tabLevel = 0;
// Callback for when the file is imported / saved successfully
var exportSuccess = function () {
console.log("exportSuccess()");
// update status
$("#status").html(i18n.t("view.dscStatusExportSuccess", {document: filename}));
// display the OK button
$("#loading").hide();
$("#waiting").hide();
$("#OK").show();
$("#OK").removeAttr("disabled");
};
// Callback for when the file failed to import
var exportFail = function (e) {
console.log("exportFail(): " + e.message);
// update status
$("#status").html(i18n.t("view.dscExportFailed", {document: filename, reason: e.message}));
$("#loading").hide();
$("#waiting").hide();
// display the OK button
$("#OK").show();
$("#OK").removeAttr("disabled");
};
///
// FILE TYPE WRITERS
// 2 loops for each file type -- a chapter and source phrase loop.
// The AI XML export will dump out the entire book; the others use the following logic:
// - If the chapter has at least some adaptations in it, we'll export it
// - If we encounter the lastSPID, we'll break out of the export loop of the chapter.
// This logic works well if the user is adapting sequentially. If the user is jumping around in their adaptations,
// some chapters might have extraneous punctuation from areas where they haven't adapted.
///
// Plain Text document
// We assume these are just text with no markup,
// in a single chapter (this could change if needed)
var exportText = function () {
var chapters = window.Application.ChapterList.where({bookid: bookid});
var content = "";
var spList = new spModel.SourcePhraseCollection();
var markerList = new USFM.MarkerCollection();
var i = 0;
var idxFilters = 0;
var value = null;
var filterAry = window.Application.currentProject.get('FilterMarkers').split("\\");
var lastSPID = window.Application.currentProject.get('lastAdaptedSPID');
var chaptersLeft = chapters.length;
var filtered = false;
var needsEndMarker = "";
var mkr = "";
writer.onwriteend = function (e) {
console.log("write completed.");
if (chaptersLeft === 0) {
exportSuccess();
}
};
writer.onerror = function (e) {
console.log("write failed: " + e.toString());
exportFail(e);
};
// get the chapters belonging to our book
markerList.fetch({reset: true, data: {name: ""}});
console.log("markerList count: " + markerList.length);
lastSPID = lastSPID.substring(lastSPID.lastIndexOf("-") + 1);
console.log("filterAry: " + filterAry.toString());
chapters.forEach(function (entry) {
// for each chapter with some adaptation done, get the sourcephrases
if (entry.get('lastadapted') !== 0) {
spList.fetch({reset: true, data: {chapterid: entry.get("chapterid")}}).done(function () {
console.log("spList: " + spList.length + " items, last id = " + lastSPID);
for (i = 0; i < spList.length; i++) {
value = spList.at(i);
// plain text -- we're not all that interested in formatting, but do add some
// line breaks for chapter, verse, paragraph marks
if ((value.get("markers").indexOf("\\c") > -1) || (value.get("markers").indexOf("\\v") > -1) ||
(value.get("markers").indexOf("\\h") > -1) || (value.get("markers").indexOf("\\p") > -1)) {
content += "\n"; // newline
}
// check to see if this sourcephrase is filtered (only looking at the top level)
if (filtered === false) {
for (idxFilters = 0; idxFilters < filterAry.length; idxFilters++) {
// sanity check for blank filter strings
if (filterAry[idxFilters].trim().length > 0) {
if (value.get("markers").indexOf(filterAry[idxFilters]) >= 0) {
// this is a filtered sourcephrase -- do not export it
console.log("filtered: " + value.get("markers"));
// if there is an end marker associated with this marker,
// do not export any source phrases until we come across the end marker
mkr = markerList.where({name: filterAry[idxFilters].trim()});
if (mkr[0].get("endMarker")) {
needsEndMarker = mkr[0].get("endMarker");
}
filtered = true;
}
}
}
}
if (value.get("markers").indexOf(needsEndMarker) >= 0) {
// found our ending marker -- this sourcephrase is not filtered
needsEndMarker = "";
filtered = false;
}
if (filtered === false) {
content += value.get("prepuncts") + value.get("target") + value.get("follpuncts") + " ";
}
if (value.get('spid') === lastSPID) {
// done -- quit after this sourcePhrase
console.log("Found last SPID: " + lastSPID);
break;
}
}
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
});
}
chaptersLeft--;
});
};
// USFM document
var exportUSFM = function () {
var chapters = window.Application.ChapterList.where({bookid: bookid});
var content = "";
var spList = new spModel.SourcePhraseCollection();
var markerList = new USFM.MarkerCollection();
var markers = "";
var i = 0;
var idxFilters = 0;
var value = null;
var chaptersLeft = chapters.length;
var filtered = false;
var needsEndMarker = "";
var mkr = "";
var filterAry = window.Application.currentProject.get('FilterMarkers').split("\\");
var lastSPID = window.Application.currentProject.get('lastAdaptedSPID');
writer.onwriteend = function (e) {
console.log("write completed.");
if (chaptersLeft === 0) {
exportSuccess();
}
};
writer.onerror = function (e) {
console.log("write failed: " + e.toString());
exportFail(e);
};
markerList.fetch({reset: true, data: {name: ""}});
console.log("markerList count: " + markerList.length);
lastSPID = lastSPID.substring(lastSPID.lastIndexOf("-") + 1);
chapters.forEach(function (entry) {
// for each chapter with some adaptation done, get the sourcephrases
if (entry.get('lastadapted') !== 0) {
spList.fetch({reset: true, data: {chapterid: entry.get("chapterid")}}).done(function () {
console.log("spList: " + spList.length + " items, last id = " + lastSPID);
for (i = 0; i < spList.length; i++) {
value = spList.at(i);
markers = value.get("markers");
// check to see if this sourcephrase is filtered (only looking at the top level)
if (filtered === false) {
for (idxFilters = 0; idxFilters < filterAry.length; idxFilters++) {
// sanity check for blank filter strings
if (filterAry[idxFilters].trim().length > 0) {
if (markers.indexOf(filterAry[idxFilters]) >= 0) {
// this is a filtered sourcephrase -- do not export it
console.log("filtered: " + markers);
// however, if there are some markers before we hit our filtered one,
// make sure they get exported now
markers = markers.substr(0, markers.indexOf(filterAry[idxFilters]) - 1);
if (markers.length > 0) {
if ((markers.indexOf("\\v") > -1) || (markers.indexOf("\\c") > -1) ||
(markers.indexOf("\\p") > -1) || (markers.indexOf("\\id") > -1) ||
(markers.indexOf("\\h") > -1) || (markers.indexOf("\\toc") > -1) || (markers.indexOf("\\mt") > -1)) {
// pretty-printing -- add a newline so the output looks better
content += "\n"; // newline
}
// now add the markers and a space
content += markers + " ";
}
content += (markers.substr(0, markers.indexOf(filterAry[idxFilters]))) + " ";
// if there is an end marker associated with this marker,
// do not export any source phrases until we come across the end marker
mkr = markerList.where({name: filterAry[idxFilters].trim()});
if (mkr[0].get("endMarker")) {
needsEndMarker = mkr[0].get("endMarker");
}
filtered = true;
}
}
}
}
if ((needsEndMarker.length > 0) && (markers.indexOf(needsEndMarker) >= 0)) {
// found our ending marker -- this sourcephrase is not filtered
// first, remove the marker from the markers string so it doesn't print out
markers = markers.replace(("\\" + needsEndMarker), '');
// now clear our flags so the sourcephrase exports
needsEndMarker = "";
filtered = false;
}
if (filtered === false) {
// add markers, and if needed, pretty-print the text on a newline
if (markers.trim().length > 0) {
if ((markers.indexOf("\\v") > -1) || (markers.indexOf("\\c") > -1) || (markers.indexOf("\\p") > -1) || (markers.indexOf("\\id") > -1) || (markers.indexOf("\\h") > -1) || (markers.indexOf("\\toc") > -1) || (markers.indexOf("\\mt") > -1)) {
// pretty-printing -- add a newline so the output looks better
content += "\n"; // newline
}
// now add the markers and a space
content += markers + " ";
}
content += value.get("prepuncts") + value.get("target") + value.get("follpuncts") + " ";
}
if (value.get('spid') === lastSPID) {
// done -- quit after this sourcePhrase
console.log("Found last SPID: " + lastSPID);
break;
}
}
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
});
}
chaptersLeft--;
});
};
// USX document
var exportUSX = function () {
var chapters = window.Application.ChapterList.where({bookid: bookid});
var book = window.Application.BookList.where({bookid: bookid})[0];
var bookID = book.get('scrid');
var content = "";
var XML_PROLOG = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
var spList = new spModel.SourcePhraseCollection();
var markerList = new USFM.MarkerCollection();
var filterAry = window.Application.currentProject.get('FilterMarkers').split("\\");
var lastSPID = window.Application.currentProject.get('lastAdaptedSPID');
var filtered = false;
var needsEndMarker = "";
var markers = "";
var i = 0;
var idxFilters = 0;
var versenum = 1;
var closeNode = ""; // holds ending string for <para> and <book> XML nodes
var value = null;
var mkr = "";
var chaptersLeft = chapters.length;
writer.onwriteend = function (e) {
console.log("write completed.");
if (chaptersLeft === 0) {
exportSuccess();
}
};
writer.onerror = function (e) {
console.log("write failed: " + e.toString());
exportFail(e);
};
// starting material -- xml prolog and usx tag
content = XML_PROLOG + "\n<usx version=\"2.0\">\n";
// get the chapters belonging to our book
markerList.fetch({reset: true, data: {name: ""}});
console.log("markerList count: " + markerList.length);
lastSPID = lastSPID.substring(lastSPID.lastIndexOf("-") + 1);
chapters.forEach(function (entry) {
// for each chapter with some adaptation done, get the sourcephrases
if (entry.get('lastadapted') !== 0) {
// add a placeholder string for this chapter, so that it ends up in order (the call to
// fetch() is async, and sometimes the chapters are returned out of order)
content += "**" + entry.get("chapterid") + "**";
spList.fetch({reset: true, data: {chapterid: entry.get("chapterid")}}).done(function () {
var chapterString = "";
console.log("spList: " + spList.length + " items, last id = " + lastSPID);
for (i = 0; i < spList.length; i++) {
value = spList.at(i);
markers = value.get("markers");
// check to see if this sourcephrase is filtered (only looking at the top level)
if (filtered === false) {
for (idxFilters = 0; idxFilters < filterAry.length; idxFilters++) {
// sanity check for blank filter strings
if (filterAry[idxFilters].trim().length > 0) {
if (markers.indexOf(filterAry[idxFilters]) >= 0) {
// this is a filtered sourcephrase -- do not export it
console.log("filtered: " + markers);
// if there is an end marker associated with this marker,
// do not export any source phrases until we come across the end marker
mkr = markerList.where({name: filterAry[idxFilters].trim()});
if (mkr[0].get("endMarker")) {
needsEndMarker = mkr[0].get("endMarker");
}
filtered = true;
}
}
}
}
if ((needsEndMarker.length > 0) && (markers.indexOf(needsEndMarker) >= 0)) {
// found our ending marker -- this sourcephrase is not filtered
// first, remove the marker from the markers string so it doesn't print out
markers = markers.replace(("\\" + needsEndMarker), '');
// now clear our flags so the sourcephrase exports
needsEndMarker = "";
filtered = false;
}
if (filtered === false) {
// not filtered -- print out the text and markers
if (markers.length > 0) {
if ((markers.indexOf("\\id ")) > -1) {
chapterString += "<book code=\"" + bookID + "\" style=\"id\">";
chapterString += value.get("target");
closeNode = "</book>";
continue; // skip to the next entry
}
// TODO -- list of markers...
if (markers.indexOf("\\c ") > -1) {
if (closeNode.length > 0) {
chapterString += closeNode;
closeNode = ""; // clear it out
}
var chpos = markers.indexOf("\\c");
chapterString += "\n<chapter number=\"";
chapterString += markers.substr(chpos + 3, (markers.indexOf(" ", chpos + 3) - (chpos + 3)));
chapterString += "\" style=\"c\" />";
}
if (markers.indexOf("\\b ") > -1) {
if (closeNode.length > 0) {
chapterString += closeNode;
closeNode = ""; // clear it out
}
chapterString += "\n<para style=\"b\" />";
}
if ((markers.indexOf("\\p") > -1) || (markers.indexOf("\\q") > -1) || (markers.indexOf("\\ide") > -1) || (markers.indexOf("\\h") > -1) || (markers.indexOf("\\mt") > -1)) {
if (closeNode.length > 0) {
chapterString += closeNode;
}
chapterString += "\n<para style=\"";
if (markers.indexOf("\\p") > -1) {
chapterString += "p";
} else if (markers.indexOf("\\q") > -1) {
// extract out what kind of quote this is (e.g., "q2") - this goes in the style attribute
var qpos = markers.indexOf("\\q");
if (markers.indexOf(" ", qpos) > -1) {
chapterString += markers.substring(qpos + 1, (markers.indexOf(" ", qpos)));
} else {
chapterString += markers.substr(qpos + 1);
}
} else if (markers.indexOf("\\ide") > -1) {
chapterString += "ide";
} else if (markers.indexOf("\\h") > -1) {
chapterString += "h";
} else if (markers.indexOf("\\mt") > -1) {
// extract out what kind of major title this is (e.g., "mt2") -
// this goes in the style attribute
var mtpos = markers.indexOf("\\mt");
if (markers.indexOf(" ", mtpos) > -1) { chapterString += markers.substring(mtpos + 1, (markers.indexOf(" ", mtpos)));
} else {
chapterString += markers.substr(mtpos + 1);
}
}
chapterString += "\">";
closeNode = "</para>";
}
// if (markers.indexOf("\\+ ") > -1) {
// chapterString += "<note caller=\"+\" style=\"f\">";
// }
if (markers.indexOf("\\v ") > -1) {
var vpos = markers.indexOf("\\v ");
chapterString += "<verse number=\"";
if (markers.indexOf(" ", vpos + 3) > -1) {
chapterString += markers.substring(vpos + 3, (markers.indexOf(" ", vpos + 3)));
} else {
chapterString += markers.substr(vpos + 3);
}
chapterString += "\" style=\"v\" />";
}
}
chapterString += value.get("prepuncts") + value.get("target") + value.get("follpuncts") + " ";
}
// done dealing with the source phrase -- is it the last one?
if (value.get('spid') === lastSPID) {
// last phrase -- exit
console.log("Found last SPID: " + lastSPID);
break;
}
}
// Now take the string from this chapter's sourcephrases that we've just built and
// insert them into the correct location in the file's content string
content = content.replace(("**" + entry.get("chapterid") + "**"), chapterString);
// decrement the chapter count, closing things out if needed
chaptersLeft--;
if (chaptersLeft === 0) {
console.log("finished within sp block");
// done with the chapters
// add a closing paragraph if necessary
if (closeNode.length > 0) {
content += closeNode;
}
// add the ending node
content += "\n</usx>\n";
// ** we are now done with all the chapters -- write out the file
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
}
});
} else {
// BUGBUG: can we end up here if there are chapters?
// no sourcephrases to export -- just decrement the chapters, and close things out if needed
chaptersLeft--;
if (chaptersLeft === 0) {
console.log("finished in a blank block");
// done with the chapters
// add a closing paragraph if necessary
if (closeNode.length > 0) {
content += closeNode;
}
// add the ending node
content += "\n</usx>\n";
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
}
}
});
};
// XML document
// Note that this export is a full dump of the document, not just the parts that have been adapted.
// This is because we're exporting the source as well as the target text.
// EDB 8/13/16: partially working. Still need:
// - colors in settings node converted to AI doc format (WXWidgets) from RGB
// ..and for each SP
// - Flag bitss generated (implement buildFlags() below)
// - type enum generated (implement buildTY() below)
// - "inform" bits copied over
// -- lower priority, but need for AI compatibility: other bits implemented
var exportXML = function () {
var chapters = window.Application.ChapterList.where({bookid: bookid});
var book = window.Application.BookList.where({bookid: bookid});
var content = "";
var words = [];
var XML_PROLOG = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>";
var spList = new spModel.SourcePhraseCollection();
var markers = "";
var i = 0;
var value = null;
var atts = {
name: [],
value: []
};
var project = window.Application.currentProject;
var chaptersLeft = chapters.length;
var buildFlags = function (sourcephrase) {
// (code in XML.cpp ~ line 5568)
var val = "";
return val;
};
var buildTY = function (sourcephrase) {
// (code in SourcePhrase.h ~ line 55)
var val = "";
val = "0"; // none
return val;
};
writer.onwriteend = function (e) {
console.log("write completed.");
if (chaptersLeft === 0) {
exportSuccess();
}
};
writer.onerror = function (e) {
console.log("write failed: " + e.toString());
exportFail(e);
};
// opening content
content = XML_PROLOG;
content += "\n<!--\n Note: Using Microsoft WORD 2003 or later is not a good way to edit this xml file.\n Instead, use NotePad or WordPad. -->\n<AdaptItDoc>\n";
// Settings: AIM doesn't do per-document settings; just copy over the project settings
content += "<Settings docVersion=\"9\" bookName=\"" + bookName + "\" owner=\"";
if (window.sqlitePlugin) {
content += device.uuid;
} else {
content += "Browser";
}
content += "\" commitcnt=\"****\" revdate=\"\" actseqnum=\"0\" sizex=\"553\" sizey=\"62464\" ftsbp=\"1\"";
// colors
content += " specialcolor=\"" + project.get('SpecialTextColor') + "\" retranscolor=\"" + project.get('RetranslationColor') + "\" navcolor=\"" + project.get('NavigationColor') + "\"";
// project info
content += " curchap=\"1:\" srcname=\"" + project.get('SourceLanguageName') + "\" tgtname=\"" + project.get('TargetLanguageName') + "\" srccode=\"" + project.get('SourceLanguageCode') + "\" tgtcode=\"" + project.get('TargetLanguageCode') + "\"";
// filtering
content += " others=\"@#@#:F:-1:0:";
content += project.get('FilterMarkers');
content += "::\"/>\n";
// END settings xml node
// CONTENT PART: get the chapters belonging to our book
chapters.forEach(function (entry) {
// for each chapter (regardless of whether there's some adaptation done), get the sourcephrases
spList.fetch({reset: true, data: {chapterid: entry.get("chapterid")}}).done(function () {
for (i = 0; i < spList.length; i++) {
value = spList.at(i);
// format for <S> nodes found in CSourcePhrase::MakeXML (SourcePhrase.cpp)
// line 1 -- source, key, target, adaptation
content += "<S s=\"";
if (value.get("prepuncts").length > 0) {
content += value.get("prepuncts");
}
content += value.get("source");
if (value.get("follpuncts").length > 0) {
content += value.get("follpuncts");
}
content += "\" k=\"" + value.get("source") + "\"";
if (value.get("target").length > 0) {
content += " t=\"" + value.get("target") + "\" a=\"" + value.get("target") + "\"";
}
// line 2 -- flags, sequNumber, SrcWords, TextType
content += " f=\"" + buildFlags(value) + "\" sn=\"" + (value.get('norder') - 1);
words = value.get("source").match(/\S+/g);
if (words) {
content += "\" w=\"" + words.length + "\"";
} else {
content += "\" w=\"1\"";
}
content += " ty=\"" + buildTY(value) + "\"";
// line 3 -- 6 atts (optional)
if (value.get("prepuncts").length > 0) {
content += " pp=\"" + value.get("prepuncts") + "\"";
}
if (value.get("follpuncts").length > 0) {
content += " fp=\"" + value.get("follpuncts") + "\"";
}
markers = value.get("markers");
// inform
if (markers.indexof("\\h ") > -1) {
content += " i=\"hdr\"";
}
// if (markers.indexof("\\mt1") > -1) {
// content += " i=\"main title L1\"";
// }
// if (markers.indexof("\\imt1") > -1) {
// content += " i=\"intro major title L1\"";
// }
// if (markers.indexof("\\ip") > -1) {
// content += " i=\"intro paragraph\"";
// }
// add markers, and if needed, pretty-print the text on a newline
if (markers.indexOf("\\v") > -1) {
// add chapter/verse
content += " c=\"" + entry.get('name') + ":" + "\"";
}
// line 4 -- markers, end markers, inline binding markers, inline binding end markers,
// inline nonbinding markers, inline nonbinding end barkers
if (markers.length > 0) {
content += " m=\"" + markers + "\"";
}
// line 5-8 -- free translation, note, back translation, filtered info
// line 9 -- lapat, tmpat, gmpat, pupat
content += ">\n";
// 3 more possible info types
// medial puncts, medial markers, saved words (another <s>)
if (value.get("midpuncts").length > 0) {
content += "<MP mp=\"" + value.get("midpuncts") + "\"/>";
}
content += "</S>\n";
}
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
chaptersLeft--;
if (chaptersLeft === 0) {
// done with the chapters -- add the ending node
content += "\n</AdaptItDoc>\n";
var blob = new Blob([content], {type: 'text/plain'});
writer.write(blob);
content = ""; // clear out the content string for the next chapter
}
});
});
};
if (window.sqlitePlugin) {
// mobile device
if (cordova.file.documentsDirectory !== null) {
// iOS, OSX
exportDirectory = cordova.file.documentsDirectory;
} else if (cordova.file.sharedDirectory !== null) {
// BB10
exportDirectory = cordova.file.sharedDirectory;
} else if (cordova.file.externalRootDirectory !== null) {
// Android, BB10
exportDirectory = cordova.file.externalRootDirectory;
} else {
// Android
exportDirectory = cordova.file.externalDataDirectory;
}
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.resolveLocalFileSystemURL(exportDirectory, function (directoryEntry) {
console.log("Got directoryEntry.");
directoryEntry.getFile(filename, {create: true}, function (fileEntry) {
console.log("Got fileEntry for: " + filename);
fileEntry.createWriter(function (fileWriter) {
console.log("Got fileWriter");
writer = fileWriter;
// now export based on the specified format
switch (format) {
case FileTypeEnum.TXT:
exportText();
break;
case FileTypeEnum.USFM:
exportUSFM();
break;
case FileTypeEnum.USX:
exportUSX();
break;
case FileTypeEnum.XML:
exportXML();
break;
}
}, exportFail);
}, exportFail);
}, exportFail);
} else {
// browser
var requestedBytes = 10 * 1024 * 1024; // 10MB
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
navigator.webkitPersistentStorage.requestQuota(requestedBytes, function (grantedBytes) {
window.requestFileSystem(window.PERSISTENT, grantedBytes, function (fs) {
fs.root.getFile(filename, {create: true}, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
console.log("Got fileWriter");
writer = fileWriter;
// now export based on the specified format
switch (format) {
case FileTypeEnum.TXT:
exportText();
break;
case FileTypeEnum.USFM:
exportUSFM();
break;
case FileTypeEnum.USX:
exportUSX();
break;
case FileTypeEnum.XML:
exportXML();
break;
}
}, exportFail);
}, exportFail);
}, exportFail);
}, exportFail);
}
},
// ****************************************
// END static methods
// ****************************************
// ImportDocumentView
// Select and import documents (txt, usfm, sfm, usx, xml) into
// AIM from the device or PC, depending on where AIM is run from.
ImportDocumentView = Marionette.ItemView.extend({
template: Handlebars.compile(tplImportDoc),
initialize: function () {
document.addEventListener("resume", this.onResume, false);
this.bookList = new bookModel.BookCollection();
},
////
// Event Handlers
////
events: {
"change #selFile": "browserImportDocs",
"click .topcoat-list__item": "mobileImportDocs",
"click #OK": "onOK"
},
// Resume handler -- user placed the app in the background, then resumed.
// Assume the file list could have changed, and reload this page
onResume: function () {
// refresh the view
Backbone.history.loadUrl(Backbone.history.fragment);
},
// Handler for when the user clicks the Select button (browser only) -
// (this is the html <input type=file> element displayed for the browser only) --
// file selections are returned by the browser in the event.currentTarget.files array
browserImportDocs: function (event) {
var fileindex = 0;
var files = event.currentTarget.files;
fileCount = files.length;
// each of the files items is a file object already; there's no need to use
// the file plugin like we need to below. Just call importFile() directly.
while (fileindex < fileCount) {
importFile(files[fileindex], this.model);
fileindex++;
}
},
// Handler for the when the user clicks a document in the list to import (mobile only) -
// we gather the file path from the selection, then reconstitute file objects
// from the path using the cordova-plugin-file / filesystem API.
mobileImportDocs: function (event) {
// replace the selection UI with the import UI
$("#mobileSelect").html(Handlebars.compile(tplLoadingPleaseWait));
$("#OK").hide();
// find all the selected file
var index = $(event.currentTarget).attr('id').trim();
var model = this.model;
console.log("index: " + index + ", FileList[index]: " + fileList[index]);
// request the persistent file system
window.resolveLocalFileSystemURL(fileList[index],
function (entry) {
entry.file(
function (file) {
$("#status").html(i18n.t("view.dscStatusReading", {document: file.name}));
importFile(file, model);
},
function (error) {
console.log("FileEntry.file error: " + error.code);
}
);
},
function (error) {
console.log("resolveLocalFileSystemURL error: " + error.code);
});
},
// Handler for the OK button -- just returns to the home screen.
onOK: function (event) {
// save the model
this.model.save();
window.Application.currentProject = this.model;
// head back to the home page
window.history.back();
},
// Show event handler (from MarionetteJS):
// - if we're running in a mobile device, we'll use the cordova-plugin-file
// API to search through the device directories and add any valid files
// to a table grid
// - If we're in a browser, just show the html <input type=file> to allow
// for file selection
onShow: function () {
// $("#selFile").attr("accept", ".xml,.usfm");
$("#title").html(i18n.t('view.lblImportDocuments'));
$("#lblDirections").html(i18n.t('view.dscImportDocuments'));
$(".topcoat-progress-bar").hide();
$("#OK").attr("disabled", true);
// build the regular expression to identify punctuation
// (this allows us to split out punctuation as separate tokens when importing
punctExp = "[\\s";
this.model.get('PunctPairs').forEach(function (elt, idx, array) {
// Unicode-encoded punctuation, formatted to get leading 00 padding (e.g., \U0065 for "a"),
// each punctuation marker is bound in "capturing parentheses", meaning that
// the punctuation itself is kept as a separate token in the array when we perform our split() call.
// Note that we have to do a charCodeAt(), which returns the decimal value of the unicode char,
// then convert it to hex using toString(16).
puncts.push(elt.s);
punctExp += "(\\u" + ("000" + elt.s.charCodeAt(0).toString(16)).slice(-4) + ")";
});
punctExp += "]+"; // one or more of ANY of the above will trigger a new token
// load the source / target case pairs
this.model.get('CasePairs').forEach(function (elt, idx, array) {
caseSource.push(elt.s);
caseTarget.push(elt.t);
});
// instantiate the KB in case we import an AI XML document (we'll populate the KB if that happens)
kblist = new kbModels.TargetUnitCollection();
kblist.fetch({reset: true, data: {source: ""}});
// cheater way to tell if running on mobile device
if (window.sqlitePlugin) {
// running on device -- use cordova file plugin to select file
$("#browserGroup").hide();
$("#mobileSelect").html(Handlebars.compile(tplLoadingPleaseWait));
var localURLs = [
cordova.file.dataDirectory,
cordova.file.documentsDirectory,
cordova.file.externalRootDirectory,
cordova.file.sharedDirectory,
cordova.file.syncedDataDirectory
];
var DirsRemaining = localURLs.length;
var index = 0;
var i;
var statusStr = "";
var addFileEntry = function (entry) {
var dirReader = entry.createReader();
dirReader.readEntries(
function (entries) {
var fileStr = "";
var i;
for (i = 0; i < entries.length; i++) {
if (entries[i].isDirectory === true) {
// Recursive -- call back into this subdirectory
addFileEntry(entries[i]);
} else {
console.log(entries[i].fullPath);
if (entries[i].fullPath.indexOf("Download") > 0 || entries[i].fullPath.indexOf("Document") > 0 || entries[i].fullPath.lastIndexOf('/') === 0) {
// only take files from the Download or Document directories
if ((entries[i].name.indexOf(".txt") > 0) ||
(entries[i].name.indexOf(".usx") > 0) ||
(entries[i].name.indexOf(".usfm") > 0) ||
(entries[i].name.indexOf(".sfm") > 0) ||
(entries[i].name.indexOf(".xml") > 0)) {
fileList[index] = entries[i].toURL();
fileStr += "<li class='topcoat-list__item' id=" + index + ">" + entries[i].fullPath + "<span class='chevron'></span></li>";
// fileStr += "<tr><td><label class='topcoat-checkbox'><input class='c' type='checkbox' id='" + index + "'><div class='topcoat-checkbox__checkmark'></div></label><td><span class='n'>" + entries[i].fullPath + "</span></td></tr>";
index++;
}
}
}
}
statusStr += fileStr;
DirsRemaining--;
if (DirsRemaining <= 0) {
if (statusStr.length > 0) {
$("#mobileSelect").html("<div class='wizard-instructions'>" + i18n.t('view.dscImportDocuments') + "</div><div class='topcoat-list__container chapter-list'><ul class='topcoat-list__container chapter-list'>" + statusStr + "</ul></div>");
// $("#mobileSelect").html("<table class=\"topcoat-table\"><colgroup><col style=\"width:2.5rem;\"><col></colgroup><thead><tr><th></th><th>" + i18n.t('view.lblName') + "</th></tr></thead><tbody id=\"tb\"></tbody></table><div><button class=\"topcoat-button\" id=\"Import\" disabled>" + i18n.t('view.lblImport') + "</button></div>");
$("#tb").html(statusStr);
$("#OK").attr("disabled", true);
} else {
// nothing to select -- inform the user
$("#mobileSelect").html("<span class=\"topcoat-notification\">!</span> <em>" + i18n.t('view.dscNoDocumentsFound') + "</em>");
$("#OK").removeAttr("disabled");
}
}
},
function (error) {
console.log("readEntries error: " + error.code);
statusStr += "<p>readEntries error: " + error.code + "</p>";
}
);
};
var addError = function (error) {
console.log("getDirectory error: " + error.code);
statusStr += "<p>getDirectory error: " + error.code + ", " + error.message + "</p>";
};
for (i = 0; i < localURLs.length; i++) {
if (localURLs[i] !== null && localURLs[i].length > 0) {
window.resolveLocalFileSystemURL(localURLs[i], addFileEntry, addError);
} else {
DirsRemaining--;
}
}
} else {
// running in browser -- use html <input> to select file
$("#mobileSelect").hide();
}
}
}),
ExportDocumentView = Marionette.ItemView.extend({
template: Handlebars.compile(tplExportDoc),
initialize: function () {
document.addEventListener("resume", this.onResume, false);
},
////
// Event Handlers
////
events: {
"click .topcoat-list__item": "selectDoc",
"change .topcoat-radio-button": "changeType",
"click #OK": "onOK",
"click #Cancel": "onCancel"
},
// Resume handler -- user placed the app in the background, then resumed.
// Assume the file list could have changed, and reload this page
onResume: function () {
// refresh the view
Backbone.history.loadUrl(Backbone.history.fragment);
},
// User changed the export format type. Add the appropriate extension
changeType: function (event) {
// strip any existing trailing extension from the filename
var filename = $("#Filename").val().trim();
if (filename.length > 0) {
if ((filename.indexOf(".xml") > -1) || (filename.indexOf(".txt") > -1) || (filename.indexOf(".sfm") > -1) || (filename.indexOf(".usx") > -1)) {
filename = filename.substr(0, filename.length - 4);
}
}
// get the desired format
if ($("#exportXML").is(":checked")) {
filename += ".xml";
} else if ($("#exportUSX").is(":checked")) {
filename += ".usx";
} else if ($("#exportUSFM").is(":checked")) {
filename += ".sfm";
} else {
// fallback to plain text
filename += ".txt";
}
// replace the filename text
$("#Filename").val(filename);
},
// User clicked the OK button. Export the selected document to the specified format.
onOK: function (event) {
if ($("#exportXML").length === 0) {
// if this is the export complete page,
// go back to the previous page
window.history.go(-1);
} else {
var format = FileTypeEnum.TXT;
var filename = $("#Filename").val().trim();
// validate input
if (filename.length === 0) {
// user didn't type anything in
// just tell them to enter something
if (navigator.notification) {
// on mobile device -- use notification plugin API
navigator.notification.alert(i18n.t('view.errNoFilename'));
} else {
// in browser -- use window.confirm / window.alert
alert(i18n.t('view.errNoFilename'));
}
$("#Filename").focus();
} else {
// get the desired format
if ($("#exportXML").is(":checked")) {
format = FileTypeEnum.XML;
} else if ($("#exportUSX").is(":checked")) {
format = FileTypeEnum.USX;
} else if ($("#exportUSFM").is(":checked")) {
format = FileTypeEnum.USFM;
} else {
// fallback to plain text
format = FileTypeEnum.TXT;
}
// update the UI
$("#mobileSelect").html(Handlebars.compile(tplLoadingPleaseWait));
$("#loading").html(i18n.t("view.lblExportingPleaseWait"));
$("#status").html(i18n.t("view.dscExporting", {file: filename}));
$("#OK").hide();
// perform the export
exportDocument(bookid, format, filename);
}
}
},
// User clicked the Cancel button. Here we don't do anything -- just return
onCancel: function (event) {
// go back to the previous page
window.history.go(-1);
},
selectDoc: function (event) {
// get the info for this document
bookName = event.currentTarget.innerText;
bookid = $(event.currentTarget).attr('id').trim();
// show the next screen
$("#lblDirections").html(i18n.t('view.lblDocSelected') + bookName);
$("#Container").html(Handlebars.compile(tplExportFormat));
// select a default of TXT for the export format (for now)
$("#exportTXT").prop("checked", true);
$("#Filename").val(bookName + ".txt");
},
onShow: function () {
var list = "";
var pid = this.model.get('projectid');
$.when(window.Application.BookList.fetch({reset: true, data: {name: ""}}).done(function () {
list = buildDocumentList(pid);
$("#Container").html("<ul class='topcoat-list__container chapter-list'>" + list + "</ul>");
$('#lblDirections').html(i18n.t('view.lblExportSelectDocument'));
}));
}
});
return {
ImportDocumentView: ImportDocumentView,
ExportDocumentView: ExportDocumentView
};
});
| Work on #67
| www/js/views/DocumentViews.js | Work on #67 | <ide><path>ww/js/views/DocumentViews.js
<ide> }
<ide> chapterString += "\n<para style=\"b\" />";
<ide> }
<del> if ((markers.indexOf("\\p") > -1) || (markers.indexOf("\\q") > -1) || (markers.indexOf("\\ide") > -1) || (markers.indexOf("\\h") > -1) || (markers.indexOf("\\mt") > -1)) {
<add> if ((markers.indexOf("\\p") > -1) || (markers.indexOf("\\q") > -1) || (markers.indexOf("\\ide") > -1) || (markers.indexOf("\\h") > -1) || (markers.indexOf("\\mt") > -1) || (markers.indexOf("\\imt") > -1) || (markers.indexOf("\\rem") > -1) || (markers.indexOf("\\toc") > -1)) {
<ide> if (closeNode.length > 0) {
<ide> chapterString += closeNode;
<ide> }
<ide> chapterString += "\n<para style=\"";
<ide> if (markers.indexOf("\\p") > -1) {
<del> chapterString += "p";
<add> var ppos = markers.indexOf("\\p");
<add> if (markers.indexOf(" ", hpos) > -1) {
<add> chapterString += markers.substring(ppos + 1, (markers.indexOf(" ", ppos)));
<add> } else {
<add> chapterString += markers.substr(ppos + 1);
<add> }
<ide> } else if (markers.indexOf("\\q") > -1) {
<ide> // extract out what kind of quote this is (e.g., "q2") - this goes in the style attribute
<ide> var qpos = markers.indexOf("\\q");
<ide> } else if (markers.indexOf("\\ide") > -1) {
<ide> chapterString += "ide";
<ide> } else if (markers.indexOf("\\h") > -1) {
<del> chapterString += "h";
<add> var hpos = markers.indexOf("\\h");
<add> if (markers.indexOf(" ", hpos) > -1) {
<add> chapterString += markers.substring(hpos + 1, (markers.indexOf(" ", hpos)));
<add> } else {
<add> chapterString += markers.substr(hpos + 1);
<add> }
<add> } else if (markers.indexOf("\\rem") > -1) {
<add> chapterString += "rem";
<add> } else if (markers.indexOf("\\imt") > -1) {
<add> // extract out what kind this is (e.g., "imt2") -
<add> // this goes in the style attribute
<add> var imtpos = markers.indexOf("\\imt");
<add> if (markers.indexOf(" ", imtpos) > -1) { chapterString += markers.substring(imtpos + 1, (markers.indexOf(" ", imtpos)));
<add> } else {
<add> chapterString += markers.substr(imtpos + 1);
<add> }
<ide> } else if (markers.indexOf("\\mt") > -1) {
<del> // extract out what kind of major title this is (e.g., "mt2") -
<add> // extract out what kind this is (e.g., "mt2") -
<ide> // this goes in the style attribute
<ide> var mtpos = markers.indexOf("\\mt");
<ide> if (markers.indexOf(" ", mtpos) > -1) { chapterString += markers.substring(mtpos + 1, (markers.indexOf(" ", mtpos)));
<ide> } else {
<ide> chapterString += markers.substr(mtpos + 1);
<add> }
<add> } else if (markers.indexOf("\\toc") > -1) {
<add> // extract out what kind this is (e.g., "toc2") -
<add> // this goes in the style attribute
<add> var tocpos = markers.indexOf("\\toc");
<add> if (markers.indexOf(" ", tocpos) > -1) { chapterString += markers.substring(tocpos + 1, (markers.indexOf(" ", tocpos)));
<add> } else {
<add> chapterString += markers.substr(tocpos + 1);
<ide> }
<ide> }
<ide> chapterString += "\">"; |
|
Java | lgpl-2.1 | ad0cb255433783be9b99bcda903008060c3070b4 | 0 | svartika/ccnx,cawka/ndnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx,svartika/ccnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,cawka/ndnx,ebollens/ccnmp,ebollens/ccnmp,cawka/ndnx,svartika/ccnx,svartika/ccnx | package org.ccnx.ccn.test.impl;
import java.io.IOException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.ccnx.ccn.CCNFilterListener;
import org.ccnx.ccn.CCNInterestListener;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.test.CCNTestBase;
import org.ccnx.ccn.test.CCNTestHelper;
import org.junit.Test;
/*
* A CCNx library test.
*
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/**
* Since the deprecated interfaces need coding support, we need to test they still work
* as long as they aren't removed.
*/
@SuppressWarnings("deprecation")
public class DeprecatedInterfaceTest extends CCNTestBase implements CCNFilterListener, CCNInterestListener {
static final int QUICK_TIMEOUT = 200;
static final int MORE_THAN_RETRY_TIMEOUT = SystemConfiguration.INTEREST_REEXPRESSION_DEFAULT * 2;
static CCNTestHelper testHelper = new CCNTestHelper(DeprecatedInterfaceTest.class);
static ContentName prefix = testHelper.getTestNamespace("testDeprecatedInterfaces");
boolean sawInterest = false;
boolean sawContent = false;
Semaphore interestSema = null;
Semaphore contentSema = null;
boolean putNow = false;
int counter = 0;
@Test
public void testDeprecatedMethods() throws Throwable {
interestSema = new Semaphore(0);
contentSema = new Semaphore(0);
Interest interest = new Interest(prefix);
// Check that we can register a filter and see an interest using the old interface
putHandle.registerFilter(prefix, this);
getHandle.expressInterest(interest, this);
interestSema.tryAcquire(QUICK_TIMEOUT, TimeUnit.MILLISECONDS);
Assert.assertTrue("Interest never seen", sawInterest);
// Check that we can see content using the old interface - we wait for interest reexpression
// to get it
sawInterest = false;
putNow = true;
contentSema.tryAcquire(MORE_THAN_RETRY_TIMEOUT, TimeUnit.MILLISECONDS);
getHandle.checkError(0);
Assert.assertTrue("Content never seen", sawContent);
// Make sure that we don't get back content after we cancel the interest
Interest nextInterest = new Interest(ContentName.fromNative(prefix,
Integer.toString(counter)));
getHandle.expressInterest(nextInterest, this);
sawContent = false;
putNow = true;
getHandle.cancelInterest(nextInterest, this);
contentSema.tryAcquire(MORE_THAN_RETRY_TIMEOUT, TimeUnit.MILLISECONDS);
getHandle.checkError(0);
Assert.assertFalse("Content seen when it should not have been", sawContent);
// Now check that we don't see an interest after we unregister its filter
sawInterest = false;
nextInterest = new Interest(ContentName.fromNative(prefix,
Integer.toString(counter)));
putHandle.unregisterFilter(prefix, this);
getHandle.expressInterest(nextInterest, this);
interestSema.tryAcquire(QUICK_TIMEOUT, TimeUnit.MILLISECONDS);
Assert.assertFalse("Interest seen after cancel", sawInterest);
getHandle.cancelInterest(nextInterest, this);
}
public boolean handleInterest(Interest interest) {
sawInterest = true;
interestSema.release();
if (putNow) {
ContentObject co = ContentObject.buildContentObject(ContentName.fromNative(prefix,
Integer.toString(counter++)), "deprecationTest".getBytes());
try {
putNow = false;
putHandle.put(co);
} catch (IOException e) {
Assert.fail(e.getMessage());
}
}
return true;
}
public Interest handleContent(ContentObject data, Interest interest) {
sawContent = true;
contentSema.release();
return null;
}
}
| javasrc/src/org/ccnx/ccn/test/impl/DeprecatedInterfaceTest.java | package org.ccnx.ccn.test.impl;
import java.io.IOException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.ccnx.ccn.CCNFilterListener;
import org.ccnx.ccn.CCNInterestListener;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.test.CCNTestBase;
import org.ccnx.ccn.test.CCNTestHelper;
import org.junit.Test;
/*
* A CCNx library test.
*
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/**
* Since the deprecated interfaces need coding support, we need to test they still work
* as long as they aren't removed.
*/
@SuppressWarnings("deprecation")
public class DeprecatedInterfaceTest extends CCNTestBase implements CCNFilterListener, CCNInterestListener {
static final int QUICK_TIMEOUT = 200;
static final int MORE_THAN_RETRY_TIMEOUT = SystemConfiguration.INTEREST_REEXPRESSION_DEFAULT * 2;
static CCNTestHelper testHelper = new CCNTestHelper(DeprecatedInterfaceTest.class);
static ContentName prefix = testHelper.getTestNamespace("testDeprecatedInterfaces");
boolean sawInterest = false;
boolean sawContent = false;
Semaphore interestSema = null;
Semaphore contentSema = null;
boolean putNow = false;
int counter = 0;
@Test
public void testDeprecatedMethods() throws Throwable {
interestSema = new Semaphore(0);
contentSema = new Semaphore(0);
Interest interest = new Interest(prefix);
// Check that we can register a filter and see an interest using the old interface
putHandle.registerFilter(prefix, this);
getHandle.expressInterest(interest, this);
interestSema.tryAcquire(QUICK_TIMEOUT, TimeUnit.MILLISECONDS);
Assert.assertTrue("Interest never seen", sawInterest);
// Check that we can see content using the old interface - we wait for interest reexpression
// to get it
sawInterest = false;
putNow = true;
contentSema.tryAcquire(MORE_THAN_RETRY_TIMEOUT, TimeUnit.MILLISECONDS);
getHandle.checkError(0);
Assert.assertTrue("Content never seen", sawContent);
// Make sure that we don't get back content after we cancel the interest
sawContent = false;
putNow = true;
getHandle.cancelInterest(interest, this);
contentSema.tryAcquire(MORE_THAN_RETRY_TIMEOUT, TimeUnit.MILLISECONDS);
getHandle.checkError(0);
Assert.assertFalse("Content seen when it should not have been", sawContent);
// Now check that we don't see an interest after we unregister its filter
sawInterest = false;
putHandle.unregisterFilter(prefix, this);
getHandle.expressInterest(interest, this);
interestSema.tryAcquire(QUICK_TIMEOUT, TimeUnit.MILLISECONDS);
Assert.assertFalse("Interest seen after cancel", sawInterest);
getHandle.cancelInterest(interest, this);
}
public boolean handleInterest(Interest interest) {
sawInterest = true;
interestSema.release();
if (putNow) {
ContentObject co = ContentObject.buildContentObject(ContentName.fromNative(prefix,
Integer.toString(counter++)), "deprecationTest".getBytes());
try {
putNow = false;
putHandle.put(co);
} catch (IOException e) {
Assert.fail(e.getMessage());
}
}
return true;
}
public Interest handleContent(ContentObject data, Interest interest) {
sawContent = true;
contentSema.release();
return Interest.next(data.name(), null, null);
}
}
| refs #100536 Fix test to generate interests in a more reasonable way
| javasrc/src/org/ccnx/ccn/test/impl/DeprecatedInterfaceTest.java | refs #100536 Fix test to generate interests in a more reasonable way | <ide><path>avasrc/src/org/ccnx/ccn/test/impl/DeprecatedInterfaceTest.java
<ide> Assert.assertTrue("Content never seen", sawContent);
<ide>
<ide> // Make sure that we don't get back content after we cancel the interest
<add> Interest nextInterest = new Interest(ContentName.fromNative(prefix,
<add> Integer.toString(counter)));
<add> getHandle.expressInterest(nextInterest, this);
<ide> sawContent = false;
<ide> putNow = true;
<del> getHandle.cancelInterest(interest, this);
<add> getHandle.cancelInterest(nextInterest, this);
<ide> contentSema.tryAcquire(MORE_THAN_RETRY_TIMEOUT, TimeUnit.MILLISECONDS);
<ide> getHandle.checkError(0);
<ide> Assert.assertFalse("Content seen when it should not have been", sawContent);
<ide>
<ide> // Now check that we don't see an interest after we unregister its filter
<ide> sawInterest = false;
<add> nextInterest = new Interest(ContentName.fromNative(prefix,
<add> Integer.toString(counter)));
<ide> putHandle.unregisterFilter(prefix, this);
<del> getHandle.expressInterest(interest, this);
<add> getHandle.expressInterest(nextInterest, this);
<ide> interestSema.tryAcquire(QUICK_TIMEOUT, TimeUnit.MILLISECONDS);
<ide> Assert.assertFalse("Interest seen after cancel", sawInterest);
<del> getHandle.cancelInterest(interest, this);
<add> getHandle.cancelInterest(nextInterest, this);
<ide> }
<ide>
<ide> public boolean handleInterest(Interest interest) {
<ide> public Interest handleContent(ContentObject data, Interest interest) {
<ide> sawContent = true;
<ide> contentSema.release();
<del> return Interest.next(data.name(), null, null);
<add> return null;
<ide> }
<ide> } |
|
JavaScript | mit | 9913df407c4c2eae3bc2987bf82750ee65a764d8 | 0 | Jdesk/brackets-git,MarcelGerber/brackets-git,M4gn4tor/brackets-git,rodrigojt/brackets-git,zaggino/brackets-git,M4gn4tor/brackets-git,mattbell87/brackets-git,zaggino/brackets-git,mattbell87/brackets-git,Jdesk/brackets-git,ReachingOut/brackets-git,MarcelGerber/brackets-git,ofer43211/brackets-git,FezVrasta/brackets-git,Jdesk/brackets-git,mattbell87/brackets-git,zaggino/brackets-git,MarcelGerber/brackets-git,EugeneKot/brackets-git,EugeneKot/brackets-git,ofer43211/brackets-git,ReachingOut/brackets-git,zaggino/brackets-git,rodrigojt/brackets-git,M4gn4tor/brackets-git,ReachingOut/brackets-git,EugeneKot/brackets-git,FezVrasta/brackets-git,MarcelGerber/brackets-git,ofer43211/brackets-git,rodrigojt/brackets-git | define(function (require) {
"use strict";
var _ = brackets.getModule("thirdparty/lodash"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
FileTreeView = brackets.getModule("project/FileTreeView");
var EventEmitter = require("src/EventEmitter"),
Events = require("src/Events"),
Git = require("src/git/Git"),
Preferences = require("src/Preferences"),
Promise = require("bluebird"),
Utils = require("src/Utils");
var ignoreEntries = [],
newPaths = [],
modifiedPaths = [];
function refreshIgnoreEntries() {
function regexEscape(str) {
// NOTE: We cannot use StringUtils.regexEscape() here because we don't wanna replace *
return str.replace(/([.?+\^$\[\]\\(){}|\-])/g, "\\$1");
}
return new Promise(function (resolve) {
if (!Preferences.get("markModifiedInTree")) {
return resolve();
}
var projectRoot = Utils.getProjectRoot();
FileSystem.getFileForPath(projectRoot + ".gitignore").read(function (err, content) {
if (err) {
ignoreEntries = [];
return resolve();
}
ignoreEntries = _.compact(_.map(content.split("\n"), function (line) {
// Rules: http://git-scm.com/docs/gitignore
var type = "deny",
leadingSlash,
trailingSlash,
regex;
line = line.trim();
if (!line || line.indexOf("#") === 0) {
return;
}
// handle explicitly allowed files/folders with a leading !
if (line.indexOf("!") === 0) {
line = line.slice(1);
type = "accept";
}
// handle lines beginning with a backslash, which is used for escaping ! or #
if (line.indexOf("\\") === 0) {
line = line.slice(1);
}
// handle lines beginning with a slash, which only matches files/folders in the root dir
if (line.indexOf("/") === 0) {
line = line.slice(1);
leadingSlash = true;
}
// handle lines ending with a slash, which only exludes dirs
if (line.lastIndexOf("/") === line.length) {
// a line ending with a slash ends with **
line += "**";
trailingSlash = true;
}
// NOTE: /(.{0,})/ is basically the same as /(.*)/, but we can't use it because the asterisk
// would be replaced later on
// create the intial regexp here. We need the absolute path 'cause it could be that there
// are external files with the same name as a project file
regex = regexEscape(projectRoot) + (leadingSlash ? "" : "((.+)/)?") + regexEscape(line) + (trailingSlash ? "" : "(/.{0,})?");
// replace all the possible asterisks
regex = regex.replace(/\*\*$/g, "(.{0,})").replace(/(\*\*|\*$)/g, "(.+)").replace(/\*/g, "([^/]+)");
regex = "^" + regex + "$";
return {
regexp: new RegExp(regex),
type: type
};
}));
return resolve();
});
});
}
function isIgnored(path) {
var ignored = false;
_.forEach(ignoreEntries, function (entry) {
if (entry.regexp.test(path)) {
ignored = (entry.type === "deny");
}
});
return ignored;
}
function isNew(fullPath) {
return newPaths.indexOf(fullPath) !== -1;
}
function isModified(fullPath) {
return modifiedPaths.indexOf(fullPath) !== -1;
}
FileTreeView.addClassesProvider(function (data) {
var fullPath = data.fullPath;
if (isIgnored(fullPath)) {
return "git-ignored";
} else if (isNew(fullPath)) {
return "git-new";
} else if (isModified(fullPath)) {
return "git-modified";
}
});
function _refreshProjectFiles(selector, dataEntry) {
$(selector).find("li").each(function () {
var $li = $(this),
data = $li.data(dataEntry);
if (data) {
var fullPath = data.fullPath;
$li.toggleClass("git-ignored", isIgnored(fullPath))
.toggleClass("git-new", isNew(fullPath))
.toggleClass("git-modified", isModified(fullPath));
}
});
}
var refreshOpenFiles = _.debounce(function () {
_refreshProjectFiles("#open-files-container", "file");
}, 100);
function refreshBoth() {
refreshOpenFiles();
}
function attachEvents() {
if (Preferences.get("markModifiedInTree")) {
$("#open-files-container").on("contentChanged", refreshOpenFiles).triggerHandler("contentChanged");
}
}
function detachEvents() {
$("#open-files-container").off("contentChanged", refreshOpenFiles);
}
// this will refresh ignore entries when .gitignore is modified
EventEmitter.on(Events.BRACKETS_FILE_CHANGED, function (evt, file) {
if (file.fullPath === Utils.getProjectRoot() + ".gitignore") {
refreshIgnoreEntries().finally(function () {
refreshBoth();
});
}
});
// this will refresh new/modified paths on every status results
EventEmitter.on(Events.GIT_STATUS_RESULTS, function (files) {
var projectRoot = Utils.getProjectRoot();
newPaths = [];
modifiedPaths = [];
files.forEach(function (entry) {
var isNew = entry.status.indexOf(Git.FILE_STATUS.UNTRACKED) !== -1 ||
entry.status.indexOf(Git.FILE_STATUS.ADDED) !== -1;
var fullPath = projectRoot + entry.file;
if (isNew) {
newPaths.push(fullPath);
} else {
modifiedPaths.push(fullPath);
}
});
refreshBoth();
});
// this will refresh ignore entries when git project is opened
EventEmitter.on(Events.GIT_ENABLED, function () {
refreshIgnoreEntries();
attachEvents();
});
// this will clear entries when non-git project is opened
EventEmitter.on(Events.GIT_DISABLED, function () {
ignoreEntries = [];
newPaths = [];
modifiedPaths = [];
detachEvents();
});
});
| src/ProjectTreeMarks.js | define(function (require) {
"use strict";
var _ = brackets.getModule("thirdparty/lodash"),
FileSystem = brackets.getModule("filesystem/FileSystem");
var EventEmitter = require("src/EventEmitter"),
Events = require("src/Events"),
Git = require("src/git/Git"),
Preferences = require("src/Preferences"),
Promise = require("bluebird"),
Utils = require("src/Utils");
var ignoreEntries = [],
newPaths = [],
modifiedPaths = [];
function refreshIgnoreEntries() {
function regexEscape(str) {
// NOTE: We cannot use StringUtils.regexEscape() here because we don't wanna replace *
return str.replace(/([.?+\^$\[\]\\(){}|\-])/g, "\\$1");
}
return new Promise(function (resolve) {
if (!Preferences.get("markModifiedInTree")) {
return resolve();
}
var projectRoot = Utils.getProjectRoot();
FileSystem.getFileForPath(projectRoot + ".gitignore").read(function (err, content) {
if (err) {
ignoreEntries = [];
return resolve();
}
ignoreEntries = _.compact(_.map(content.split("\n"), function (line) {
// Rules: http://git-scm.com/docs/gitignore
var type = "deny",
leadingSlash,
trailingSlash,
regex;
line = line.trim();
if (!line || line.indexOf("#") === 0) {
return;
}
// handle explicitly allowed files/folders with a leading !
if (line.indexOf("!") === 0) {
line = line.slice(1);
type = "accept";
}
// handle lines beginning with a backslash, which is used for escaping ! or #
if (line.indexOf("\\") === 0) {
line = line.slice(1);
}
// handle lines beginning with a slash, which only matches files/folders in the root dir
if (line.indexOf("/") === 0) {
line = line.slice(1);
leadingSlash = true;
}
// handle lines ending with a slash, which only exludes dirs
if (line.lastIndexOf("/") === line.length) {
// a line ending with a slash ends with **
line += "**";
trailingSlash = true;
}
// NOTE: /(.{0,})/ is basically the same as /(.*)/, but we can't use it because the asterisk
// would be replaced later on
// create the intial regexp here. We need the absolute path 'cause it could be that there
// are external files with the same name as a project file
regex = regexEscape(projectRoot) + (leadingSlash ? "" : "((.+)/)?") + regexEscape(line) + (trailingSlash ? "" : "(/.{0,})?");
// replace all the possible asterisks
regex = regex.replace(/\*\*$/g, "(.{0,})").replace(/(\*\*|\*$)/g, "(.+)").replace(/\*/g, "([^/]+)");
regex = "^" + regex + "$";
return {
regexp: new RegExp(regex),
type: type
};
}));
return resolve();
});
});
}
function isIgnored(path) {
var ignored = false;
_.forEach(ignoreEntries, function (entry) {
if (entry.regexp.test(path)) {
ignored = (entry.type === "deny");
}
});
return ignored;
}
function isNew(fullPath) {
return newPaths.indexOf(fullPath) !== -1;
}
function isModified(fullPath) {
return modifiedPaths.indexOf(fullPath) !== -1;
}
function _refreshProjectFiles(selector, dataEntry) {
$(selector).find("li").each(function () {
var $li = $(this),
data = $li.data(dataEntry);
if (data) {
var fullPath = data.fullPath;
$li.toggleClass("git-ignored", isIgnored(fullPath))
.toggleClass("git-new", isNew(fullPath))
.toggleClass("git-modified", isModified(fullPath));
}
});
}
var refreshOpenFiles = _.debounce(function () {
_refreshProjectFiles("#open-files-container", "file");
}, 100);
var refreshProjectFiles = _.debounce(function () {
_refreshProjectFiles("#project-files-container", "entry");
}, 100);
function refreshBoth() {
refreshOpenFiles();
refreshProjectFiles();
}
function attachEvents() {
if (Preferences.get("markModifiedInTree")) {
$("#open-files-container").on("contentChanged", refreshOpenFiles).triggerHandler("contentChanged");
$("#project-files-container").on("contentChanged after_open.jstree", refreshProjectFiles).triggerHandler("contentChanged");
}
}
function detachEvents() {
$("#open-files-container").off("contentChanged", refreshOpenFiles);
$("#project-files-container").off("contentChanged after_open.jstree", refreshProjectFiles);
}
// this will refresh ignore entries when .gitignore is modified
EventEmitter.on(Events.BRACKETS_FILE_CHANGED, function (evt, file) {
if (file.fullPath === Utils.getProjectRoot() + ".gitignore") {
refreshIgnoreEntries().finally(function () {
refreshBoth();
});
}
});
// this will refresh new/modified paths on every status results
EventEmitter.on(Events.GIT_STATUS_RESULTS, function (files) {
var projectRoot = Utils.getProjectRoot();
newPaths = [];
modifiedPaths = [];
files.forEach(function (entry) {
var isNew = entry.status.indexOf(Git.FILE_STATUS.UNTRACKED) !== -1 ||
entry.status.indexOf(Git.FILE_STATUS.ADDED) !== -1;
var fullPath = projectRoot + entry.file;
if (isNew) {
newPaths.push(fullPath);
} else {
modifiedPaths.push(fullPath);
}
});
refreshBoth();
});
// this will refresh ignore entries when git project is opened
EventEmitter.on(Events.GIT_ENABLED, function () {
refreshIgnoreEntries();
attachEvents();
});
// this will clear entries when non-git project is opened
EventEmitter.on(Events.GIT_DISABLED, function () {
ignoreEntries = [];
newPaths = [];
modifiedPaths = [];
detachEvents();
});
});
| Use the new API in FileTreeView
| src/ProjectTreeMarks.js | Use the new API in FileTreeView | <ide><path>rc/ProjectTreeMarks.js
<ide> "use strict";
<ide>
<ide> var _ = brackets.getModule("thirdparty/lodash"),
<del> FileSystem = brackets.getModule("filesystem/FileSystem");
<add> FileSystem = brackets.getModule("filesystem/FileSystem"),
<add> FileTreeView = brackets.getModule("project/FileTreeView");
<ide>
<ide> var EventEmitter = require("src/EventEmitter"),
<ide> Events = require("src/Events"),
<ide> return modifiedPaths.indexOf(fullPath) !== -1;
<ide> }
<ide>
<add> FileTreeView.addClassesProvider(function (data) {
<add> var fullPath = data.fullPath;
<add> if (isIgnored(fullPath)) {
<add> return "git-ignored";
<add> } else if (isNew(fullPath)) {
<add> return "git-new";
<add> } else if (isModified(fullPath)) {
<add> return "git-modified";
<add> }
<add> });
<add>
<ide> function _refreshProjectFiles(selector, dataEntry) {
<ide> $(selector).find("li").each(function () {
<ide> var $li = $(this),
<ide> if (data) {
<ide> var fullPath = data.fullPath;
<ide> $li.toggleClass("git-ignored", isIgnored(fullPath))
<del> .toggleClass("git-new", isNew(fullPath))
<del> .toggleClass("git-modified", isModified(fullPath));
<add> .toggleClass("git-new", isNew(fullPath))
<add> .toggleClass("git-modified", isModified(fullPath));
<ide> }
<ide> });
<ide> }
<del>
<ide> var refreshOpenFiles = _.debounce(function () {
<ide> _refreshProjectFiles("#open-files-container", "file");
<ide> }, 100);
<ide>
<del> var refreshProjectFiles = _.debounce(function () {
<del> _refreshProjectFiles("#project-files-container", "entry");
<del> }, 100);
<del>
<ide> function refreshBoth() {
<ide> refreshOpenFiles();
<del> refreshProjectFiles();
<ide> }
<ide>
<ide> function attachEvents() {
<ide> if (Preferences.get("markModifiedInTree")) {
<ide> $("#open-files-container").on("contentChanged", refreshOpenFiles).triggerHandler("contentChanged");
<del> $("#project-files-container").on("contentChanged after_open.jstree", refreshProjectFiles).triggerHandler("contentChanged");
<ide> }
<ide> }
<ide>
<ide> function detachEvents() {
<ide> $("#open-files-container").off("contentChanged", refreshOpenFiles);
<del> $("#project-files-container").off("contentChanged after_open.jstree", refreshProjectFiles);
<ide> }
<ide>
<ide> // this will refresh ignore entries when .gitignore is modified |
|
JavaScript | mit | 63b435a40398f41fc81d6bf80b33aa8072796174 | 0 | Zarel/Pokemon-Showdown,Enigami/Pokemon-Showdown,xfix/Pokemon-Showdown,Zarel/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,svivian/Pokemon-Showdown,svivian/Pokemon-Showdown,panpawn/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,Enigami/Pokemon-Showdown,AustinXII/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,xfix/Pokemon-Showdown,svivian/Pokemon-Showdown,panpawn/Gold-Server,QuiteQuiet/Pokemon-Showdown,svivian/Pokemon-Showdown,svivian/Pokemon-Showdown,panpawn/Gold-Server,urkerab/Pokemon-Showdown,xfix/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,Enigami/Pokemon-Showdown,Enigami/Pokemon-Showdown,AustinXII/Pokemon-Showdown,xfix/Pokemon-Showdown,urkerab/Pokemon-Showdown,urkerab/Pokemon-Showdown,AustinXII/Pokemon-Showdown,Zarel/Pokemon-Showdown,xfix/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,panpawn/Pokemon-Showdown,panpawn/Gold-Server | 'use strict';
// Note: This is the list of formats
// The rules that formats use are stored in data/rulesets.js
exports.Formats = [
// SM Singles
///////////////////////////////////////////////////////////////////
{
section: "SM Singles",
},
{
name: "[Gen 7] Random Battle",
desc: ["Randomized teams of level-balanced Pokémon with sets that are generated to be competitively viable."],
mod: 'gen7',
team: 'random',
ruleset: ['PotD', 'Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] Unrated Random Battle",
mod: 'gen7',
team: 'random',
challengeShow: false,
rated: false,
ruleset: ['PotD', 'Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3608656/\">OU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3587177/\">OU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3590726/\">OU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3606650/\">OU Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Standard', 'Team Preview'],
banlist: ['Uber', 'Arena Trap', 'Power Construct', 'Shadow Tag', 'Baton Pass'],
},
{
name: "[Gen 7] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3587184/\">Ubers Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591388/\">Ubers Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3599816/\">Ubers Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Mega Rayquaza Clause'],
banlist: ['Baton Pass'],
},
{
name: "[Gen 7] UU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3616332/\">UU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3613279/\">UU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591880/\">UU Sample Teams</a>",
],
mod: 'gen7',
searchShow: false,
ruleset: ['[Gen 7] OU'],
banlist: ['OU', 'BL', 'Drizzle', 'Mewnium Z'],
},
{
name: "[Gen 7] UU (suspect test)",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3616332/\">UU Suspect Test</a>"],
mod: 'gen7',
challengeShow: false,
ruleset: ['[Gen 7] UU'],
banlist: [],
},
{
name: "[Gen 7] RU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3615711/\">RU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3602279/\">RU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3598090/\">RU Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['[Gen 7] UU'],
banlist: ['UU', 'BL2', 'Aurora Veil'],
},
{
name: "[Gen 7] NU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3616091/\">NU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3607629/\">NU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3606112/\">NU Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['[Gen 7] RU'],
banlist: ['RU', 'BL3', 'Drought'],
},
{
name: "[Gen 7] PU",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3614120/\">PU Metagame Discussion</a>"],
mod: 'gen7',
ruleset: ['[Gen 7] NU'],
banlist: ['NU', 'BL4'],
},
{
name: "[Gen 7] LC",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3587196/\">LC Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/dex/sm/formats/lc/\">LC Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3609771/\">LC Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3588679/\">LC Sample Teams</a>",
],
mod: 'gen7',
maxLevel: 5,
ruleset: ['Pokemon', 'Standard', 'Swagger Clause', 'Team Preview', 'Little Cup'],
banlist: ['Cutiefly', 'Drifloon', 'Gligar', 'Gothita', 'Meditite', 'Misdreavus', 'Murkrow', 'Porygon', 'Scyther', 'Sneasel', 'Swirlix', 'Tangela', 'Vulpix-Base', 'Yanma', 'Eevium Z', 'Dragon Rage', 'Sonic Boom'],
},
{
name: "[Gen 7] Monotype",
desc: [
"All the Pokémon on a team must share a type.",
"• <a href=\"https://www.smogon.com/forums/threads/3587204/\">Monotype Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3589809/\">Monotype Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3599682/\">Monotype Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Standard', 'Swagger Clause', 'Same Type Clause', 'Team Preview'],
banlist: [
'Aegislash', 'Arceus', 'Blaziken', 'Darkrai', 'Deoxys-Base', 'Deoxys-Attack', 'Dialga', 'Genesect', 'Giratina', 'Groudon', 'Ho-Oh', 'Hoopa-Unbound', 'Kartana', 'Kyogre', 'Kyurem-White',
'Lugia', 'Lunala', 'Magearna', 'Marshadow', 'Mewtwo', 'Palkia', 'Pheromosa', 'Rayquaza', 'Reshiram', 'Shaymin-Sky', 'Solgaleo', 'Tapu Lele', 'Xerneas', 'Yveltal', 'Zekrom', 'Zygarde',
'Battle Bond', 'Damp Rock', 'Gengarite', 'Kangaskhanite', 'Lucarionite', 'Mawilite', 'Medichamite', 'Metagrossite', 'Salamencite', 'Smooth Rock', 'Terrain Extender', 'Baton Pass',
],
},
{
name: "[Gen 7] Anything Goes",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3587441/\">Anything Goes</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591711/\">AG Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/ag/\">AG Analyses</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Illegal', 'Unreleased'],
},
{
name: "[Gen 7] CAP",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3587865/\">CAP Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3597893/\">CAP Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/posts/7203358/\">CAP Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['[Gen 7] OU', 'Allow CAP'],
banlist: ['Tomohawk + Earth Power', 'Tomohawk + Reflect'],
},
{
name: "[Gen 7] CAP LC",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3599594/\">CAP LC</a>"],
mod: 'gen7',
searchShow: false,
maxLevel: 5,
ruleset: ['[Gen 7] LC', 'Allow CAP'],
},
{
name: "[Gen 7] Battle Spot Singles",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3601012/\">Introduction to Battle Spot Singles</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3605970/\">Battle Spot Singles Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3601658/\">Battle Spot Singles Roles Compendium</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3593055/\">Battle Spot Singles Sample Teams</a>",
],
mod: 'gen7',
maxForcedLevel: 50,
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 7] Battle Spot Special 6",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3614104/\">Battle Spot Special</a>"],
mod: 'gen7',
maxForcedLevel: 50,
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
banlist: ['Aegislash', 'Blaziken', 'Charizard', 'Ferrothorn', 'Garchomp', 'Gengar', 'Greninja', 'Gyarados', 'Hippowdon', 'Landorus',
'Landorus-Therian', 'Lucario', 'Mamoswine', 'Mimikyu', 'Porygon2', 'Salamence', 'Tapu Fini', 'Tapu Koko', 'Tapu Lele',
],
requirePentagon: true,
},
{
name: "[Gen 7] Custom Game",
mod: 'gen7',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
teamLength: {
validate: [1, 24],
battle: 24,
},
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// SM Doubles
///////////////////////////////////////////////////////////////////
{
section: "SM Doubles",
},
{
name: "[Gen 7] Random Doubles Battle",
mod: 'gen7',
gameType: 'doubles',
team: 'random',
ruleset: ['PotD', 'Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] Doubles OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3610992/\">Doubles OU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3592903/\">Doubles OU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3590987/\">Doubles OU Sample Teams</a>",
],
mod: 'gen7',
gameType: 'doubles',
ruleset: ['Pokemon', 'Standard Doubles', 'Swagger Clause', 'Team Preview'],
banlist: ['Arceus', 'Dialga', 'Giratina', 'Giratina-Origin', 'Groudon', 'Ho-Oh', 'Jirachi', 'Kyogre', 'Kyurem-White',
'Lugia', 'Lunala', 'Magearna', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Solgaleo', 'Xerneas', 'Yveltal', 'Zekrom',
'Power Construct', 'Eevium Z', 'Kangaskhanite', 'Dark Void', 'Gravity ++ Grass Whistle', 'Gravity ++ Hypnosis', 'Gravity ++ Lovely Kiss', 'Gravity ++ Sing', 'Gravity ++ Sleep Powder',
],
},
{
name: "[Gen 7] Doubles Ubers",
mod: 'gen7',
gameType: 'doubles',
ruleset: ['Pokemon', 'Standard Doubles', 'Team Preview'],
banlist: ['Illegal', 'Unreleased', 'Dark Void'],
},
{
name: "[Gen 7] Doubles UU",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3598014/\">Doubles UU Metagame Discussion</a>"],
mod: 'gen7',
gameType: 'doubles',
ruleset: ['[Gen 7] Doubles OU'],
banlist: [
'Aegislash', 'Amoonguss', 'Arcanine', 'Bronzong', 'Celesteela', 'Deoxys-Attack', 'Diancie', 'Excadrill', 'Ferrothorn',
'Garchomp', 'Gastrodon', 'Genesect', 'Heatran', 'Hoopa-Unbound', 'Jirachi', 'Kartana', 'Kingdra', 'Kyurem-Black',
'Landorus-Therian', 'Ludicolo', 'Marowak-Alola', 'Marshadow', 'Milotic', 'Mimikyu', 'Ninetales-Alola', 'Oranguru',
'Pelipper', 'Politoed', 'Porygon2', 'Scrafty', 'Snorlax', 'Suicune', 'Tapu Bulu', 'Tapu Fini', 'Tapu Koko',
'Tapu Lele', 'Tyranitar', 'Volcanion', 'Volcarona', 'Weavile', 'Whimsicott', 'Zapdos', 'Zygarde-Base',
'Charizardite Y', 'Diancite', 'Gardevoirite', 'Gengarite', 'Kangaskhanite', 'Mawilite', 'Metagrossite', 'Salamencite', 'Swampertite',
],
},
{
name: "[Gen 7] VGC 2017",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3583926/\">VGC 2017 Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591794/\">VGC 2017 Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3590391/\">VGC 2017 Sample Teams</a>",
],
mod: 'gen7',
gameType: 'doubles',
forcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
timer: {starting: 15 * 60 - 10, perTurn: 10, maxPerTurn: 60, maxFirstTurn: 90, timeoutAutoChoose: true},
ruleset: ['Pokemon', 'Species Clause', 'Nickname Clause', 'Item Clause', 'Team Preview', 'Cancel Mod', 'Alola Pokedex'],
banlist: ['Illegal', 'Unreleased', 'Solgaleo', 'Lunala', 'Necrozma', 'Magearna', 'Marshadow', 'Zygarde', 'Mega'],
requirePlus: true,
},
{
name: "[Gen 7] Battle Spot Doubles",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3595001/\">Battle Spot Doubles Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3593890/\">Battle Spot Doubles Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3595859/\">Battle Spot Doubles Sample Teams</a>",
],
mod: 'gen7',
gameType: 'doubles',
maxForcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 7] Doubles Custom Game",
mod: 'gen7',
gameType: 'doubles',
searchShow: false,
canUseRandomTeam: true,
maxLevel: 9999,
defaultLevel: 100,
debug: true,
teamLength: {
validate: [2, 24],
battle: 24,
},
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// Other Metagames
///////////////////////////////////////////////////////////////////
{
section: "OM of the Month",
column: 2,
},
{
name: "[Gen 7] Ultimate Z",
desc: [
"Use any type of Z-Crystal on any move and as many times per battle as desired.",
"• <a href=\"https://www.smogon.com/forums/threads/3609393/\">Ultimate Z</a>",
],
mod: 'ultimatez',
ruleset: ['[Gen 7] OU'],
banlist: ['Kyurem-Black', 'Celebrate', 'Conversion', 'Happy Hour', 'Hold Hands'],
},
{
name: "[Gen 6] Balanced Hackmons",
desc: ["• <a href=\"https://www.smogon.com/dex/xy/formats/bh/\">ORAS Balanced Hackmons</a>"],
mod: 'gen6',
searchShow: false,
ruleset: ['Pokemon', 'Ability Clause', 'OHKO Clause', 'Evasion Moves Clause', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Groudon-Primal', 'Kyogre-Primal', 'Aerilate + Pixilate + Refrigerate > 1',
'Arena Trap', 'Huge Power', 'Moody', 'Parental Bond', 'Protean', 'Pure Power', 'Shadow Tag', 'Wonder Guard', 'Assist', 'Chatter',
],
},
{
section: "Other Metagames",
column: 2,
},
{
name: "[Gen 7] Balanced Hackmons",
desc: [
"Anything that can be hacked in-game and is usable in local battles is allowed.",
"• <a href=\"https://www.smogon.com/forums/threads/3587475/\">Balanced Hackmons</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3588586/\">BH Suspects and Bans Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3593766/\">BH Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/bh/\">BH Analyses</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Ability Clause', 'OHKO Clause', 'Evasion Moves Clause', 'CFZ Clause', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Groudon-Primal', 'Arena Trap', 'Huge Power', 'Innards Out', 'Magnet Pull', 'Moody', 'Parental Bond', 'Protean', 'Pure Power', 'Shadow Tag', 'Stakeout', 'Water Bubble', 'Wonder Guard', 'Gengarite', 'Chatter', 'Comatose + Sleep Talk'],
},
{
name: "[Gen 7] 1v1",
desc: [
"Bring three Pokémon to Team Preview and choose one to battle.",
"• <a href=\"https://www.smogon.com/forums/threads/3587523/\">1v1</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3592842/\">1v1 Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/1v1/\">1v1 Analyses</a>",
],
mod: 'gen7',
searchShow: false,
teamLength: {
validate: [1, 3],
battle: 1,
},
ruleset: ['Pokemon', 'Species Clause', 'Nickname Clause', 'Moody Clause', 'OHKO Clause', 'Evasion Moves Clause', 'Swagger Clause', 'Endless Battle Clause', 'HP Percentage Mod', 'Cancel Mod', 'Team Preview'],
banlist: [
'Illegal', 'Unreleased', 'Arceus', 'Darkrai', 'Deoxys-Base', 'Deoxys-Attack', 'Deoxys-Defense', 'Dialga', 'Giratina', 'Groudon', 'Ho-Oh', 'Kyogre',
'Kyurem-White', 'Lugia', 'Lunala', 'Marshadow', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Shaymin-Sky', 'Solgaleo', 'Xerneas', 'Yveltal', 'Zekrom',
'Power Construct', 'Perish Song', 'Focus Sash', 'Kangaskhanite', 'Salamencite', 'Chansey + Charm + Seismic Toss', 'Chansey + Charm + Psywave',
'Flash', 'Kinesis', 'Leaf Tornado', 'Mirror Shot', 'Mud Bomb', 'Mud-Slap', 'Muddy Water', 'Night Daze', 'Octazooka', 'Sand Attack', 'Smokescreen',
],
},
{
name: "[Gen 7] 1v1 (suspect test)",
desc: ["• <a href=\"https://www.smogon.com/forums/posts/7530494/\">1v1 Suspect Test</a>"],
mod: 'gen7',
teamLength: {
validate: [1, 3],
battle: 1,
},
ruleset: ['[Gen 7] 1v1'],
banlist: ['Kyurem-Black'],
},
{
name: "[Gen 7] Mix and Mega",
desc: [
"Mega Stones and Primal Orbs can be used on almost any fully evolved Pokémon with no Mega Evolution limit.",
"• <a href=\"https://www.smogon.com/forums/threads/3587740/\">Mix and Mega</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591580/\">Mix and Mega Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/mix_and_mega/\">Mix and Mega Analyses</a>",
],
mod: 'mixandmega',
ruleset: ['Pokemon', 'Standard', 'Mega Rayquaza Clause', 'Team Preview'],
banlist: ['Baton Pass', 'Electrify'],
onValidateTeam: function (team) {
let itemTable = {};
for (let i = 0; i < team.length; i++) {
let item = this.getItem(team[i].item);
if (!item) continue;
if (itemTable[item] && item.megaStone) return ["You are limited to one of each Mega Stone.", "(You have more than one " + this.getItem(item).name + ")"];
if (itemTable[item] && (item.id === 'blueorb' || item.id === 'redorb')) return ["You are limited to one of each Primal Orb.", "(You have more than one " + this.getItem(item).name + ")"];
itemTable[item] = true;
}
},
onValidateSet: function (set) {
let template = this.getTemplate(set.species || set.name);
let item = this.getItem(set.item);
if (!item.megaEvolves && item.id !== 'blueorb' && item.id !== 'redorb') return;
if (template.baseSpecies === item.megaEvolves || (template.baseSpecies === 'Groudon' && item.id === 'redorb') || (template.baseSpecies === 'Kyogre' && item.id === 'blueorb')) return;
if (template.evos.length) return ["" + template.species + " is not allowed to hold " + item.name + " because it's not fully evolved."];
let uberStones = ['beedrillite', 'blazikenite', 'gengarite', 'kangaskhanite', 'mawilite', 'medichamite'];
if (template.tier === 'Uber' || set.ability === 'Power Construct' || uberStones.includes(item.id)) return ["" + template.species + " is not allowed to hold " + item.name + "."];
},
onBegin: function () {
let allPokemon = this.p1.pokemon.concat(this.p2.pokemon);
for (let i = 0, len = allPokemon.length; i < len; i++) {
let pokemon = allPokemon[i];
pokemon.originalSpecies = pokemon.baseTemplate.species;
}
},
onSwitchIn: function (pokemon) {
let oMegaTemplate = this.getTemplate(pokemon.template.originalMega);
if (oMegaTemplate.exists && pokemon.originalSpecies !== oMegaTemplate.baseSpecies) {
// Place volatiles on the Pokémon to show its mega-evolved condition and details
this.add('-start', pokemon, oMegaTemplate.requiredItem || oMegaTemplate.requiredMove, '[silent]');
let oTemplate = this.getTemplate(pokemon.originalSpecies);
if (oTemplate.types.length !== pokemon.template.types.length || oTemplate.types[1] !== pokemon.template.types[1]) {
this.add('-start', pokemon, 'typechange', pokemon.template.types.join('/'), '[silent]');
}
}
},
onSwitchOut: function (pokemon) {
let oMegaTemplate = this.getTemplate(pokemon.template.originalMega);
if (oMegaTemplate.exists && pokemon.originalSpecies !== oMegaTemplate.baseSpecies) {
this.add('-end', pokemon, oMegaTemplate.requiredItem || oMegaTemplate.requiredMove, '[silent]');
}
},
},
{
name: "[Gen 7] Almost Any Ability",
desc: [
"Pokémon can use any ability, barring the few that are banned.",
"• <a href=\"https://www.smogon.com/forums/threads/3587901/\">Almost Any Ability</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3595753/\">AAA Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/aaa/\">AAA Analyses</a>",
],
mod: 'gen7',
searchShow: false,
ruleset: ['Pokemon', 'Standard', 'Ability Clause', 'Ignore Illegal Abilities', 'Team Preview'],
banlist: ['Arceus', 'Archeops', 'Blaziken', 'Darkrai', 'Deoxys', 'Dialga', 'Dragonite', 'Giratina', 'Groudon', 'Ho-Oh', 'Hoopa-Unbound',
'Kartana', 'Keldeo', 'Kyogre', 'Kyurem-Black', 'Kyurem-White', 'Lugia', 'Lunala', 'Marshadow', 'Mewtwo', 'Palkia', 'Pheromosa',
'Rayquaza', 'Regigigas', 'Reshiram', 'Shaymin-Sky', 'Shedinja', 'Slaking', 'Solgaleo', 'Xerneas', 'Yveltal', 'Zekrom',
'Arena Trap', 'Power Construct', 'Shadow Tag', 'Gengarite', 'Kangaskhanite', 'Lucarionite', 'Salamencite', 'Baton Pass',
],
onValidateSet: function (set) {
let bannedAbilities = {'Arena Trap': 1, 'Comatose': 1, 'Contrary': 1, 'Fluffy': 1, 'Fur Coat': 1, 'Huge Power': 1, 'Illusion': 1, 'Imposter': 1, 'Innards Out': 1, 'Parental Bond': 1, 'Power Construct': 1, 'Protean': 1, 'Pure Power': 1, 'Shadow Tag':1, 'Simple':1, 'Speed Boost': 1, 'Stakeout': 1, 'Water Bubble': 1, 'Wonder Guard': 1};
if (set.ability in bannedAbilities) {
let template = this.getTemplate(set.species || set.name);
let legalAbility = false;
for (let i in template.abilities) {
if (set.ability === template.abilities[i]) legalAbility = true;
}
if (!legalAbility) return ['The ability ' + set.ability + ' is banned on Pok\u00e9mon that do not naturally have it.'];
}
},
},
{
name: "[Gen 7] Almost Any Ability (suspect test)",
desc: ["• <a href=\"https://www.smogon.com/forums/posts/7523926/\">Almost Any Ability: Terrakion Suspect</a>"],
mod: 'gen7',
challengeShow: false,
ruleset: ['[Gen 7] Almost Any Ability'],
banlist: [],
onValidateSet: function (set) {
let bannedAbilities = {'Comatose': 1, 'Contrary': 1, 'Fluffy': 1, 'Fur Coat': 1, 'Huge Power': 1, 'Illusion': 1, 'Imposter': 1, 'Innards Out': 1, 'Parental Bond': 1, 'Protean': 1, 'Pure Power': 1, 'Simple':1, 'Speed Boost': 1, 'Stakeout': 1, 'Water Bubble': 1, 'Wonder Guard': 1};
if (set.ability in bannedAbilities) {
let template = this.getTemplate(set.species || set.name);
let legalAbility = false;
for (let i in template.abilities) {
if (set.ability === template.abilities[i]) legalAbility = true;
}
if (!legalAbility) return ['The ability ' + set.ability + ' is banned on Pok\u00e9mon that do not naturally have it.'];
}
},
},
{
name: "[Gen 7] Sketchmons",
desc: [
"Pokémon gain access to one Sketched move.",
"• <a href=\"https://www.smogon.com/forums/threads/3587743/\">Sketchmons</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3606633/\">Sketchmons Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/sketchmons/\">Sketchmons Analyses</a>",
],
mod: 'gen7',
ruleset: ['[Gen 7] OU', 'Allow One Sketch', 'Sketch Clause'],
banlist: ['Porygon-Z'],
noSketch: ['Belly Drum', 'Celebrate', 'Conversion', "Forest's Curse", 'Geomancy', 'Happy Hour', 'Hold Hands', 'Lovely Kiss', 'Purify', 'Quiver Dance', 'Shell Smash', 'Shift Gear', 'Sketch', 'Spore', 'Sticky Web', 'Trick-or-Treat'],
},
{
name: "[Gen 7] Hidden Type",
desc: [
"Pokémon have an added type determined by their IVs. Same as the Hidden Power type.",
"• <a href=\"https://www.smogon.com/forums/threads/3591194/\">Hidden Type</a>",
],
mod: 'gen7',
searchShow: false,
ruleset: ['[Gen 7] OU'],
onModifyTemplate: function (template, pokemon) {
if (template.types.includes(pokemon.hpType)) return;
return Object.assign({addedType: pokemon.hpType}, template);
},
},
{
name: "[Gen 7] 2v2 Doubles",
desc: [
"Double battle where you bring four Pokémon to Team Preview and choose only two.",
"• <a href=\"https://www.smogon.com/forums/threads/3606989/\">2v2 Doubles</a>",
],
mod: 'gen7',
gameType: 'doubles',
searchShow: false,
teamLength: {
validate: [2, 4],
battle: 2,
},
ruleset: ['Gen 7] Doubles OU'],
banlist: ['Tapu Lele', 'Focus Sash', 'Perish Song'],
},
{
name: "[Gen 6] Gen-NEXT OU",
mod: 'gennext',
searchShow: false,
ruleset: ['Pokemon', 'Standard NEXT', 'Team Preview'],
banlist: ['Uber'],
},
// Randomized Metas
///////////////////////////////////////////////////////////////////
{
section: "Randomized Metas",
column: 2,
},
{
name: "[Gen 6] Battle Factory",
mod: 'gen6',
team: 'randomFactory',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod', 'Mega Rayquaza Clause'],
},
{
name: "[Gen 7] BSS Factory",
desc: [
"Randomised 3v3 Singles featuring Pokémon and movesets popular in Battle Spot Singles.",
"• <a href=\"https://www.smogon.com/forums/threads/3604845/\">Information and Suggestions Thread</a>",
],
mod: 'gen7',
team: 'randomBSSFactory',
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
},
{
name: "[Gen 7] Challenge Cup 1v1",
mod: 'gen7',
team: 'randomCC',
teamLength: {
battle: 1,
},
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod', 'Team Preview'],
},
{
name: "[Gen 7] Monotype Random Battle",
mod: 'gen7',
team: 'random',
searchShow: false,
ruleset: ['Pokemon', 'Same Type Clause', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] Hackmons Cup",
desc: ["Randomized teams of level-balanced Pokémon with absolutely any ability, moves, and item."],
mod: 'gen7',
team: 'randomHC',
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] Doubles Hackmons Cup",
mod: 'gen7',
gameType: 'doubles',
team: 'randomHC',
searchShow: false,
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
// RoA Spotlight
///////////////////////////////////////////////////////////////////
{
section: "RoA Spotlight",
column: 3,
},
{
name: "[Gen 4] Doubles OU",
mod: 'gen4',
gameType: 'doubles',
ruleset: ['[Gen 4] OU'],
banlist: [],
},
// ORAS Singles
///////////////////////////////////////////////////////////////////
{
section: "ORAS Singles",
column: 3,
},
{
name: "[Gen 6] OU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/ou/\">ORAS OU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3596900/\">ORAS OU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Swagger Clause', 'Baton Pass Clause'],
banlist: ['Uber', 'Shadow Tag', 'Soul Dew'],
},
{
name: "[Gen 6] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3522911/\">ORAS Ubers</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3535106/\">ORAS Ubers Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['Pokemon', 'Standard', 'Swagger Clause', 'Team Preview', 'Mega Rayquaza Clause'],
},
{
name: "[Gen 6] UU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/uu/\">ORAS UU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3598164/\">ORAS UU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['[Gen 6] OU'],
banlist: ['OU', 'BL', 'Drizzle', 'Drought', 'Baton Pass'],
},
{
name: "[Gen 6] RU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/ru/\">ORAS RU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3574583/\">ORAS RU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['[Gen 6] UU'],
banlist: ['UU', 'BL2'],
},
{
name: "[Gen 6] NU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/nu/\">ORAS NU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3555650/\">ORAS NU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['[Gen 6] RU'],
banlist: ['RU', 'BL3'],
},
{
name: "[Gen 6] PU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/pu/\">ORAS PU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3528743/\">ORAS PU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['[Gen 6] NU'],
banlist: ['NU', 'BL4', 'Chatter'],
unbanlist: ['Baton Pass'],
},
{
name: "[Gen 6] LC",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/formats/lc/\">ORAS LC Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3547566/\">ORAS LC Viability Rankings</a>",
],
mod: 'gen6',
maxLevel: 5,
ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Little Cup'],
banlist: ['LC Uber', 'Gligar', 'Misdreavus', 'Scyther', 'Sneasel', 'Tangela', 'Dragon Rage', 'Sonic Boom', 'Swagger'],
},
{
name: "[Gen 6] Anything Goes",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3523229/\">ORAS Anything Goes</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3548945/\">ORAS AG Resources</a>",
],
mod: 'gen6',
ruleset: ['Pokemon', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Illegal', 'Unreleased'],
},
{
name: "[Gen 6] Monotype",
desc: ["• <a href=\"https://www.smogon.com/forums/posts/7421332/\">ORAS Monotype</a>"],
mod: 'gen6',
searchShow: false,
ruleset: ['Pokemon', 'Standard', 'Swagger Clause', 'Same Type Clause', 'Team Preview'],
banlist: [
'Aegislash', 'Arceus', 'Blaziken', 'Darkrai', 'Deoxys-Base', 'Deoxys-Attack', 'Dialga', 'Genesect', 'Giratina', 'Greninja', 'Groudon', 'Ho-Oh',
'Kyogre', 'Kyurem-White', 'Lugia', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Shaymin-Sky', 'Talonflame', 'Xerneas', 'Yveltal', 'Zekrom',
'Altarianite', 'Charizardite X', 'Damp Rock', 'Gengarite', 'Kangaskhanite', 'Lucarionite', 'Mawilite', 'Metagrossite', 'Sablenite', 'Salamencite', 'Slowbronite', 'Smooth Rock', 'Soul Dew',
],
},
{
name: "[Gen 6] CAP",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3537407/\">ORAS CAP Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3545628/\">ORAS CAP Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/posts/5594694/\">ORAS CAP Sample Teams</a>",
],
mod: 'gen6',
searchShow: false,
ruleset: ['[Gen 6] OU', 'Allow CAP'],
},
{
name: "[Gen 6] Battle Spot Singles",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3527960/\">ORAS Battle Spot Singles</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3554616/\">ORAS BSS Viability Rankings</a>",
],
mod: 'gen6',
maxForcedLevel: 50,
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 6] Inverse Battle",
desc: ["The effectiveness of attacks is inverted."],
mod: 'gen6',
searchShow: false,
ruleset: ['Pokemon', 'Inverse Mod', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Illegal', 'Unreleased'],
},
{
name: "[Gen 6] Random Battle",
mod: 'gen6',
team: 'random',
ruleset: ['PotD', 'Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 6] Custom Game",
mod: 'gen6',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// ORAS Doubles/Triples
///////////////////////////////////////////////////////////////////
{
section: "ORAS Doubles/Triples",
},
{
name: "[Gen 6] Doubles OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3498688/\">ORAS Doubles OU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3535930/\">ORAS Doubles OU Viability Rankings</a>",
],
mod: 'gen6',
gameType: 'doubles',
ruleset: ['Pokemon', 'Standard Doubles', 'Swagger Clause', 'Team Preview'],
banlist: [
'Arceus', 'Dialga', 'Giratina', 'Giratina-Origin', 'Groudon', 'Ho-Oh', 'Kyogre', 'Kyurem-White', 'Lugia', 'Mewtwo',
'Palkia', 'Rayquaza', 'Reshiram', 'Salamence-Mega', 'Salamencite', 'Shaymin-Sky', 'Xerneas', 'Yveltal', 'Zekrom', 'Soul Dew',
'Dark Void', 'Gravity ++ Grass Whistle', 'Gravity ++ Hypnosis', 'Gravity ++ Lovely Kiss', 'Gravity ++ Sing', 'Gravity ++ Sleep Powder',
],
},
{
name: "[Gen 6] Doubles Ubers",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3542746/\">ORAS Doubles Ubers</a>"],
mod: 'gen6',
gameType: 'doubles',
searchShow: false,
ruleset: ['Pokemon', 'Species Clause', 'Moody Clause', 'OHKO Clause', 'Evasion Moves Clause', 'Evasion Abilities Clause', 'Endless Battle Clause', 'HP Percentage Mod', 'Cancel Mod', 'Team Preview'],
banlist: ['Illegal', 'Unreleased', 'Dark Void'],
},
{
name: "[Gen 6] Doubles UU",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3542755/\">ORAS Doubles UU</a>"],
mod: 'gen6',
gameType: 'doubles',
searchShow: false,
ruleset: ['[Gen 6] Doubles OU'],
banlist: [
'Aegislash', 'Amoonguss', 'Arcanine', 'Azumarill', 'Bisharp', 'Breloom', 'Charizard-Mega-Y', 'Charizardite Y',
'Conkeldurr', 'Cresselia', 'Diancie-Mega', 'Diancite', 'Ferrothorn', 'Garchomp', 'Gardevoir-Mega', 'Gardevoirite',
'Gastrodon', 'Gengar', 'Greninja', 'Heatran', 'Hitmontop', 'Hoopa-Unbound', 'Hydreigon', 'Jirachi',
'Kangaskhan-Mega', 'Kangaskhanite', 'Keldeo', 'Kyurem-Black', 'Landorus-Therian', 'Latios', 'Ludicolo', 'Milotic',
'Politoed', 'Raichu', 'Rotom-Wash', 'Scizor', 'Scrafty', 'Shaymin-Sky', 'Suicune', 'Sylveon', 'Talonflame',
'Terrakion', 'Thundurus', 'Togekiss', 'Tyranitar', 'Venusaur', 'Volcanion', 'Weavile', 'Whimsicott', 'Zapdos',
],
},
{
name: "[Gen 6] VGC 2016",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3558332/\">VGC 2016 Rules</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3580592/\">VGC 2016 Viability Rankings</a>",
],
mod: 'gen6',
gameType: 'doubles',
maxForcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
ruleset: ['Pokemon', 'Species Clause', 'Nickname Clause', 'Item Clause', 'Team Preview', 'Cancel Mod'],
banlist: [
'Illegal', 'Unreleased', 'Mew', 'Celebi', 'Jirachi', 'Deoxys', 'Deoxys-Attack', 'Deoxys-Defense', 'Deoxys-Speed', 'Phione', 'Manaphy', 'Darkrai',
'Shaymin', 'Shaymin-Sky', 'Arceus', 'Victini', 'Keldeo', 'Meloetta', 'Genesect', 'Diancie', 'Hoopa', 'Hoopa-Unbound', 'Volcanion', 'Soul Dew',
],
requirePentagon: true,
onValidateTeam: function (team) {
const legends = {'Mewtwo':1, 'Lugia':1, 'Ho-Oh':1, 'Kyogre':1, 'Groudon':1, 'Rayquaza':1, 'Dialga':1, 'Palkia':1, 'Giratina':1, 'Reshiram':1, 'Zekrom':1, 'Kyurem':1, 'Xerneas':1, 'Yveltal':1, 'Zygarde':1};
let n = 0;
for (let i = 0; i < team.length; i++) {
let template = this.getTemplate(team[i].species).baseSpecies;
if (template in legends) n++;
if (n > 2) return ["You can only use up to two legendary Pok\u00E9mon."];
}
},
},
{
name: "[Gen 6] Battle Spot Doubles",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3560820/\">ORAS Battle Spot Doubles Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3560824/\">ORAS BSD Viability Rankings</a>",
],
mod: 'gen6',
gameType: 'doubles',
maxForcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 6] Random Doubles Battle",
mod: 'gen6',
gameType: 'doubles',
team: 'random',
searchShow: false,
ruleset: ['PotD', 'Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 6] Doubles Custom Game",
mod: 'gen6',
gameType: 'doubles',
searchShow: false,
canUseRandomTeam: true,
maxLevel: 9999,
defaultLevel: 100,
debug: true,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
{
name: "[Gen 6] Battle Spot Triples",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3533914/\">ORAS Battle Spot Triples Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3549201/\">ORAS BST Viability Rankings</a>",
],
mod: 'gen6',
gameType: 'triples',
maxForcedLevel: 50,
teamLength: {
validate: [6, 6],
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 6] Triples Custom Game",
mod: 'gen6',
gameType: 'triples',
searchShow: false,
canUseRandomTeam: true,
maxLevel: 9999,
defaultLevel: 100,
debug: true,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// BW2 Singles
///////////////////////////////////////////////////////////////////
{
section: "BW2 Singles",
column: 4,
},
{
name: "[Gen 5] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3599678/\">BW2 OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Baton Pass Clause', 'Swagger Clause', 'Team Preview'],
banlist: ['Uber', 'Drizzle ++ Swift Swim', 'Drought ++ Chlorophyll', 'Sand Stream ++ Sand Rush', 'Soul Dew'],
},
{
name: "[Gen 5] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3550881/\">BW2 Ubers Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6446463/\">BW2 Ubers Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['Pokemon', 'Team Preview', 'Standard Ubers'],
},
{
name: "[Gen 5] UU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3474024/\">BW2 UU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['[Gen 5] OU'],
banlist: ['OU', 'BL', 'Drought', 'Sand Stream', 'Snow Warning'],
},
{
name: "[Gen 5] RU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3473124/\">BW2 RU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['[Gen 5] UU'],
banlist: ['UU', 'BL2', 'Shell Smash + Baton Pass', 'Snow Warning'],
},
{
name: "[Gen 5] NU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3484121/\">BW2 NU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['[Gen 5] RU'],
banlist: ['RU', 'BL3', 'Prankster + Assist'],
},
{
name: "[Gen 5] LC",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3485860/\">BW2 LC Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
maxLevel: 5,
ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Little Cup'],
banlist: ['Berry Juice', 'Soul Dew', 'Dragon Rage', 'Sonic Boom', 'LC Uber', 'Gligar', 'Murkrow', 'Scyther', 'Sneasel', 'Tangela'],
},
{
name: "[Gen 5] GBU Singles",
mod: 'gen5',
searchShow: false,
maxForcedLevel: 50,
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
banlist: ['Dark Void', 'Sky Drop'],
},
{
name: "[Gen 5] Random Battle",
mod: 'gen5',
searchShow: false,
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 5] Custom Game",
mod: 'gen5',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// BW2 Doubles
///////////////////////////////////////////////////////////////////
{
section: 'BW2 Doubles',
column: 4,
},
{
name: "[Gen 5] Doubles OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3533424/\">BW2 Doubles Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3533421/\">BW2 Doubles Viability Ranking</a>",
],
mod: 'gen5',
gameType: 'doubles',
ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Swagger Clause', 'Team Preview'],
banlist: [
'Arceus', 'Dialga', 'Giratina', 'Giratina-Origin', 'Groudon', 'Ho-Oh', 'Kyogre', 'Kyurem-White', 'Jirachi',
'Lugia', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Zekrom', 'Soul Dew', 'Dark Void', 'Sky Drop',
],
},
{
name: "[Gen 5] GBU Doubles",
mod: 'gen5',
gameType: 'doubles',
searchShow: false,
maxForcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
banlist: ['Dark Void', 'Sky Drop'],
},
{
name: "[Gen 5] Doubles Custom Game",
mod: 'gen5',
gameType: 'doubles',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// Past Generations
///////////////////////////////////////////////////////////////////
{
section: "Past Generations",
column: 4,
},
{
name: "[Gen 4] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3551992/\">DPP OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431088/\">DPP Sample Teams</a>",
],
mod: 'gen4',
ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause'],
banlist: ['Uber'],
},
{
name: "[Gen 4] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3505128/\">DPP Ubers Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6446464/\">DPP Ubers Sample Teams</a>",
],
mod: 'gen4',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Arceus'],
},
{
name: "[Gen 4] UU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3503638/\">DPP UU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431088/\">DPP Sample Teams</a>",
],
mod: 'gen4',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Uber', 'OU', 'BL'],
},
{
name: "[Gen 4] LC",
desc: [
"• <a href=\"https://www.smogon.com/dp/articles/little_cup_guide\">DPP LC Guide</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431088/\">DPP Sample Teams</a>",
],
mod: 'gen4',
maxLevel: 5,
ruleset: ['Pokemon', 'Standard', 'Little Cup'],
banlist: ['LC Uber', 'Misdreavus', 'Murkrow', 'Scyther', 'Sneasel', 'Tangela', 'Yanma', 'Berry Juice', 'Deep Sea Tooth', 'Dragon Rage', 'Sonic Boom'],
},
{
name: "[Gen 4] Random Battle",
mod: 'gen4',
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 4] Custom Game",
mod: 'gen4',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions
ruleset: ['Cancel Mod'],
},
{
name: "[Gen 4] Doubles Custom Game",
mod: 'gen4',
gameType: 'doubles',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions
ruleset: ['Cancel Mod'],
},
{
name: "[Gen 3] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3503019/\">ADV OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431087/\">ADV Sample Teams</a>",
],
mod: 'gen3',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Uber', 'Smeargle + Ingrain'],
},
{
name: "[Gen 3] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3536426/\">ADV Ubers Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6446466/\">ADV Ubers Sample Teams</a>",
],
mod: 'gen3',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Wobbuffet + Leftovers'],
},
{
name: "[Gen 3] Random Battle",
mod: 'gen3',
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 3] Custom Game",
mod: 'gen3',
searchShow: false,
debug: true,
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 2] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3556533/\">GSC OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431086/\">GSC Sample Teams</a>",
],
mod: 'gen2',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Uber'],
},
{
name: "[Gen 2] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3507552/\">GSC Ubers Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431086/\">GSC Sample Teams</a>",
],
mod: 'gen2',
searchShow: false,
ruleset: ['Pokemon', 'Standard'],
},
{
name: "[Gen 2] Random Battle",
mod: 'gen2',
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 2] Custom Game",
mod: 'gen2',
searchShow: false,
debug: true,
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 1] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3572352/\">RBY OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431045/\">RBY Sample Teams</a>",
],
mod: 'gen1',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Uber'],
},
{
name: "[Gen 1] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3541329/\">RBY Ubers Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431045/\">RBY Sample Teams</a>",
],
mod: 'gen1',
searchShow: false,
ruleset: ['Pokemon', 'Standard'],
},
{
name: "[Gen 1] OU (tradeback)",
mod: 'gen1',
searchShow: false,
ruleset: ['Pokemon', 'Allow Tradeback', 'Sleep Clause Mod', 'Freeze Clause Mod', 'Species Clause', 'OHKO Clause', 'Evasion Moves Clause', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Uber', 'Unreleased', 'Illegal',
'Nidoking + Fury Attack + Thrash', 'Exeggutor + Poison Powder + Stomp', 'Exeggutor + Sleep Powder + Stomp',
'Exeggutor + Stun Spore + Stomp', 'Jolteon + Focus Energy + Thunder Shock', 'Flareon + Focus Energy + Ember',
],
},
{
name: "[Gen 1] Random Battle",
mod: 'gen1',
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 1] Challenge Cup",
mod: 'gen1',
team: 'randomCC',
searchShow: false,
challengeShow: false,
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 1] Stadium",
mod: 'stadium',
searchShow: false,
ruleset: ['Pokemon', 'Standard', 'Team Preview'],
banlist: ['Uber',
'Nidoking + Fury Attack + Thrash', 'Exeggutor + Poison Powder + Stomp', 'Exeggutor + Sleep Powder + Stomp',
'Exeggutor + Stun Spore + Stomp', 'Jolteon + Focus Energy + Thunder Shock', 'Flareon + Focus Energy + Ember',
],
},
{
name: "[Gen 1] Custom Game",
mod: 'gen1',
searchShow: false,
debug: true,
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
];
| config/formats.js | 'use strict';
// Note: This is the list of formats
// The rules that formats use are stored in data/rulesets.js
exports.Formats = [
// SM Singles
///////////////////////////////////////////////////////////////////
{
section: "SM Singles",
},
{
name: "[Gen 7] Random Battle",
desc: ["Randomized teams of level-balanced Pokémon with sets that are generated to be competitively viable."],
mod: 'gen7',
team: 'random',
ruleset: ['PotD', 'Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] Unrated Random Battle",
mod: 'gen7',
team: 'random',
challengeShow: false,
rated: false,
ruleset: ['PotD', 'Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3608656/\">OU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3587177/\">OU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3590726/\">OU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3606650/\">OU Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Standard', 'Team Preview'],
banlist: ['Uber', 'Arena Trap', 'Power Construct', 'Shadow Tag', 'Baton Pass'],
},
{
name: "[Gen 7] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3587184/\">Ubers Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591388/\">Ubers Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3599816/\">Ubers Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Mega Rayquaza Clause'],
banlist: ['Baton Pass'],
},
{
name: "[Gen 7] UU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3616332/\">UU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3613279/\">UU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591880/\">UU Sample Teams</a>",
],
mod: 'gen7',
searchShow: false,
ruleset: ['[Gen 7] OU'],
banlist: ['OU', 'BL', 'Drizzle', 'Mewnium Z'],
},
{
name: "[Gen 7] UU (suspect test)",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3616332/\">UU Suspect Test</a>"],
mod: 'gen7',
challengeShow: false,
ruleset: ['[Gen 7] UU'],
banlist: [],
},
{
name: "[Gen 7] RU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3615711/\">RU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3602279/\">RU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3598090/\">RU Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['[Gen 7] UU'],
banlist: ['UU', 'BL2', 'Aurora Veil'],
},
{
name: "[Gen 7] NU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3616091/\">NU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3607629/\">NU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3606112/\">NU Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['[Gen 7] RU'],
banlist: ['RU', 'BL3', 'Drought'],
},
{
name: "[Gen 7] PU",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3614120/\">PU Metagame Discussion</a>"],
mod: 'gen7',
searchShow: false,
ruleset: ['[Gen 7] NU'],
banlist: ['NU', 'BL4'],
},
{
name: "[Gen 7] PU (suspect test)",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3614120/\">PU Suspect Test</a>"],
mod: 'gen7',
ruleset: ['[Gen 7] PU'],
unbanlist: ['Hariyama'],
},
{
name: "[Gen 7] LC",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3587196/\">LC Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/dex/sm/formats/lc/\">LC Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3609771/\">LC Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3588679/\">LC Sample Teams</a>",
],
mod: 'gen7',
maxLevel: 5,
ruleset: ['Pokemon', 'Standard', 'Swagger Clause', 'Team Preview', 'Little Cup'],
banlist: ['Cutiefly', 'Drifloon', 'Gligar', 'Gothita', 'Meditite', 'Misdreavus', 'Murkrow', 'Porygon', 'Scyther', 'Sneasel', 'Swirlix', 'Tangela', 'Vulpix-Base', 'Yanma', 'Eevium Z', 'Dragon Rage', 'Sonic Boom'],
},
{
name: "[Gen 7] Monotype",
desc: [
"All the Pokémon on a team must share a type.",
"• <a href=\"https://www.smogon.com/forums/threads/3587204/\">Monotype Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3589809/\">Monotype Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3599682/\">Monotype Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Standard', 'Swagger Clause', 'Same Type Clause', 'Team Preview'],
banlist: [
'Aegislash', 'Arceus', 'Blaziken', 'Darkrai', 'Deoxys-Base', 'Deoxys-Attack', 'Dialga', 'Genesect', 'Giratina', 'Groudon', 'Ho-Oh', 'Hoopa-Unbound', 'Kartana', 'Kyogre', 'Kyurem-White',
'Lugia', 'Lunala', 'Magearna', 'Marshadow', 'Mewtwo', 'Palkia', 'Pheromosa', 'Rayquaza', 'Reshiram', 'Shaymin-Sky', 'Solgaleo', 'Tapu Lele', 'Xerneas', 'Yveltal', 'Zekrom', 'Zygarde',
'Battle Bond', 'Damp Rock', 'Gengarite', 'Kangaskhanite', 'Lucarionite', 'Mawilite', 'Medichamite', 'Metagrossite', 'Salamencite', 'Smooth Rock', 'Terrain Extender', 'Baton Pass',
],
},
{
name: "[Gen 7] Anything Goes",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3587441/\">Anything Goes</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591711/\">AG Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/ag/\">AG Analyses</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Illegal', 'Unreleased'],
},
{
name: "[Gen 7] CAP",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3587865/\">CAP Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3597893/\">CAP Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/posts/7203358/\">CAP Sample Teams</a>",
],
mod: 'gen7',
ruleset: ['[Gen 7] OU', 'Allow CAP'],
banlist: ['Tomohawk + Earth Power', 'Tomohawk + Reflect'],
},
{
name: "[Gen 7] CAP LC",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3599594/\">CAP LC</a>"],
mod: 'gen7',
searchShow: false,
maxLevel: 5,
ruleset: ['[Gen 7] LC', 'Allow CAP'],
},
{
name: "[Gen 7] Battle Spot Singles",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3601012/\">Introduction to Battle Spot Singles</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3605970/\">Battle Spot Singles Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3601658/\">Battle Spot Singles Roles Compendium</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3593055/\">Battle Spot Singles Sample Teams</a>",
],
mod: 'gen7',
maxForcedLevel: 50,
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 7] Battle Spot Special 6",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3614104/\">Battle Spot Special</a>"],
mod: 'gen7',
maxForcedLevel: 50,
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
banlist: ['Aegislash', 'Blaziken', 'Charizard', 'Ferrothorn', 'Garchomp', 'Gengar', 'Greninja', 'Gyarados', 'Hippowdon', 'Landorus',
'Landorus-Therian', 'Lucario', 'Mamoswine', 'Mimikyu', 'Porygon2', 'Salamence', 'Tapu Fini', 'Tapu Koko', 'Tapu Lele',
],
requirePentagon: true,
},
{
name: "[Gen 7] Custom Game",
mod: 'gen7',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
teamLength: {
validate: [1, 24],
battle: 24,
},
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// SM Doubles
///////////////////////////////////////////////////////////////////
{
section: "SM Doubles",
},
{
name: "[Gen 7] Random Doubles Battle",
mod: 'gen7',
gameType: 'doubles',
team: 'random',
ruleset: ['PotD', 'Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] Doubles OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3610992/\">Doubles OU Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3592903/\">Doubles OU Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3590987/\">Doubles OU Sample Teams</a>",
],
mod: 'gen7',
gameType: 'doubles',
ruleset: ['Pokemon', 'Standard Doubles', 'Swagger Clause', 'Team Preview'],
banlist: ['Arceus', 'Dialga', 'Giratina', 'Giratina-Origin', 'Groudon', 'Ho-Oh', 'Jirachi', 'Kyogre', 'Kyurem-White',
'Lugia', 'Lunala', 'Magearna', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Solgaleo', 'Xerneas', 'Yveltal', 'Zekrom',
'Power Construct', 'Eevium Z', 'Kangaskhanite', 'Dark Void', 'Gravity ++ Grass Whistle', 'Gravity ++ Hypnosis', 'Gravity ++ Lovely Kiss', 'Gravity ++ Sing', 'Gravity ++ Sleep Powder',
],
},
{
name: "[Gen 7] Doubles Ubers",
mod: 'gen7',
gameType: 'doubles',
ruleset: ['Pokemon', 'Standard Doubles', 'Team Preview'],
banlist: ['Illegal', 'Unreleased', 'Dark Void'],
},
{
name: "[Gen 7] Doubles UU",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3598014/\">Doubles UU Metagame Discussion</a>"],
mod: 'gen7',
gameType: 'doubles',
ruleset: ['[Gen 7] Doubles OU'],
banlist: [
'Aegislash', 'Amoonguss', 'Arcanine', 'Bronzong', 'Celesteela', 'Deoxys-Attack', 'Diancie', 'Excadrill', 'Ferrothorn',
'Garchomp', 'Gastrodon', 'Genesect', 'Heatran', 'Hoopa-Unbound', 'Jirachi', 'Kartana', 'Kingdra', 'Kyurem-Black',
'Landorus-Therian', 'Ludicolo', 'Marowak-Alola', 'Marshadow', 'Milotic', 'Mimikyu', 'Ninetales-Alola', 'Oranguru',
'Pelipper', 'Politoed', 'Porygon2', 'Scrafty', 'Snorlax', 'Suicune', 'Tapu Bulu', 'Tapu Fini', 'Tapu Koko',
'Tapu Lele', 'Tyranitar', 'Volcanion', 'Volcarona', 'Weavile', 'Whimsicott', 'Zapdos', 'Zygarde-Base',
'Charizardite Y', 'Diancite', 'Gardevoirite', 'Gengarite', 'Kangaskhanite', 'Mawilite', 'Metagrossite', 'Salamencite', 'Swampertite',
],
},
{
name: "[Gen 7] VGC 2017",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3583926/\">VGC 2017 Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591794/\">VGC 2017 Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3590391/\">VGC 2017 Sample Teams</a>",
],
mod: 'gen7',
gameType: 'doubles',
forcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
timer: {starting: 15 * 60 - 10, perTurn: 10, maxPerTurn: 60, maxFirstTurn: 90, timeoutAutoChoose: true},
ruleset: ['Pokemon', 'Species Clause', 'Nickname Clause', 'Item Clause', 'Team Preview', 'Cancel Mod', 'Alola Pokedex'],
banlist: ['Illegal', 'Unreleased', 'Solgaleo', 'Lunala', 'Necrozma', 'Magearna', 'Marshadow', 'Zygarde', 'Mega'],
requirePlus: true,
},
{
name: "[Gen 7] Battle Spot Doubles",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3595001/\">Battle Spot Doubles Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3593890/\">Battle Spot Doubles Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3595859/\">Battle Spot Doubles Sample Teams</a>",
],
mod: 'gen7',
gameType: 'doubles',
maxForcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 7] Doubles Custom Game",
mod: 'gen7',
gameType: 'doubles',
searchShow: false,
canUseRandomTeam: true,
maxLevel: 9999,
defaultLevel: 100,
debug: true,
teamLength: {
validate: [2, 24],
battle: 24,
},
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// Other Metagames
///////////////////////////////////////////////////////////////////
{
section: "OM of the Month",
column: 2,
},
{
name: "[Gen 7] Ultimate Z",
desc: [
"Use any type of Z-Crystal on any move and as many times per battle as desired.",
"• <a href=\"https://www.smogon.com/forums/threads/3609393/\">Ultimate Z</a>",
],
mod: 'ultimatez',
ruleset: ['[Gen 7] OU'],
banlist: ['Kyurem-Black', 'Celebrate', 'Conversion', 'Happy Hour', 'Hold Hands'],
},
{
name: "[Gen 6] Balanced Hackmons",
desc: ["• <a href=\"https://www.smogon.com/dex/xy/formats/bh/\">ORAS Balanced Hackmons</a>"],
mod: 'gen6',
searchShow: false,
ruleset: ['Pokemon', 'Ability Clause', 'OHKO Clause', 'Evasion Moves Clause', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Groudon-Primal', 'Kyogre-Primal', 'Aerilate + Pixilate + Refrigerate > 1',
'Arena Trap', 'Huge Power', 'Moody', 'Parental Bond', 'Protean', 'Pure Power', 'Shadow Tag', 'Wonder Guard', 'Assist', 'Chatter',
],
},
{
section: "Other Metagames",
column: 2,
},
{
name: "[Gen 7] Balanced Hackmons",
desc: [
"Anything that can be hacked in-game and is usable in local battles is allowed.",
"• <a href=\"https://www.smogon.com/forums/threads/3587475/\">Balanced Hackmons</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3588586/\">BH Suspects and Bans Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3593766/\">BH Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/bh/\">BH Analyses</a>",
],
mod: 'gen7',
ruleset: ['Pokemon', 'Ability Clause', 'OHKO Clause', 'Evasion Moves Clause', 'CFZ Clause', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Groudon-Primal', 'Arena Trap', 'Huge Power', 'Innards Out', 'Magnet Pull', 'Moody', 'Parental Bond', 'Protean', 'Pure Power', 'Shadow Tag', 'Stakeout', 'Water Bubble', 'Wonder Guard', 'Gengarite', 'Chatter', 'Comatose + Sleep Talk'],
},
{
name: "[Gen 7] 1v1",
desc: [
"Bring three Pokémon to Team Preview and choose one to battle.",
"• <a href=\"https://www.smogon.com/forums/threads/3587523/\">1v1</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3592842/\">1v1 Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/1v1/\">1v1 Analyses</a>",
],
mod: 'gen7',
searchShow: false,
teamLength: {
validate: [1, 3],
battle: 1,
},
ruleset: ['Pokemon', 'Species Clause', 'Nickname Clause', 'Moody Clause', 'OHKO Clause', 'Evasion Moves Clause', 'Swagger Clause', 'Endless Battle Clause', 'HP Percentage Mod', 'Cancel Mod', 'Team Preview'],
banlist: [
'Illegal', 'Unreleased', 'Arceus', 'Darkrai', 'Deoxys-Base', 'Deoxys-Attack', 'Deoxys-Defense', 'Dialga', 'Giratina', 'Groudon', 'Ho-Oh', 'Kyogre',
'Kyurem-White', 'Lugia', 'Lunala', 'Marshadow', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Shaymin-Sky', 'Solgaleo', 'Xerneas', 'Yveltal', 'Zekrom',
'Power Construct', 'Perish Song', 'Focus Sash', 'Kangaskhanite', 'Salamencite', 'Chansey + Charm + Seismic Toss', 'Chansey + Charm + Psywave',
'Flash', 'Kinesis', 'Leaf Tornado', 'Mirror Shot', 'Mud Bomb', 'Mud-Slap', 'Muddy Water', 'Night Daze', 'Octazooka', 'Sand Attack', 'Smokescreen',
],
},
{
name: "[Gen 7] 1v1 (suspect test)",
desc: ["• <a href=\"https://www.smogon.com/forums/posts/7530494/\">1v1 Suspect Test</a>"],
mod: 'gen7',
teamLength: {
validate: [1, 3],
battle: 1,
},
ruleset: ['[Gen 7] 1v1'],
banlist: ['Kyurem-Black'],
},
{
name: "[Gen 7] Mix and Mega",
desc: [
"Mega Stones and Primal Orbs can be used on almost any fully evolved Pokémon with no Mega Evolution limit.",
"• <a href=\"https://www.smogon.com/forums/threads/3587740/\">Mix and Mega</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3591580/\">Mix and Mega Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/mix_and_mega/\">Mix and Mega Analyses</a>",
],
mod: 'mixandmega',
ruleset: ['Pokemon', 'Standard', 'Mega Rayquaza Clause', 'Team Preview'],
banlist: ['Baton Pass', 'Electrify'],
onValidateTeam: function (team) {
let itemTable = {};
for (let i = 0; i < team.length; i++) {
let item = this.getItem(team[i].item);
if (!item) continue;
if (itemTable[item] && item.megaStone) return ["You are limited to one of each Mega Stone.", "(You have more than one " + this.getItem(item).name + ")"];
if (itemTable[item] && (item.id === 'blueorb' || item.id === 'redorb')) return ["You are limited to one of each Primal Orb.", "(You have more than one " + this.getItem(item).name + ")"];
itemTable[item] = true;
}
},
onValidateSet: function (set) {
let template = this.getTemplate(set.species || set.name);
let item = this.getItem(set.item);
if (!item.megaEvolves && item.id !== 'blueorb' && item.id !== 'redorb') return;
if (template.baseSpecies === item.megaEvolves || (template.baseSpecies === 'Groudon' && item.id === 'redorb') || (template.baseSpecies === 'Kyogre' && item.id === 'blueorb')) return;
if (template.evos.length) return ["" + template.species + " is not allowed to hold " + item.name + " because it's not fully evolved."];
let uberStones = ['beedrillite', 'blazikenite', 'gengarite', 'kangaskhanite', 'mawilite', 'medichamite'];
if (template.tier === 'Uber' || set.ability === 'Power Construct' || uberStones.includes(item.id)) return ["" + template.species + " is not allowed to hold " + item.name + "."];
},
onBegin: function () {
let allPokemon = this.p1.pokemon.concat(this.p2.pokemon);
for (let i = 0, len = allPokemon.length; i < len; i++) {
let pokemon = allPokemon[i];
pokemon.originalSpecies = pokemon.baseTemplate.species;
}
},
onSwitchIn: function (pokemon) {
let oMegaTemplate = this.getTemplate(pokemon.template.originalMega);
if (oMegaTemplate.exists && pokemon.originalSpecies !== oMegaTemplate.baseSpecies) {
// Place volatiles on the Pokémon to show its mega-evolved condition and details
this.add('-start', pokemon, oMegaTemplate.requiredItem || oMegaTemplate.requiredMove, '[silent]');
let oTemplate = this.getTemplate(pokemon.originalSpecies);
if (oTemplate.types.length !== pokemon.template.types.length || oTemplate.types[1] !== pokemon.template.types[1]) {
this.add('-start', pokemon, 'typechange', pokemon.template.types.join('/'), '[silent]');
}
}
},
onSwitchOut: function (pokemon) {
let oMegaTemplate = this.getTemplate(pokemon.template.originalMega);
if (oMegaTemplate.exists && pokemon.originalSpecies !== oMegaTemplate.baseSpecies) {
this.add('-end', pokemon, oMegaTemplate.requiredItem || oMegaTemplate.requiredMove, '[silent]');
}
},
},
{
name: "[Gen 7] Almost Any Ability",
desc: [
"Pokémon can use any ability, barring the few that are banned.",
"• <a href=\"https://www.smogon.com/forums/threads/3587901/\">Almost Any Ability</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3595753/\">AAA Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/aaa/\">AAA Analyses</a>",
],
mod: 'gen7',
searchShow: false,
ruleset: ['Pokemon', 'Standard', 'Ability Clause', 'Ignore Illegal Abilities', 'Team Preview'],
banlist: ['Arceus', 'Archeops', 'Blaziken', 'Darkrai', 'Deoxys', 'Dialga', 'Dragonite', 'Giratina', 'Groudon', 'Ho-Oh', 'Hoopa-Unbound',
'Kartana', 'Keldeo', 'Kyogre', 'Kyurem-Black', 'Kyurem-White', 'Lugia', 'Lunala', 'Marshadow', 'Mewtwo', 'Palkia', 'Pheromosa',
'Rayquaza', 'Regigigas', 'Reshiram', 'Shaymin-Sky', 'Shedinja', 'Slaking', 'Solgaleo', 'Xerneas', 'Yveltal', 'Zekrom',
'Arena Trap', 'Power Construct', 'Shadow Tag', 'Gengarite', 'Kangaskhanite', 'Lucarionite', 'Salamencite', 'Baton Pass',
],
onValidateSet: function (set) {
let bannedAbilities = {'Arena Trap': 1, 'Comatose': 1, 'Contrary': 1, 'Fluffy': 1, 'Fur Coat': 1, 'Huge Power': 1, 'Illusion': 1, 'Imposter': 1, 'Innards Out': 1, 'Parental Bond': 1, 'Power Construct': 1, 'Protean': 1, 'Pure Power': 1, 'Shadow Tag':1, 'Simple':1, 'Speed Boost': 1, 'Stakeout': 1, 'Water Bubble': 1, 'Wonder Guard': 1};
if (set.ability in bannedAbilities) {
let template = this.getTemplate(set.species || set.name);
let legalAbility = false;
for (let i in template.abilities) {
if (set.ability === template.abilities[i]) legalAbility = true;
}
if (!legalAbility) return ['The ability ' + set.ability + ' is banned on Pok\u00e9mon that do not naturally have it.'];
}
},
},
{
name: "[Gen 7] Almost Any Ability (suspect test)",
desc: ["• <a href=\"https://www.smogon.com/forums/posts/7523926/\">Almost Any Ability: Terrakion Suspect</a>"],
mod: 'gen7',
challengeShow: false,
ruleset: ['[Gen 7] Almost Any Ability'],
banlist: [],
onValidateSet: function (set) {
let bannedAbilities = {'Comatose': 1, 'Contrary': 1, 'Fluffy': 1, 'Fur Coat': 1, 'Huge Power': 1, 'Illusion': 1, 'Imposter': 1, 'Innards Out': 1, 'Parental Bond': 1, 'Protean': 1, 'Pure Power': 1, 'Simple':1, 'Speed Boost': 1, 'Stakeout': 1, 'Water Bubble': 1, 'Wonder Guard': 1};
if (set.ability in bannedAbilities) {
let template = this.getTemplate(set.species || set.name);
let legalAbility = false;
for (let i in template.abilities) {
if (set.ability === template.abilities[i]) legalAbility = true;
}
if (!legalAbility) return ['The ability ' + set.ability + ' is banned on Pok\u00e9mon that do not naturally have it.'];
}
},
},
{
name: "[Gen 7] Sketchmons",
desc: [
"Pokémon gain access to one Sketched move.",
"• <a href=\"https://www.smogon.com/forums/threads/3587743/\">Sketchmons</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3606633/\">Sketchmons Resources</a>",
"• <a href=\"https://www.smogon.com/tiers/om/analyses/sketchmons/\">Sketchmons Analyses</a>",
],
mod: 'gen7',
ruleset: ['[Gen 7] OU', 'Allow One Sketch', 'Sketch Clause'],
banlist: ['Porygon-Z'],
noSketch: ['Belly Drum', 'Celebrate', 'Conversion', "Forest's Curse", 'Geomancy', 'Happy Hour', 'Hold Hands', 'Lovely Kiss', 'Purify', 'Quiver Dance', 'Shell Smash', 'Shift Gear', 'Sketch', 'Spore', 'Sticky Web', 'Trick-or-Treat'],
},
{
name: "[Gen 7] Hidden Type",
desc: [
"Pokémon have an added type determined by their IVs. Same as the Hidden Power type.",
"• <a href=\"https://www.smogon.com/forums/threads/3591194/\">Hidden Type</a>",
],
mod: 'gen7',
searchShow: false,
ruleset: ['[Gen 7] OU'],
onModifyTemplate: function (template, pokemon) {
if (template.types.includes(pokemon.hpType)) return;
return Object.assign({addedType: pokemon.hpType}, template);
},
},
{
name: "[Gen 7] 2v2 Doubles",
desc: [
"Double battle where you bring four Pokémon to Team Preview and choose only two.",
"• <a href=\"https://www.smogon.com/forums/threads/3606989/\">2v2 Doubles</a>",
],
mod: 'gen7',
gameType: 'doubles',
searchShow: false,
teamLength: {
validate: [2, 4],
battle: 2,
},
ruleset: ['Gen 7] Doubles OU'],
banlist: ['Tapu Lele', 'Focus Sash', 'Perish Song'],
},
{
name: "[Gen 6] Gen-NEXT OU",
mod: 'gennext',
searchShow: false,
ruleset: ['Pokemon', 'Standard NEXT', 'Team Preview'],
banlist: ['Uber'],
},
// Randomized Metas
///////////////////////////////////////////////////////////////////
{
section: "Randomized Metas",
column: 2,
},
{
name: "[Gen 6] Battle Factory",
mod: 'gen6',
team: 'randomFactory',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod', 'Mega Rayquaza Clause'],
},
{
name: "[Gen 7] BSS Factory",
desc: [
"Randomised 3v3 Singles featuring Pokémon and movesets popular in Battle Spot Singles.",
"• <a href=\"https://www.smogon.com/forums/threads/3604845/\">Information and Suggestions Thread</a>",
],
mod: 'gen7',
team: 'randomBSSFactory',
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
},
{
name: "[Gen 7] Challenge Cup 1v1",
mod: 'gen7',
team: 'randomCC',
teamLength: {
battle: 1,
},
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod', 'Team Preview'],
},
{
name: "[Gen 7] Monotype Random Battle",
mod: 'gen7',
team: 'random',
searchShow: false,
ruleset: ['Pokemon', 'Same Type Clause', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] Hackmons Cup",
desc: ["Randomized teams of level-balanced Pokémon with absolutely any ability, moves, and item."],
mod: 'gen7',
team: 'randomHC',
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 7] Doubles Hackmons Cup",
mod: 'gen7',
gameType: 'doubles',
team: 'randomHC',
searchShow: false,
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
// RoA Spotlight
///////////////////////////////////////////////////////////////////
{
section: "RoA Spotlight",
column: 3,
},
{
name: "[Gen 4] Doubles OU",
mod: 'gen4',
gameType: 'doubles',
ruleset: ['[Gen 4] OU'],
banlist: [],
},
// ORAS Singles
///////////////////////////////////////////////////////////////////
{
section: "ORAS Singles",
column: 3,
},
{
name: "[Gen 6] OU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/ou/\">ORAS OU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3596900/\">ORAS OU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Swagger Clause', 'Baton Pass Clause'],
banlist: ['Uber', 'Shadow Tag', 'Soul Dew'],
},
{
name: "[Gen 6] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3522911/\">ORAS Ubers</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3535106/\">ORAS Ubers Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['Pokemon', 'Standard', 'Swagger Clause', 'Team Preview', 'Mega Rayquaza Clause'],
},
{
name: "[Gen 6] UU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/uu/\">ORAS UU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3598164/\">ORAS UU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['[Gen 6] OU'],
banlist: ['OU', 'BL', 'Drizzle', 'Drought', 'Baton Pass'],
},
{
name: "[Gen 6] RU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/ru/\">ORAS RU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3574583/\">ORAS RU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['[Gen 6] UU'],
banlist: ['UU', 'BL2'],
},
{
name: "[Gen 6] NU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/nu/\">ORAS NU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3555650/\">ORAS NU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['[Gen 6] RU'],
banlist: ['RU', 'BL3'],
},
{
name: "[Gen 6] PU",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/tags/pu/\">ORAS PU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3528743/\">ORAS PU Viability Rankings</a>",
],
mod: 'gen6',
ruleset: ['[Gen 6] NU'],
banlist: ['NU', 'BL4', 'Chatter'],
unbanlist: ['Baton Pass'],
},
{
name: "[Gen 6] LC",
desc: [
"• <a href=\"https://www.smogon.com/dex/xy/formats/lc/\">ORAS LC Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3547566/\">ORAS LC Viability Rankings</a>",
],
mod: 'gen6',
maxLevel: 5,
ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Little Cup'],
banlist: ['LC Uber', 'Gligar', 'Misdreavus', 'Scyther', 'Sneasel', 'Tangela', 'Dragon Rage', 'Sonic Boom', 'Swagger'],
},
{
name: "[Gen 6] Anything Goes",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3523229/\">ORAS Anything Goes</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3548945/\">ORAS AG Resources</a>",
],
mod: 'gen6',
ruleset: ['Pokemon', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Illegal', 'Unreleased'],
},
{
name: "[Gen 6] Monotype",
desc: ["• <a href=\"https://www.smogon.com/forums/posts/7421332/\">ORAS Monotype</a>"],
mod: 'gen6',
searchShow: false,
ruleset: ['Pokemon', 'Standard', 'Swagger Clause', 'Same Type Clause', 'Team Preview'],
banlist: [
'Aegislash', 'Arceus', 'Blaziken', 'Darkrai', 'Deoxys-Base', 'Deoxys-Attack', 'Dialga', 'Genesect', 'Giratina', 'Greninja', 'Groudon', 'Ho-Oh',
'Kyogre', 'Kyurem-White', 'Lugia', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Shaymin-Sky', 'Talonflame', 'Xerneas', 'Yveltal', 'Zekrom',
'Altarianite', 'Charizardite X', 'Damp Rock', 'Gengarite', 'Kangaskhanite', 'Lucarionite', 'Mawilite', 'Metagrossite', 'Sablenite', 'Salamencite', 'Slowbronite', 'Smooth Rock', 'Soul Dew',
],
},
{
name: "[Gen 6] CAP",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3537407/\">ORAS CAP Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3545628/\">ORAS CAP Viability Rankings</a>",
"• <a href=\"https://www.smogon.com/forums/posts/5594694/\">ORAS CAP Sample Teams</a>",
],
mod: 'gen6',
searchShow: false,
ruleset: ['[Gen 6] OU', 'Allow CAP'],
},
{
name: "[Gen 6] Battle Spot Singles",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3527960/\">ORAS Battle Spot Singles</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3554616/\">ORAS BSS Viability Rankings</a>",
],
mod: 'gen6',
maxForcedLevel: 50,
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 6] Inverse Battle",
desc: ["The effectiveness of attacks is inverted."],
mod: 'gen6',
searchShow: false,
ruleset: ['Pokemon', 'Inverse Mod', 'Endless Battle Clause', 'Team Preview', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Illegal', 'Unreleased'],
},
{
name: "[Gen 6] Random Battle",
mod: 'gen6',
team: 'random',
ruleset: ['PotD', 'Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 6] Custom Game",
mod: 'gen6',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// ORAS Doubles/Triples
///////////////////////////////////////////////////////////////////
{
section: "ORAS Doubles/Triples",
},
{
name: "[Gen 6] Doubles OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3498688/\">ORAS Doubles OU Banlist</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3535930/\">ORAS Doubles OU Viability Rankings</a>",
],
mod: 'gen6',
gameType: 'doubles',
ruleset: ['Pokemon', 'Standard Doubles', 'Swagger Clause', 'Team Preview'],
banlist: [
'Arceus', 'Dialga', 'Giratina', 'Giratina-Origin', 'Groudon', 'Ho-Oh', 'Kyogre', 'Kyurem-White', 'Lugia', 'Mewtwo',
'Palkia', 'Rayquaza', 'Reshiram', 'Salamence-Mega', 'Salamencite', 'Shaymin-Sky', 'Xerneas', 'Yveltal', 'Zekrom', 'Soul Dew',
'Dark Void', 'Gravity ++ Grass Whistle', 'Gravity ++ Hypnosis', 'Gravity ++ Lovely Kiss', 'Gravity ++ Sing', 'Gravity ++ Sleep Powder',
],
},
{
name: "[Gen 6] Doubles Ubers",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3542746/\">ORAS Doubles Ubers</a>"],
mod: 'gen6',
gameType: 'doubles',
searchShow: false,
ruleset: ['Pokemon', 'Species Clause', 'Moody Clause', 'OHKO Clause', 'Evasion Moves Clause', 'Evasion Abilities Clause', 'Endless Battle Clause', 'HP Percentage Mod', 'Cancel Mod', 'Team Preview'],
banlist: ['Illegal', 'Unreleased', 'Dark Void'],
},
{
name: "[Gen 6] Doubles UU",
desc: ["• <a href=\"https://www.smogon.com/forums/threads/3542755/\">ORAS Doubles UU</a>"],
mod: 'gen6',
gameType: 'doubles',
searchShow: false,
ruleset: ['[Gen 6] Doubles OU'],
banlist: [
'Aegislash', 'Amoonguss', 'Arcanine', 'Azumarill', 'Bisharp', 'Breloom', 'Charizard-Mega-Y', 'Charizardite Y',
'Conkeldurr', 'Cresselia', 'Diancie-Mega', 'Diancite', 'Ferrothorn', 'Garchomp', 'Gardevoir-Mega', 'Gardevoirite',
'Gastrodon', 'Gengar', 'Greninja', 'Heatran', 'Hitmontop', 'Hoopa-Unbound', 'Hydreigon', 'Jirachi',
'Kangaskhan-Mega', 'Kangaskhanite', 'Keldeo', 'Kyurem-Black', 'Landorus-Therian', 'Latios', 'Ludicolo', 'Milotic',
'Politoed', 'Raichu', 'Rotom-Wash', 'Scizor', 'Scrafty', 'Shaymin-Sky', 'Suicune', 'Sylveon', 'Talonflame',
'Terrakion', 'Thundurus', 'Togekiss', 'Tyranitar', 'Venusaur', 'Volcanion', 'Weavile', 'Whimsicott', 'Zapdos',
],
},
{
name: "[Gen 6] VGC 2016",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3558332/\">VGC 2016 Rules</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3580592/\">VGC 2016 Viability Rankings</a>",
],
mod: 'gen6',
gameType: 'doubles',
maxForcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
ruleset: ['Pokemon', 'Species Clause', 'Nickname Clause', 'Item Clause', 'Team Preview', 'Cancel Mod'],
banlist: [
'Illegal', 'Unreleased', 'Mew', 'Celebi', 'Jirachi', 'Deoxys', 'Deoxys-Attack', 'Deoxys-Defense', 'Deoxys-Speed', 'Phione', 'Manaphy', 'Darkrai',
'Shaymin', 'Shaymin-Sky', 'Arceus', 'Victini', 'Keldeo', 'Meloetta', 'Genesect', 'Diancie', 'Hoopa', 'Hoopa-Unbound', 'Volcanion', 'Soul Dew',
],
requirePentagon: true,
onValidateTeam: function (team) {
const legends = {'Mewtwo':1, 'Lugia':1, 'Ho-Oh':1, 'Kyogre':1, 'Groudon':1, 'Rayquaza':1, 'Dialga':1, 'Palkia':1, 'Giratina':1, 'Reshiram':1, 'Zekrom':1, 'Kyurem':1, 'Xerneas':1, 'Yveltal':1, 'Zygarde':1};
let n = 0;
for (let i = 0; i < team.length; i++) {
let template = this.getTemplate(team[i].species).baseSpecies;
if (template in legends) n++;
if (n > 2) return ["You can only use up to two legendary Pok\u00E9mon."];
}
},
},
{
name: "[Gen 6] Battle Spot Doubles",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3560820/\">ORAS Battle Spot Doubles Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3560824/\">ORAS BSD Viability Rankings</a>",
],
mod: 'gen6',
gameType: 'doubles',
maxForcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 6] Random Doubles Battle",
mod: 'gen6',
gameType: 'doubles',
team: 'random',
searchShow: false,
ruleset: ['PotD', 'Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 6] Doubles Custom Game",
mod: 'gen6',
gameType: 'doubles',
searchShow: false,
canUseRandomTeam: true,
maxLevel: 9999,
defaultLevel: 100,
debug: true,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
{
name: "[Gen 6] Battle Spot Triples",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3533914/\">ORAS Battle Spot Triples Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3549201/\">ORAS BST Viability Rankings</a>",
],
mod: 'gen6',
gameType: 'triples',
maxForcedLevel: 50,
teamLength: {
validate: [6, 6],
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
requirePentagon: true,
},
{
name: "[Gen 6] Triples Custom Game",
mod: 'gen6',
gameType: 'triples',
searchShow: false,
canUseRandomTeam: true,
maxLevel: 9999,
defaultLevel: 100,
debug: true,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// BW2 Singles
///////////////////////////////////////////////////////////////////
{
section: "BW2 Singles",
column: 4,
},
{
name: "[Gen 5] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3599678/\">BW2 OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Baton Pass Clause', 'Swagger Clause', 'Team Preview'],
banlist: ['Uber', 'Drizzle ++ Swift Swim', 'Drought ++ Chlorophyll', 'Sand Stream ++ Sand Rush', 'Soul Dew'],
},
{
name: "[Gen 5] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3550881/\">BW2 Ubers Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6446463/\">BW2 Ubers Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['Pokemon', 'Team Preview', 'Standard Ubers'],
},
{
name: "[Gen 5] UU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3474024/\">BW2 UU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['[Gen 5] OU'],
banlist: ['OU', 'BL', 'Drought', 'Sand Stream', 'Snow Warning'],
},
{
name: "[Gen 5] RU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3473124/\">BW2 RU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['[Gen 5] UU'],
banlist: ['UU', 'BL2', 'Shell Smash + Baton Pass', 'Snow Warning'],
},
{
name: "[Gen 5] NU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3484121/\">BW2 NU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
ruleset: ['[Gen 5] RU'],
banlist: ['RU', 'BL3', 'Prankster + Assist'],
},
{
name: "[Gen 5] LC",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3485860/\">BW2 LC Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431094/\">BW2 Sample Teams</a>",
],
mod: 'gen5',
maxLevel: 5,
ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Little Cup'],
banlist: ['Berry Juice', 'Soul Dew', 'Dragon Rage', 'Sonic Boom', 'LC Uber', 'Gligar', 'Murkrow', 'Scyther', 'Sneasel', 'Tangela'],
},
{
name: "[Gen 5] GBU Singles",
mod: 'gen5',
searchShow: false,
maxForcedLevel: 50,
teamLength: {
validate: [3, 6],
battle: 3,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
banlist: ['Dark Void', 'Sky Drop'],
},
{
name: "[Gen 5] Random Battle",
mod: 'gen5',
searchShow: false,
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 5] Custom Game",
mod: 'gen5',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// BW2 Doubles
///////////////////////////////////////////////////////////////////
{
section: 'BW2 Doubles',
column: 4,
},
{
name: "[Gen 5] Doubles OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3533424/\">BW2 Doubles Metagame Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/threads/3533421/\">BW2 Doubles Viability Ranking</a>",
],
mod: 'gen5',
gameType: 'doubles',
ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Swagger Clause', 'Team Preview'],
banlist: [
'Arceus', 'Dialga', 'Giratina', 'Giratina-Origin', 'Groudon', 'Ho-Oh', 'Kyogre', 'Kyurem-White', 'Jirachi',
'Lugia', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Zekrom', 'Soul Dew', 'Dark Void', 'Sky Drop',
],
},
{
name: "[Gen 5] GBU Doubles",
mod: 'gen5',
gameType: 'doubles',
searchShow: false,
maxForcedLevel: 50,
teamLength: {
validate: [4, 6],
battle: 4,
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview'],
banlist: ['Dark Void', 'Sky Drop'],
},
{
name: "[Gen 5] Doubles Custom Game",
mod: 'gen5',
gameType: 'doubles',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions, for serious (other than team preview)
ruleset: ['Team Preview', 'Cancel Mod'],
},
// Past Generations
///////////////////////////////////////////////////////////////////
{
section: "Past Generations",
column: 4,
},
{
name: "[Gen 4] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3551992/\">DPP OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431088/\">DPP Sample Teams</a>",
],
mod: 'gen4',
ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause'],
banlist: ['Uber'],
},
{
name: "[Gen 4] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3505128/\">DPP Ubers Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6446464/\">DPP Ubers Sample Teams</a>",
],
mod: 'gen4',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Arceus'],
},
{
name: "[Gen 4] UU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3503638/\">DPP UU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431088/\">DPP Sample Teams</a>",
],
mod: 'gen4',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Uber', 'OU', 'BL'],
},
{
name: "[Gen 4] LC",
desc: [
"• <a href=\"https://www.smogon.com/dp/articles/little_cup_guide\">DPP LC Guide</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431088/\">DPP Sample Teams</a>",
],
mod: 'gen4',
maxLevel: 5,
ruleset: ['Pokemon', 'Standard', 'Little Cup'],
banlist: ['LC Uber', 'Misdreavus', 'Murkrow', 'Scyther', 'Sneasel', 'Tangela', 'Yanma', 'Berry Juice', 'Deep Sea Tooth', 'Dragon Rage', 'Sonic Boom'],
},
{
name: "[Gen 4] Random Battle",
mod: 'gen4',
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 4] Custom Game",
mod: 'gen4',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions
ruleset: ['Cancel Mod'],
},
{
name: "[Gen 4] Doubles Custom Game",
mod: 'gen4',
gameType: 'doubles',
searchShow: false,
canUseRandomTeam: true,
debug: true,
maxLevel: 9999,
defaultLevel: 100,
// no restrictions
ruleset: ['Cancel Mod'],
},
{
name: "[Gen 3] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3503019/\">ADV OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431087/\">ADV Sample Teams</a>",
],
mod: 'gen3',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Uber', 'Smeargle + Ingrain'],
},
{
name: "[Gen 3] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3536426/\">ADV Ubers Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6446466/\">ADV Ubers Sample Teams</a>",
],
mod: 'gen3',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Wobbuffet + Leftovers'],
},
{
name: "[Gen 3] Random Battle",
mod: 'gen3',
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 3] Custom Game",
mod: 'gen3',
searchShow: false,
debug: true,
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 2] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3556533/\">GSC OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431086/\">GSC Sample Teams</a>",
],
mod: 'gen2',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Uber'],
},
{
name: "[Gen 2] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3507552/\">GSC Ubers Discussion</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431086/\">GSC Sample Teams</a>",
],
mod: 'gen2',
searchShow: false,
ruleset: ['Pokemon', 'Standard'],
},
{
name: "[Gen 2] Random Battle",
mod: 'gen2',
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 2] Custom Game",
mod: 'gen2',
searchShow: false,
debug: true,
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 1] OU",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3572352/\">RBY OU Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431045/\">RBY Sample Teams</a>",
],
mod: 'gen1',
ruleset: ['Pokemon', 'Standard'],
banlist: ['Uber'],
},
{
name: "[Gen 1] Ubers",
desc: [
"• <a href=\"https://www.smogon.com/forums/threads/3541329/\">RBY Ubers Viability Ranking</a>",
"• <a href=\"https://www.smogon.com/forums/posts/6431045/\">RBY Sample Teams</a>",
],
mod: 'gen1',
searchShow: false,
ruleset: ['Pokemon', 'Standard'],
},
{
name: "[Gen 1] OU (tradeback)",
mod: 'gen1',
searchShow: false,
ruleset: ['Pokemon', 'Allow Tradeback', 'Sleep Clause Mod', 'Freeze Clause Mod', 'Species Clause', 'OHKO Clause', 'Evasion Moves Clause', 'HP Percentage Mod', 'Cancel Mod'],
banlist: ['Uber', 'Unreleased', 'Illegal',
'Nidoking + Fury Attack + Thrash', 'Exeggutor + Poison Powder + Stomp', 'Exeggutor + Sleep Powder + Stomp',
'Exeggutor + Stun Spore + Stomp', 'Jolteon + Focus Energy + Thunder Shock', 'Flareon + Focus Energy + Ember',
],
},
{
name: "[Gen 1] Random Battle",
mod: 'gen1',
team: 'random',
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 1] Challenge Cup",
mod: 'gen1',
team: 'randomCC',
searchShow: false,
challengeShow: false,
ruleset: ['Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod', 'Cancel Mod'],
},
{
name: "[Gen 1] Stadium",
mod: 'stadium',
searchShow: false,
ruleset: ['Pokemon', 'Standard', 'Team Preview'],
banlist: ['Uber',
'Nidoking + Fury Attack + Thrash', 'Exeggutor + Poison Powder + Stomp', 'Exeggutor + Sleep Powder + Stomp',
'Exeggutor + Stun Spore + Stomp', 'Jolteon + Focus Energy + Thunder Shock', 'Flareon + Focus Energy + Ember',
],
},
{
name: "[Gen 1] Custom Game",
mod: 'gen1',
searchShow: false,
debug: true,
ruleset: ['Pokemon', 'HP Percentage Mod', 'Cancel Mod'],
},
];
| Remove PU suspect test
| config/formats.js | Remove PU suspect test | <ide><path>onfig/formats.js
<ide> desc: ["• <a href=\"https://www.smogon.com/forums/threads/3614120/\">PU Metagame Discussion</a>"],
<ide>
<ide> mod: 'gen7',
<del> searchShow: false,
<ide> ruleset: ['[Gen 7] NU'],
<ide> banlist: ['NU', 'BL4'],
<del> },
<del> {
<del> name: "[Gen 7] PU (suspect test)",
<del> desc: ["• <a href=\"https://www.smogon.com/forums/threads/3614120/\">PU Suspect Test</a>"],
<del>
<del> mod: 'gen7',
<del> ruleset: ['[Gen 7] PU'],
<del> unbanlist: ['Hariyama'],
<ide> },
<ide> {
<ide> name: "[Gen 7] LC", |
|
Java | apache-2.0 | 1b952dc8ef6003ad8fef02e903335a5a7e199d6f | 0 | GoogleCloudPlatform/google-cloud-eclipse,GoogleCloudPlatform/google-cloud-eclipse,GoogleCloudPlatform/google-cloud-eclipse,GoogleCloudPlatform/google-cloud-eclipse | /*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.tools.eclipse.login.ui;
import org.eclipse.core.databinding.observable.Diffs;
import org.eclipse.core.databinding.observable.value.AbstractObservableValue;
import org.eclipse.jface.databinding.swt.DisplayRealm;
/**
* An object that represents and binds to the email value of an {@link AccountSelector}, whose
* changes (i.e., account selection changes in the combo box) can be tracked by value change
* listeners.
*/
public class AccountSelectorObservableValue extends AbstractObservableValue<String> {
private String oldValue;
private AccountSelector accountSelector;
public AccountSelectorObservableValue(final AccountSelector accountSelector) {
super(DisplayRealm.getRealm(accountSelector.getDisplay()));
this.accountSelector = accountSelector;
accountSelector.addSelectionListener(new Runnable() {
@Override
public void run() {
String newValue = accountSelector.getSelectedEmail();
fireValueChange(Diffs.createValueDiff(oldValue, newValue));
oldValue = newValue;
}
});
}
@Override
public Object getValueType() {
return String.class;
}
@Override
protected String doGetValue() {
return accountSelector.getSelectedEmail();
}
@Override
protected void doSetValue(final String value) {
accountSelector.selectAccount(value);
}
}
| plugins/com.google.cloud.tools.eclipse.login/src/com/google/cloud/tools/eclipse/login/ui/AccountSelectorObservableValue.java | /*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.tools.eclipse.login.ui;
import org.eclipse.core.databinding.observable.Diffs;
import org.eclipse.core.databinding.observable.value.AbstractObservableValue;
import org.eclipse.jface.databinding.swt.DisplayRealm;
/**
* An object that represents and binds to the email value of an {@link AccountSelector}, whose
* changes (i.e., account selection changes in the combo box) can be tracked by value change
* listeners.
*/
public class AccountSelectorObservableValue extends AbstractObservableValue {
private String oldValue;
private AccountSelector accountSelector;
public AccountSelectorObservableValue(final AccountSelector accountSelector) {
super(DisplayRealm.getRealm(accountSelector.getDisplay()));
this.accountSelector = accountSelector;
accountSelector.addSelectionListener(new Runnable() {
@Override
public void run() {
String newValue = accountSelector.getSelectedEmail();
fireValueChange(Diffs.createValueDiff(oldValue, newValue));
oldValue = newValue;
}
});
}
@Override
public Object getValueType() {
return String.class;
}
@Override
protected Object doGetValue() {
return accountSelector.getSelectedEmail();
}
@Override
protected void doSetValue(final Object value) {
accountSelector.selectAccount((String) value);
}
}
| fix warning (#2819)
* ignore remote systems explorer junk
* generics
| plugins/com.google.cloud.tools.eclipse.login/src/com/google/cloud/tools/eclipse/login/ui/AccountSelectorObservableValue.java | fix warning (#2819) | <ide><path>lugins/com.google.cloud.tools.eclipse.login/src/com/google/cloud/tools/eclipse/login/ui/AccountSelectorObservableValue.java
<ide> * changes (i.e., account selection changes in the combo box) can be tracked by value change
<ide> * listeners.
<ide> */
<del>public class AccountSelectorObservableValue extends AbstractObservableValue {
<add>public class AccountSelectorObservableValue extends AbstractObservableValue<String> {
<ide>
<ide> private String oldValue;
<ide> private AccountSelector accountSelector;
<ide> }
<ide>
<ide> @Override
<del> protected Object doGetValue() {
<add> protected String doGetValue() {
<ide> return accountSelector.getSelectedEmail();
<ide> }
<ide>
<ide> @Override
<del> protected void doSetValue(final Object value) {
<del> accountSelector.selectAccount((String) value);
<add> protected void doSetValue(final String value) {
<add> accountSelector.selectAccount(value);
<ide> }
<ide> } |
|
Java | apache-2.0 | 17cea9837e1fca8aabe5140e37487e66d482b998 | 0 | PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder | package org.pdxfinder.services;
import org.pdxfinder.services.constants.DataUrl;
import org.pdxfinder.services.dto.europepmc.Publication;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service
public class PublicationService {
private RestTemplate restTemplate;
private static final String PUBLICATION_PREFIX = "PMID:";
private static final String EMPTY_STRING = "";
public PublicationService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@SuppressWarnings("WeakerAccess")
public List<Publication> getEuropePmcPublications(List<String> pubMedIds) {
pubMedIds = sanitizePubMedIds(pubMedIds);
List<Publication> publications = new ArrayList<>();
pubMedIds.forEach(pubMedId->{
String api = String.format("%s?query=ext_id:%s&resultType=core&format=json", DataUrl.EUROPE_PMC_URL.get(), pubMedId);
publications.add(restTemplate.getForObject(api, Publication.class));
});
return publications;
}
@SuppressWarnings("WeakerAccess")
public List<String> sanitizePubMedIds(List<String> pubMedIds){
List<String> cleanedPubMedIds = new ArrayList<>();
pubMedIds.forEach(pubMedId -> {
pubMedId = pubMedId.replace("\u00A0", EMPTY_STRING);
pubMedId = pubMedId.toUpperCase();
pubMedId = pubMedId.replace(PUBLICATION_PREFIX, EMPTY_STRING);
pubMedId = pubMedId.replaceAll("\\s+",EMPTY_STRING);
if (pubMedId.contains(";")){
cleanedPubMedIds.addAll(Arrays.asList(pubMedId.split(";")));
}else {
cleanedPubMedIds.add(pubMedId);
}
});
return cleanedPubMedIds;
}
}
| data-services/src/main/java/org/pdxfinder/services/PublicationService.java | package org.pdxfinder.services;
import org.pdxfinder.services.constants.DataUrl;
import org.pdxfinder.services.dto.europepmc.Publication;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service
public class PublicationService {
private RestTemplate restTemplate;
private static final String PUBLICATION_PREFIX = "PMID:";
private static final String EMPTY_STRING = "";
public PublicationService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@SuppressWarnings("WeakerAccess")
public List<Publication> getEuropePmcPublications(List<String> pubMedIds) {
pubMedIds = sanitizePubMedIds(pubMedIds);
List<Publication> publications = new ArrayList<>();
pubMedIds.forEach(pubMedId->{
String api = String.format("%s?query=ext_id:%s&resultType=core&format=json", DataUrl.EUROPE_PMC_URL.get(), pubMedId);
publications.add(restTemplate.getForObject(api, Publication.class));
});
return publications;
}
@SuppressWarnings("WeakerAccess")
public List<String> sanitizePubMedIds(List<String> pubMedIds){
List<String> cleanedPubMedIds = new ArrayList<>();
pubMedIds.forEach(pubMedId -> {
pubMedId = pubMedId.replaceAll("\u00A0", EMPTY_STRING);
pubMedId = pubMedId.toUpperCase();
pubMedId = pubMedId.replace(PUBLICATION_PREFIX, EMPTY_STRING);
pubMedId = pubMedId.replaceAll("\\s+",EMPTY_STRING);
if (pubMedId.contains(";")){
cleanedPubMedIds.addAll(Arrays.asList(pubMedId.split(";")));
}else {
cleanedPubMedIds.add(pubMedId);
}
});
return cleanedPubMedIds;
}
}
| Fix publications error
- Fix code smell reported by sonar (replace instead replaceAll)
| data-services/src/main/java/org/pdxfinder/services/PublicationService.java | Fix publications error | <ide><path>ata-services/src/main/java/org/pdxfinder/services/PublicationService.java
<ide> public List<String> sanitizePubMedIds(List<String> pubMedIds){
<ide> List<String> cleanedPubMedIds = new ArrayList<>();
<ide> pubMedIds.forEach(pubMedId -> {
<del> pubMedId = pubMedId.replaceAll("\u00A0", EMPTY_STRING);
<add> pubMedId = pubMedId.replace("\u00A0", EMPTY_STRING);
<ide> pubMedId = pubMedId.toUpperCase();
<ide> pubMedId = pubMedId.replace(PUBLICATION_PREFIX, EMPTY_STRING);
<ide> pubMedId = pubMedId.replaceAll("\\s+",EMPTY_STRING); |
|
Java | apache-2.0 | b7b6fc13b4a1cc5392f1ff428defca9647e421a9 | 0 | doom369/netty,johnou/netty,ejona86/netty,zer0se7en/netty,andsel/netty,tbrooks8/netty,johnou/netty,zer0se7en/netty,Spikhalskiy/netty,artgon/netty,fenik17/netty,artgon/netty,fenik17/netty,zer0se7en/netty,fenik17/netty,tbrooks8/netty,Spikhalskiy/netty,tbrooks8/netty,doom369/netty,andsel/netty,tbrooks8/netty,Spikhalskiy/netty,doom369/netty,NiteshKant/netty,doom369/netty,artgon/netty,NiteshKant/netty,netty/netty,NiteshKant/netty,Spikhalskiy/netty,zer0se7en/netty,NiteshKant/netty,ejona86/netty,andsel/netty,artgon/netty,artgon/netty,netty/netty,andsel/netty,netty/netty,NiteshKant/netty,johnou/netty,netty/netty,fenik17/netty,tbrooks8/netty,ejona86/netty,netty/netty,Spikhalskiy/netty,doom369/netty,andsel/netty,johnou/netty,zer0se7en/netty,johnou/netty,ejona86/netty,fenik17/netty,ejona86/netty | /*
* Copyright 2014 The Netty Project
*
* The Netty Project 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 io.netty.handler.codec.compression;
import com.ning.compress.BufferRecycler;
import com.ning.compress.lzf.ChunkEncoder;
import com.ning.compress.lzf.LZFEncoder;
import com.ning.compress.lzf.util.ChunkEncoderFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import static com.ning.compress.lzf.LZFChunk.*;
/**
* Compresses a {@link ByteBuf} using the LZF format.
*
* See original <a href="http://oldhome.schmorp.de/marc/liblzf.html">LZF package</a>
* and <a href="https://github.com/ning/compress/wiki/LZFFormat">LZF format</a> for full description.
*/
public class LzfEncoder extends MessageToByteEncoder<ByteBuf> {
/**
* Minimum block size ready for compression. Blocks with length
* less than {@link #MIN_BLOCK_TO_COMPRESS} will write as uncompressed.
*/
private static final int MIN_BLOCK_TO_COMPRESS = 16;
/**
* Underlying decoder in use.
*/
private final ChunkEncoder encoder;
/**
* Object that handles details of buffer recycling.
*/
private final BufferRecycler recycler;
/**
* Creates a new LZF encoder with the most optimal available methods for underlying data access.
* It will "unsafe" instance if one can be used on current JVM.
* It should be safe to call this constructor as implementations are dynamically loaded; however, on some
* non-standard platforms it may be necessary to use {@link #LzfEncoder(boolean)} with {@code true} param.
*/
public LzfEncoder() {
this(false, MAX_CHUNK_LEN);
}
/**
* Creates a new LZF encoder with specified encoding instance.
*
* @param safeInstance
* If {@code true} encoder will use {@link ChunkEncoder} that only uses standard JDK access methods,
* and should work on all Java platforms and JVMs.
* Otherwise encoder will try to use highly optimized {@link ChunkEncoder} implementation that uses
* Sun JDK's {@link sun.misc.Unsafe} class (which may be included by other JDK's as well).
*/
public LzfEncoder(boolean safeInstance) {
this(safeInstance, MAX_CHUNK_LEN);
}
/**
* Creates a new LZF encoder with specified total length of encoded chunk. You can configure it to encode
* your data flow more efficient if you know the average size of messages that you send.
*
* @param totalLength
* Expected total length of content to compress; only matters for outgoing messages that is smaller
* than maximum chunk size (64k), to optimize encoding hash tables.
*/
public LzfEncoder(int totalLength) {
this(false, totalLength);
}
/**
* Creates a new LZF encoder with specified settings.
*
* @param safeInstance
* If {@code true} encoder will use {@link ChunkEncoder} that only uses standard JDK access methods,
* and should work on all Java platforms and JVMs.
* Otherwise encoder will try to use highly optimized {@link ChunkEncoder} implementation that uses
* Sun JDK's {@link sun.misc.Unsafe} class (which may be included by other JDK's as well).
* @param totalLength
* Expected total length of content to compress; only matters for outgoing messages that is smaller
* than maximum chunk size (64k), to optimize encoding hash tables.
*/
public LzfEncoder(boolean safeInstance, int totalLength) {
super(false);
if (totalLength < MIN_BLOCK_TO_COMPRESS || totalLength > MAX_CHUNK_LEN) {
throw new IllegalArgumentException("totalLength: " + totalLength +
" (expected: " + MIN_BLOCK_TO_COMPRESS + '-' + MAX_CHUNK_LEN + ')');
}
encoder = safeInstance ?
ChunkEncoderFactory.safeNonAllocatingInstance(totalLength)
: ChunkEncoderFactory.optimalNonAllocatingInstance(totalLength);
recycler = BufferRecycler.instance();
}
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
final int length = in.readableBytes();
final int idx = in.readerIndex();
final byte[] input;
final int inputPtr;
if (in.hasArray()) {
input = in.array();
inputPtr = in.arrayOffset() + idx;
} else {
input = recycler.allocInputBuffer(length);
in.getBytes(idx, input, 0, length);
inputPtr = 0;
}
final int maxOutputLength = LZFEncoder.estimateMaxWorkspaceSize(length);
out.ensureWritable(maxOutputLength);
final byte[] output = out.array();
final int outputPtr = out.arrayOffset() + out.writerIndex();
final int outputLength = LZFEncoder.appendEncoded(encoder,
input, inputPtr, length, output, outputPtr) - outputPtr;
out.writerIndex(out.writerIndex() + outputLength);
in.skipBytes(length);
if (!in.hasArray()) {
recycler.releaseInputBuffer(input);
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
encoder.close();
super.handlerRemoved(ctx);
}
}
| codec/src/main/java/io/netty/handler/codec/compression/LzfEncoder.java | /*
* Copyright 2014 The Netty Project
*
* The Netty Project 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 io.netty.handler.codec.compression;
import com.ning.compress.BufferRecycler;
import com.ning.compress.lzf.ChunkEncoder;
import com.ning.compress.lzf.LZFEncoder;
import com.ning.compress.lzf.util.ChunkEncoderFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import static com.ning.compress.lzf.LZFChunk.*;
/**
* Compresses a {@link ByteBuf} using the LZF format.
*
* See original <a href="http://oldhome.schmorp.de/marc/liblzf.html">LZF package</a>
* and <a href="https://github.com/ning/compress/wiki/LZFFormat">LZF format</a> for full description.
*/
public class LzfEncoder extends MessageToByteEncoder<ByteBuf> {
/**
* Minimum block size ready for compression. Blocks with length
* less than {@link #MIN_BLOCK_TO_COMPRESS} will write as uncompressed.
*/
private static final int MIN_BLOCK_TO_COMPRESS = 16;
/**
* Underlying decoder in use.
*/
private final ChunkEncoder encoder;
/**
* Object that handles details of buffer recycling.
*/
private final BufferRecycler recycler;
/**
* Creates a new LZF encoder with the most optimal available methods for underlying data access.
* It will "unsafe" instance if one can be used on current JVM.
* It should be safe to call this constructor as implementations are dynamically loaded; however, on some
* non-standard platforms it may be necessary to use {@link #LzfEncoder(boolean)} with {@code true} param.
*/
public LzfEncoder() {
this(false, MAX_CHUNK_LEN);
}
/**
* Creates a new LZF encoder with specified encoding instance.
*
* @param safeInstance
* If {@code true} encoder will use {@link ChunkEncoder} that only uses standard JDK access methods,
* and should work on all Java platforms and JVMs.
* Otherwise encoder will try to use highly optimized {@link ChunkEncoder} implementation that uses
* Sun JDK's {@link sun.misc.Unsafe} class (which may be included by other JDK's as well).
*/
public LzfEncoder(boolean safeInstance) {
this(safeInstance, MAX_CHUNK_LEN);
}
/**
* Creates a new LZF encoder with specified total length of encoded chunk. You can configure it to encode
* your data flow more efficient if you know the average size of messages that you send.
*
* @param totalLength
* Expected total length of content to compress; only matters for outgoing messages that is smaller
* than maximum chunk size (64k), to optimize encoding hash tables.
*/
public LzfEncoder(int totalLength) {
this(false, totalLength);
}
/**
* Creates a new LZF encoder with specified settings.
*
* @param safeInstance
* If {@code true} encoder will use {@link ChunkEncoder} that only uses standard JDK access methods,
* and should work on all Java platforms and JVMs.
* Otherwise encoder will try to use highly optimized {@link ChunkEncoder} implementation that uses
* Sun JDK's {@link sun.misc.Unsafe} class (which may be included by other JDK's as well).
* @param totalLength
* Expected total length of content to compress; only matters for outgoing messages that is smaller
* than maximum chunk size (64k), to optimize encoding hash tables.
*/
public LzfEncoder(boolean safeInstance, int totalLength) {
super(false);
if (totalLength < MIN_BLOCK_TO_COMPRESS || totalLength > MAX_CHUNK_LEN) {
throw new IllegalArgumentException("totalLength: " + totalLength +
" (expected: " + MIN_BLOCK_TO_COMPRESS + '-' + MAX_CHUNK_LEN + ')');
}
encoder = safeInstance ?
ChunkEncoderFactory.safeNonAllocatingInstance(totalLength)
: ChunkEncoderFactory.optimalNonAllocatingInstance(totalLength);
recycler = BufferRecycler.instance();
}
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
final int length = in.readableBytes();
final int idx = in.readerIndex();
final byte[] input;
final int inputPtr;
if (in.hasArray()) {
input = in.array();
inputPtr = in.arrayOffset() + idx;
} else {
input = recycler.allocInputBuffer(length);
in.getBytes(idx, input, 0, length);
inputPtr = 0;
}
final int maxOutputLength = LZFEncoder.estimateMaxWorkspaceSize(length);
out.ensureWritable(maxOutputLength);
final byte[] output = out.array();
final int outputPtr = out.arrayOffset() + out.writerIndex();
final int outputLength = LZFEncoder.appendEncoded(encoder,
input, inputPtr, length, output, outputPtr) - outputPtr;
out.writerIndex(out.writerIndex() + outputLength);
in.skipBytes(length);
if (!in.hasArray()) {
recycler.releaseInputBuffer(input);
}
}
}
| Close encoder when handlerRemoved. (#9950)
Motivation:
We should close encoder when `LzfEncoder` was removed from pipeline.
Modification:
call `encoder.close` when `handlerRemoved` triggered.
Result:
Close encoder to release internal buffer. | codec/src/main/java/io/netty/handler/codec/compression/LzfEncoder.java | Close encoder when handlerRemoved. (#9950) | <ide><path>odec/src/main/java/io/netty/handler/codec/compression/LzfEncoder.java
<ide> recycler.releaseInputBuffer(input);
<ide> }
<ide> }
<add>
<add> @Override
<add> public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
<add> encoder.close();
<add> super.handlerRemoved(ctx);
<add> }
<ide> } |
|
JavaScript | bsd-2-clause | 66f1b7477c995d3607ef70f8a34cda54907e510a | 0 | gregr/ina,gregr/ina,gregr/ina | 'use strict';
// TODO: read(/annotate), write
function is_nil(datum) { return datum === null; }
function is_closure(datum) { return typeof datum === 'function'; }
function is_boolean(datum) { return typeof datum === 'boolean'; }
function is_text(datum) { return typeof datum === 'string'; }
function is_number(datum) { return typeof datum === 'number'; }
function is_int32(datum) {
return (typeof datum === 'number') && (datum === (datum | 0));
}
function is_pair(datum) {
return (typeof datum === 'object') && (datum !== null);
}
function env_extend(env, datum) { return [datum, env]; }
function env_ref(env, idx) {
for (; idx > 0; --idx) { env = env[1]; }
return env[0];
}
function env_find(env, found) {
var index = 0;
for (; env !== null; ++index) {
if (found(env[0])) { return index; }
env = env[1];
}
return undefined;
}
function env_find_name(env, name) {
var index = env_find(env, function(b){return (name === b[0]);});
if (index === undefined) { throw ['unbound variable', name]; }
return index;
}
function env_lookup(env, name) {
var index = env_find_name(env, name);
return env_ref(env, index)[1];
}
// TODO: Expect annotated syntax.
function syntax_list_of_length(len, xs, err) {
var result = [];
for (; len > 0; --len) {
if (!is_pair(xs)) { throw err; }
result.push(xs[0]);
xs = xs[1];
}
if (!is_nil(xs)) { throw err; }
return result;
}
function syntax_list(xs, err) {
var result = [];
while (is_pair(xs)) {
result.push(xs[0]);
xs = xs[1];
}
if (!is_nil(xs)) { throw err; }
return result;
}
function array_to_list(xs) {
var i = xs.length - 1;
var result = null;
for (; i >= 0; --i) { result = [xs[i], result]; }
return result;
}
function array_map(f, xs) {
var i = xs.length - 1;
var result = [];
result.length = xs.length;
for (; i >= 0; --i) { result[i] = f(xs[i]); }
return result;
}
function evaluate(stx) {
// TODO: It may be better to pass these registers around in an explicit
// context rather than capturing them in closures. It may also be more
// efficient to represent continuations as tagged data structures.
var result, env = null, ks = [function(){return null;}];
// TODO: Might as well inline this everywhere.
function unwind() { return ks.pop(); }
function denote_literal(datum) {
return function() { result = datum; return unwind(); };
}
function denote_var(senv, name) {
var index = env_find_name(senv, name);
if (env_ref(senv, index)[1] !== false) { throw ['invalid syntax', name]; }
return function() { result = env_ref(env, index); return unwind(); };
}
function build_app(senv, dp, as) {
if (is_nil(as)) { return dp; }
var da = denote(senv, as[0]);
var dapp = function(){
var kenv = env;
ks.push(function() {
var proc = result;
if (!is_closure(proc)) { throw ['cannot apply non-procedure', proc]; }
ks.push(function() { return proc(result); });
env = kenv;
return da;
});
return dp;
};
return build_app(senv, dapp, as[1]);
}
function denote_app(senv, stx) {
var err = ['invalid application', stx];
if (!is_pair(stx)) { throw err; }
syntax_list(stx[1], err);
return build_app(senv, denote(senv, stx[0]), stx[1]);
}
function denote(senv, stx) {
if (is_nil(stx) || is_boolean(stx) || is_number(stx)) {
return denote_literal(stx);
} else if (is_text(stx)) {
return denote_var(senv, stx);
} else if (is_pair(stx)) {
if (is_text(stx[0])) {
var special = env_lookup(senv, stx[0]);
if (typeof special === 'function') { return special(senv, stx[1]); }
}
return denote_app(senv, stx);
} else { throw ['unknown syntax', stx]; }
}
function build_lambda(senv, params, body) {
if (is_nil(params)) { return denote(senv, body); }
senv = env_extend(senv, [params[0], false]);
var dl = build_lambda(senv, params[1], body);
return function() {
var clo_env = env;
result = function(arg) {
env = env_extend(clo_env, arg);
return dl;
};
return unwind();
};
}
function denote_lambda(senv, stx) {
var err = ['invalid lambda', stx];
stx = syntax_list_of_length(2, stx, err);
var params = stx[0], body = stx[1];
if (!is_pair(params)) { throw err; }
array_map(function(p){ if (!is_text(p)) { throw err; } },
syntax_list(params, err));
return build_lambda(senv, params, body);
}
function denote_if(senv, stx) {
stx = syntax_list_of_length(3, stx, ['invalid if', stx]);
var dc = denote(senv, stx[0]);
var dt = denote(senv, stx[1]);
var df = denote(senv, stx[2]);
return function() {
var kenv = env;
ks.push(function(){
env = kenv;
if (result === false) { return df; } else { return dt; }
});
return dc;
};
}
function denote_quote(senv, stx) {
stx = syntax_list_of_length(1, stx, ['invalid quote', stx]);
return denote_literal(stx[0]);
}
function denote_qq(senv, stx) {
// TODO:
}
function denote_let(senv, stx) {
var err = ['invalid let', stx];
stx = syntax_list_of_length(2, stx, err);
var bindings = array_map(function(b) {
return syntax_list_of_length(2, b, err);
}, syntax_list(stx[0], err));
var params = array_map(function(b) {
if (!is_text(b[0])) { throw err; } return b[0];
}, bindings);
var args = array_map(function(b) { return b[1]; }, bindings);
var body = stx[1];
var dp = build_lambda(senv, array_to_list(params), body);
return build_app(senv, dp, array_to_list(args));
}
var operatives = [
['let', denote_let],
['quasiquote', denote_qq],
['quote', denote_quote],
['if', denote_if],
['lambda', denote_lambda]];
function native_procedure_huh(datum) {
result = is_closure(datum); return unwind();
}
function native_boolean_huh(datum) {
result = is_boolean(datum); return unwind();
}
function native_pair_huh(datum) { result = is_pair(datum); return unwind(); }
function native_nil_huh(datum) { result = is_nil(datum); return unwind(); }
function native_text_huh(datum) { result = is_text(datum); return unwind(); }
function native_number_huh(datum) { result = is_number(datum); return unwind(); }
function native_int32_huh(datum) { result = is_int32(datum); return unwind(); }
function make_eq(name, is_x) {
return function(x0) {
if (!is_x(x0)) { throw ["invalid argument to '"+name+"'", x0]; }
result = function(x1) {
if (!is_x(x1)) { throw ["invalid argument to '"+name+"'", x1]; }
result = (x0 === x1);
return unwind();
};
return unwind();
};
}
var native_text_eq = make_eq('text=?', is_text);
var native_number_eq = make_eq('number=?', is_number);
var native_int32_eq = make_eq('int32=?', is_int32);
function make_lt(name, is_x) {
return function(x0) {
if (!is_x(x0)) { throw ["invalid argument to '"+name+"'", x0]; }
result = function(x1) {
if (!is_x(x1)) { throw ["invalid argument to '"+name+"'", x1]; }
result = (x0 < x1);
return unwind();
};
return unwind();
};
}
var native_text_lt = make_lt('text<?', is_text);
var native_number_lt = make_lt('number<?', is_number);
var native_int32_lt = make_lt('int32<?', is_int32);
function native_pair(h) {
result = function(t) { result = [h, t]; return unwind(); };
return unwind();
}
function native_pair_head(p) {
if (!is_pair(p)) { throw ['cannot take head of non-pair', p]; }
result = p[0];
return unwind();
}
function native_pair_tail(p) {
if (!is_pair(p)) { throw ['cannot take tail of non-pair', p]; }
result = p[1];
return unwind();
}
function native_text_concat(t0) {
if (!is_text(t0)) { throw ['cannot text-concat non-text', t0]; }
result = function(t1) {
if (!is_text(t1)) { throw ['cannot text-concat non-text', t1]; }
result = t0.concat(t1);
return unwind();
};
return unwind();
}
function native_text_to_list(txt) {
if (!is_text(t0)) { throw ['cannot text->list non-text', txt]; }
var i = txt.length - 1;
var answer = null;
for (; i >= 0; --i) { answer = [txt.charAt(i), answer]; }
result = answer;
return unwind();
}
// NOTE: codePointAt and String.fromCodePoint aren't supported in ES5
function native_text_to_codes(txt) {
if (!is_text(t0)) { throw ['cannot text->codes non-text', txt]; }
var i = txt.length - 1;
var answer = null;
for (; i >= 0; --i) { answer = [txt.charCodeAt(i), answer]; }
result = answer;
return unwind();
}
function native_text_from_codes(cs) {
var err = ['invalid text codes', cs];
cs = syntax_list(cs, err);
var i = cs.length - 1;
for (; i >= 0; --i) { if (!is_int32(cs[i])) { throw err; } }
result = String.fromCharCode.apply(this, cs);
return unwind();
}
function native_nadd(n0) {
if (!is_number(n0)) { throw ['cannot add non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot add non-number', n1]; }
result = n0 + n1; return unwind();
};
return unwind();
}
function native_nsub(n0) {
if (!is_number(n0)) { throw ['cannot subtract non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot subtract non-number', n1]; }
result = n0 - n1; return unwind();
};
return unwind();
}
function native_nmul(n0) {
if (!is_number(n0)) { throw ['cannot multiply non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot multiply non-number', n1]; }
result = n0 * n1; return unwind();
};
return unwind();
}
function native_ndiv(n0) {
if (!is_number(n0)) { throw ['cannot divide non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot divide non-number', n1]; }
result = n0 / n1; return unwind();
};
return unwind();
}
function native_nmod(n0) {
if (!is_number(n0)) { throw ['cannot modulo non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot modulo non-number', n1]; }
result = n0 % n1; return unwind();
};
return unwind();
}
// TODO: More text and/or numerical operations?
var applicatives = [
['procedure?', native_procedure_huh],
['pair?', native_pair_huh],
['nil?', native_nil_huh],
['boolean?', native_boolean_huh],
['text?', native_text_huh],
['number?', native_number_huh],
['int32?', native_int32_huh],
['text=?', native_text_eq],
['text<?', native_text_lt],
['number=?', native_number_eq],
['number<?', native_number_lt],
['int32=?', native_int32_eq],
['int32<?', native_int32_lt],
['pair', native_pair],
['head', native_pair_head],
['tail', native_pair_tail],
['text-concat', native_text_concat],
['text->list', native_text_to_list],
['text->codes', native_text_to_codes],
['text<-codes', native_text_from_codes],
['+', native_nadd],
['-', native_nsub],
['*', native_nmul],
['/', native_ndiv],
['%', native_nmod]];
var initial_senv =
array_to_list(
array_map(function(binding){return [binding[0],false];},
applicatives).concat(operatives));
var initial_env =
array_to_list(
array_map(function(binding){return binding[1];}, applicatives).concat(
array_map(function(binding){return binding[1];}, operatives)));
env = initial_env;
var k = denote(initial_senv, stx);
while (k !== null) { k = k(); }
return result;
}
| bootstrap/stage0.js | 'use strict';
// TODO: read(/annotate), write
function is_nil(datum) { return datum === null; }
function is_closure(datum) { return typeof datum === 'function'; }
function is_boolean(datum) { return typeof datum === 'boolean'; }
function is_text(datum) { return typeof datum === 'string'; }
function is_number(datum) { return typeof datum === 'number'; }
function is_int32(datum) {
return (typeof datum === 'number') && (datum === (datum | 0));
}
function is_pair(datum) {
return (typeof datum === 'object') && (datum !== null);
}
function env_extend(env, datum) { return [datum, env]; }
function env_ref(env, idx) {
for (; idx > 0; --idx) { env = env[1]; }
return env[0];
}
function env_find(env, found) {
var index = 0;
for (; env !== null; ++index) {
if (found(env[0])) { return index; }
env = env[1];
}
return undefined;
}
function env_find_name(env, name) {
var index = env_find(env, function(b){return (name === b[0]);});
if (index === undefined) { throw ['unbound variable', name]; }
return index;
}
function env_lookup(env, name) {
var index = env_find_name(env, name);
return env_ref(env, index)[1];
}
// TODO: Expect annotated syntax.
function syntax_list_of_length(len, xs, err) {
var result = [];
for (; len > 0; --len) {
if (!is_pair(xs)) { throw err; }
result.push(xs[0]);
xs = xs[1];
}
if (!is_nil(xs)) { throw err; }
return result;
}
function syntax_list(xs, err) {
var result = [];
while (is_pair(xs)) {
result.push(xs[0]);
xs = xs[1];
}
if (!is_nil(xs)) { throw err; }
return result;
}
function array_to_list(xs) {
var i = xs.length - 1;
var result = null;
for (; i >= 0; --i) { result = [xs[i], result]; }
return result;
}
function array_map(f, xs) {
var i = xs.length - 1;
var result = [];
result.length = xs.length;
for (; i >= 0; --i) { result[i] = f(xs[i]); }
return result;
}
function evaluate(stx) {
// TODO: It may be better to pass these registers around in an explicit
// context rather than capturing them in closures. It may also be more
// efficient to represent continuations as tagged data structures.
var result, env = null, ks = [function(){return null;}];
// TODO: Might as well inline this everywhere.
function unwind() { return ks.pop(); }
function denote_literal(datum) {
return function() { result = datum; return unwind(); };
}
function denote_var(senv, name) {
var index = env_find_name(senv, name);
if (env_ref(senv, index)[1] !== false) { throw ['invalid syntax', name]; }
return function() { result = env_ref(env, index); return unwind(); };
}
function build_app(senv, dp, as) {
if (is_nil(as)) { return dp; }
var da = denote(senv, as[0]);
var dapp = function(){
var kenv = env;
ks.push(function() {
var proc = result;
if (!is_closure(proc)) { throw ['cannot apply non-procedure', proc]; }
ks.push(function() { return proc(result); });
env = kenv;
return da;
});
return dp;
};
return build_app(senv, dapp, as[1]);
}
function denote_app(senv, stx) {
var err = ['invalid application', stx];
if (!is_pair(stx)) { throw err; }
syntax_list(stx[1], err);
return build_app(senv, denote(senv, stx[0]), stx[1]);
}
function denote(senv, stx) {
if (is_nil(stx) || is_boolean(stx) || is_number(stx)) {
return denote_literal(stx);
} else if (is_text(stx)) {
return denote_var(senv, stx);
} else if (is_pair(stx)) {
if (is_text(stx[0])) {
var special = env_lookup(senv, stx[0]);
if (typeof special === 'function') { return special(senv, stx[1]); }
}
return denote_app(senv, stx);
} else { throw ['unknown syntax', stx]; }
}
function build_lambda(senv, params, body) {
if (is_nil(params)) { return denote(senv, body); }
senv = env_extend(senv, [params[0], false]);
var dl = build_lambda(senv, params[1], body);
return function() {
var clo_env = env;
result = function(arg) {
env = env_extend(clo_env, arg);
return dl;
};
return unwind();
};
}
function denote_lambda(senv, stx) {
var err = ['invalid lambda', stx];
stx = syntax_list_of_length(2, stx, err);
var params = stx[0], body = stx[1];
if (!is_pair(params)) { throw err; }
array_map(function(p){ if (!is_text(p)) { throw err; } },
syntax_list(params, err));
return build_lambda(senv, params, body);
}
function denote_if(senv, stx) {
stx = syntax_list_of_length(3, stx, ['invalid if', stx]);
var dc = denote(senv, stx[0]);
var dt = denote(senv, stx[1]);
var df = denote(senv, stx[2]);
return function() {
var kenv = env;
ks.push(function(){
env = kenv;
if (result === false) { return df; } else { return dt; }
});
return dc;
};
}
function denote_quote(senv, stx) {
stx = syntax_list_of_length(1, stx, ['invalid quote', stx]);
return denote_literal(stx[0]);
}
function denote_qq(senv, stx) {
// TODO:
}
function denote_let(senv, stx) {
var err = ['invalid let', orig_stx];
stx = syntax_list_of_length(2, stx, err);
var bindings = array_map(function(binding) {
return syntax_list_of_length(2, binding, err);
}, syntax_list(stx[0], err));
var params = array_map(function(binding) {
if (!is_text(binding[0])) { throw err; } return binding[0];
}, bindings);
var args = array_map(function(binding) { return bindings[1]; }, bindings);
var body = stx[1];
var dp = build_lambda(senv, array_to_list(params), body);
return build_app(senv, dp, array_to_list(args));
}
var operatives = [
['let', denote_let],
['quasiquote', denote_qq],
['quote', denote_quote],
['if', denote_if],
['lambda', denote_lambda]];
function native_procedure_huh(datum) {
result = is_closure(datum); return unwind();
}
function native_boolean_huh(datum) {
result = is_boolean(datum); return unwind();
}
function native_pair_huh(datum) { result = is_pair(datum); return unwind(); }
function native_nil_huh(datum) { result = is_nil(datum); return unwind(); }
function native_text_huh(datum) { result = is_text(datum); return unwind(); }
function native_number_huh(datum) { result = is_number(datum); return unwind(); }
function native_int32_huh(datum) { result = is_int32(datum); return unwind(); }
function make_eq(name, is_x) {
return function(x0) {
if (!is_x(x0)) { throw ["invalid argument to '"+name+"'", x0]; }
result = function(x1) {
if (!is_x(x1)) { throw ["invalid argument to '"+name+"'", x1]; }
result = (x0 === x1);
return unwind();
};
return unwind();
};
}
var native_text_eq = make_eq('text=?', is_text);
var native_number_eq = make_eq('number=?', is_number);
var native_int32_eq = make_eq('int32=?', is_int32);
function make_lt(name, is_x) {
return function(x0) {
if (!is_x(x0)) { throw ["invalid argument to '"+name+"'", x0]; }
result = function(x1) {
if (!is_x(x1)) { throw ["invalid argument to '"+name+"'", x1]; }
result = (x0 < x1);
return unwind();
};
return unwind();
};
}
var native_text_lt = make_lt('text<?', is_text);
var native_number_lt = make_lt('number<?', is_number);
var native_int32_lt = make_lt('int32<?', is_int32);
function native_pair(h) {
result = function(t) { result = [h, t]; return unwind(); };
return unwind();
}
function native_pair_head(p) {
if (!is_pair(p)) { throw ['cannot take head of non-pair', p]; }
result = p[0];
return unwind();
}
function native_pair_tail(p) {
if (!is_pair(p)) { throw ['cannot take tail of non-pair', p]; }
result = p[1];
return unwind();
}
function native_text_concat(t0) {
if (!is_text(t0)) { throw ['cannot text-concat non-text', t0]; }
result = function(t1) {
if (!is_text(t1)) { throw ['cannot text-concat non-text', t1]; }
result = t0.concat(t1);
return unwind();
};
return unwind();
}
function native_text_to_list(txt) {
if (!is_text(t0)) { throw ['cannot text->list non-text', txt]; }
var i = txt.length - 1;
var answer = null;
for (; i >= 0; --i) { answer = [txt.charAt(i), answer]; }
result = answer;
return unwind();
}
// NOTE: codePointAt and String.fromCodePoint aren't supported in ES5
function native_text_to_codes(txt) {
if (!is_text(t0)) { throw ['cannot text->codes non-text', txt]; }
var i = txt.length - 1;
var answer = null;
for (; i >= 0; --i) { answer = [txt.charCodeAt(i), answer]; }
result = answer;
return unwind();
}
function native_text_from_codes(cs) {
var err = ['invalid text codes', cs];
cs = syntax_list(cs, err);
var i = cs.length - 1;
for (; i >= 0; --i) { if (!is_int32(cs[i])) { throw err; } }
result = String.fromCharCode.apply(this, cs);
return unwind();
}
function native_nadd(n0) {
if (!is_number(n0)) { throw ['cannot add non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot add non-number', n1]; }
result = n0 + n1; return unwind();
};
return unwind();
}
function native_nsub(n0) {
if (!is_number(n0)) { throw ['cannot subtract non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot subtract non-number', n1]; }
result = n0 - n1; return unwind();
};
return unwind();
}
function native_nmul(n0) {
if (!is_number(n0)) { throw ['cannot multiply non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot multiply non-number', n1]; }
result = n0 * n1; return unwind();
};
return unwind();
}
function native_ndiv(n0) {
if (!is_number(n0)) { throw ['cannot divide non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot divide non-number', n1]; }
result = n0 / n1; return unwind();
};
return unwind();
}
function native_nmod(n0) {
if (!is_number(n0)) { throw ['cannot modulo non-number', n0]; }
result = function(n1) {
if (!is_number(n1)) { throw ['cannot modulo non-number', n1]; }
result = n0 % n1; return unwind();
};
return unwind();
}
// TODO: More text and/or numerical operations?
var applicatives = [
['procedure?', native_procedure_huh],
['pair?', native_pair_huh],
['nil?', native_nil_huh],
['boolean?', native_boolean_huh],
['text?', native_text_huh],
['number?', native_number_huh],
['int32?', native_int32_huh],
['text=?', native_text_eq],
['text<?', native_text_lt],
['number=?', native_number_eq],
['number<?', native_number_lt],
['int32=?', native_int32_eq],
['int32<?', native_int32_lt],
['pair', native_pair],
['head', native_pair_head],
['tail', native_pair_tail],
['text-concat', native_text_concat],
['text->list', native_text_to_list],
['text->codes', native_text_to_codes],
['text<-codes', native_text_from_codes],
['+', native_nadd],
['-', native_nsub],
['*', native_nmul],
['/', native_ndiv],
['%', native_nmod]];
var initial_senv =
array_to_list(
array_map(function(binding){return [binding[0],false];},
applicatives).concat(operatives));
var initial_env =
array_to_list(
array_map(function(binding){return binding[1];}, applicatives).concat(
array_map(function(binding){return binding[1];}, operatives)));
env = initial_env;
var k = denote(initial_senv, stx);
while (k !== null) { k = k(); }
return result;
}
| Fix denote_let
| bootstrap/stage0.js | Fix denote_let | <ide><path>ootstrap/stage0.js
<ide> // TODO:
<ide> }
<ide> function denote_let(senv, stx) {
<del> var err = ['invalid let', orig_stx];
<add> var err = ['invalid let', stx];
<ide> stx = syntax_list_of_length(2, stx, err);
<del> var bindings = array_map(function(binding) {
<del> return syntax_list_of_length(2, binding, err);
<add> var bindings = array_map(function(b) {
<add> return syntax_list_of_length(2, b, err);
<ide> }, syntax_list(stx[0], err));
<del> var params = array_map(function(binding) {
<del> if (!is_text(binding[0])) { throw err; } return binding[0];
<add> var params = array_map(function(b) {
<add> if (!is_text(b[0])) { throw err; } return b[0];
<ide> }, bindings);
<del> var args = array_map(function(binding) { return bindings[1]; }, bindings);
<add> var args = array_map(function(b) { return b[1]; }, bindings);
<ide> var body = stx[1];
<ide> var dp = build_lambda(senv, array_to_list(params), body);
<ide> return build_app(senv, dp, array_to_list(args)); |
|
Java | mit | error: pathspec 'src/data-stream-as-disjoint-intervals/main.java' did not match any file(s) known to git
| 3d88522234317d3f792ccbf160ec120b90320298 | 1 | alenny/leetcode,alenny/leetcode | import java.util.*;
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* List<Interval> param_2 = obj.getIntervals();
*/
public class Program {
public static void main(String[] args) {
SummaryRanges sum = new SummaryRanges();
sum.addNum(1);
List<Interval> ret = sum.getIntervals();
System.out.println("hello");
}
}
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
class Interval {
public int start;
public int end;
public Interval() {
start = 0;
end = 0;
}
public Interval(int s, int e) {
start = s;
end = e;
}
}
class SummaryRanges {
private List<Interval> ranges;
/** Initialize your data structure here. */
public SummaryRanges() {
ranges = new ArrayList<Interval>();
}
public void addNum(int val) {
if (ranges.size() == 0) {
ranges.add(new Interval(val, val));
}
int i = 0;
while (i < ranges.size()) {
Interval interval = ranges.get(i);
if (val < interval.start - 1) {
ranges.add(i, new Interval(val, val));
return;
}
if (val == interval.start - 1) {
interval.start = val;
return;
}
if (val >= interval.start && val <= interval.end) {
return;
}
if (val == interval.end + 1) {
if (i == ranges.size() - 1 || val < ranges.get(i + 1).start - 1) {
interval.end = val;
} else {
interval.end = ranges.get(i + 1).end;
ranges.remove(i + 1);
}
return;
}
// then, val > ranges[i].end + 1
if (i == ranges.size() - 1) {
ranges.add(new Interval(val, val));
return;
}
++i;
}
}
public List<Interval> getIntervals() {
return ranges;
}
}
| src/data-stream-as-disjoint-intervals/main.java | Commit solution for data stream as disjoint intervals
| src/data-stream-as-disjoint-intervals/main.java | Commit solution for data stream as disjoint intervals | <ide><path>rc/data-stream-as-disjoint-intervals/main.java
<add>import java.util.*;
<add>
<add>/**
<add> * Your SummaryRanges object will be instantiated and called as such:
<add> * SummaryRanges obj = new SummaryRanges();
<add> * obj.addNum(val);
<add> * List<Interval> param_2 = obj.getIntervals();
<add> */
<add>public class Program {
<add> public static void main(String[] args) {
<add> SummaryRanges sum = new SummaryRanges();
<add> sum.addNum(1);
<add> List<Interval> ret = sum.getIntervals();
<add> System.out.println("hello");
<add> }
<add>}
<add>
<add>/**
<add> * Definition for an interval.
<add> * public class Interval {
<add> * int start;
<add> * int end;
<add> * Interval() { start = 0; end = 0; }
<add> * Interval(int s, int e) { start = s; end = e; }
<add> * }
<add> */
<add>class Interval {
<add> public int start;
<add> public int end;
<add>
<add> public Interval() {
<add> start = 0;
<add> end = 0;
<add> }
<add>
<add> public Interval(int s, int e) {
<add> start = s;
<add> end = e;
<add> }
<add>}
<add>
<add>class SummaryRanges {
<add> private List<Interval> ranges;
<add>
<add> /** Initialize your data structure here. */
<add> public SummaryRanges() {
<add> ranges = new ArrayList<Interval>();
<add> }
<add>
<add> public void addNum(int val) {
<add> if (ranges.size() == 0) {
<add> ranges.add(new Interval(val, val));
<add> }
<add> int i = 0;
<add> while (i < ranges.size()) {
<add> Interval interval = ranges.get(i);
<add> if (val < interval.start - 1) {
<add> ranges.add(i, new Interval(val, val));
<add> return;
<add> }
<add> if (val == interval.start - 1) {
<add> interval.start = val;
<add> return;
<add> }
<add> if (val >= interval.start && val <= interval.end) {
<add> return;
<add> }
<add> if (val == interval.end + 1) {
<add> if (i == ranges.size() - 1 || val < ranges.get(i + 1).start - 1) {
<add> interval.end = val;
<add> } else {
<add> interval.end = ranges.get(i + 1).end;
<add> ranges.remove(i + 1);
<add> }
<add> return;
<add> }
<add> // then, val > ranges[i].end + 1
<add> if (i == ranges.size() - 1) {
<add> ranges.add(new Interval(val, val));
<add> return;
<add> }
<add> ++i;
<add> }
<add> }
<add>
<add> public List<Interval> getIntervals() {
<add> return ranges;
<add> }
<add>} |
|
JavaScript | mit | 880d6922a05ac1ba7f30b7a23d26f815f6f4b138 | 0 | eleloya/whatdabug,Bluehats/whatdabug,Bluehats/whatdabug,eleloya/whatdabug,Bluehats/whatdabug,eleloya/whatdabug,eleloya/whatdabug,Bluehats/whatdabug,eleloya/whatdabug | var streak = 0;
var time = 10;
var loop = "";
var currentBug;
var rounds;
window.onload = function(){
if(window.location.search.match(/restart=true/) !== null){
remove_instructions();
init_game();
}
};
function init_game(){
streak = 0;
time = 10;
loop = window.setInterval(gameloop, 1000);
next_round();
}
function restart(){
window.location.search = '&restart=true';
}
function lineClickHandlers(){
var rows = document.getElementsByTagName("tr");
for(var i = 0; i < rows.length; i++)
{
(function(i) {
var thisRow = rows[i];
thisRow.setAttribute("ontouched", "this.onclick=fix");
thisRow.addEventListener('click', function(){
checkAnswer(i+1);
});
})(i);
}
}
function remove_instructions(){
var instructions = document.getElementById('instructions');
instructions.setAttribute("style", "display: none");
}
function fix(){
var el = this;
var par = el.parentNode;
var next = el.nextSibling;
par.removeChild(el);
setTimeout(function() {par.insertBefore(el, next);}, 0);
}
function checkAnswer(rowNumber){
bugLines = currentBug.get('bug_lines').split(',');
var rows = document.getElementsByTagName("tr");
if (bugLines.indexOf(rowNumber + '') >= 0 ) {
next_round();
time += 10;
streak += 1;
updateDOMStreak();
}else{
rows[rowNumber-1].setAttribute("id", "wrong");
time -= 5;
}
}
function gameloop(){
time--;
updateDOMTime(); // We redraw the time
updateDOMStreak(); // We redraw the streak
if(time<=0){
looseGame();
}
var rows = document.getElementById("wrong");
rows.removeAttribute("id");
}
function updateDOMTime(){
var timediv = document.getElementById("whatdatimep");
timediv.innerHTML = "Time: " + time;
}
function updateDOMStreak(){
var streakdiv = document.getElementById("whatdastreakp");
streakdiv.innerHTML = "Score: " + streak;
}
function looseGame(){
window.clearInterval(loop);
time = 0;
updateDOMTime();
drawLoose();
}
function drawLoose(){
var overlay = document.getElementById("gameover");
var message = document.getElementById("goexplanation");
overlay.setAttribute("style", "display: block");
message.innerHTML = "Lines " + currentBug.get("bug_lines") + ": " + currentBug.get("explanation");
window.setTimeout(function ()
{
document.getElementById('scorername').focus();
}, 0);
}
function next_round(){
var random = Math.floor(Math.random()*rounds.length);
currentBug = rounds[random];
if (rounds.length === 0){
//alert('You have finished all bugs for this language, please contribute more at github.com/bluehats/whatdabug');
looseGame();
}
document.getElementsByTagName('tbody')[0].innerHTML = currentBug.get("code");
rounds.splice(random, 1);
lineClickHandlers();
}
function send_score(){
var HighScore = Parse.Object.extend("HighScore");
var newScore = new HighScore();
newScore.set("username", document.getElementById('scorername').value);
newScore.set("score", streak);
newScore.save(null, {
success: function(newScore)
{
console.log("saved!!!");
restart();
},
error: function(newScore, error)
{
console.log("error saving :(");
}
});
}
| dabug.js | var streak = 0;
var time = 10;
var loop = "";
var currentBug;
var rounds;
window.onload = function(){
if(window.location.search.match(/restart=true/) !== null){
remove_instructions();
init_game();
}
};
function init_game(){
streak = 0;
time = 10;
loop = window.setInterval(gameloop, 1000);
next_round();
}
function restart(){
window.location.search += '&restart=true';
}
function lineClickHandlers(){
var rows = document.getElementsByTagName("tr");
for(var i = 0; i < rows.length; i++)
{
(function(i) {
var thisRow = rows[i];
thisRow.setAttribute("ontouched", "this.onclick=fix");
thisRow.addEventListener('click', function(){
checkAnswer(i+1);
});
})(i);
}
}
function remove_instructions(){
var instructions = document.getElementById('instructions');
instructions.setAttribute("style", "display: none");
}
function fix(){
var el = this;
var par = el.parentNode;
var next = el.nextSibling;
par.removeChild(el);
setTimeout(function() {par.insertBefore(el, next);}, 0);
}
function checkAnswer(rowNumber){
bugLines = currentBug.get('bug_lines').split(',');
var rows = document.getElementsByTagName("tr");
if (bugLines.indexOf(rowNumber + '') >= 0 ) {
next_round();
time += 10;
streak += 1;
updateDOMStreak();
}else{
rows[rowNumber-1].setAttribute("id", "wrong");
time -= 5;
}
}
function gameloop(){
time--;
updateDOMTime(); // We redraw the time
updateDOMStreak(); // We redraw the streak
if(time<=0){
looseGame();
}
var rows = document.getElementById("wrong");
rows.removeAttribute("id");
}
function updateDOMTime(){
var timediv = document.getElementById("whatdatimep");
timediv.innerHTML = "Time: " + time;
}
function updateDOMStreak(){
var streakdiv = document.getElementById("whatdastreakp");
streakdiv.innerHTML = "Score: " + streak;
}
function looseGame(){
window.clearInterval(loop);
time = 0;
updateDOMTime();
drawLoose();
}
function drawLoose(){
var overlay = document.getElementById("gameover");
var message = document.getElementById("goexplanation");
overlay.setAttribute("style", "display: block");
message.innerHTML = "Lines " + currentBug.get("bug_lines") + ": " + currentBug.get("explanation");
window.setTimeout(function ()
{
document.getElementById('scorername').focus();
}, 0);
}
function next_round(){
var random = Math.floor(Math.random()*rounds.length);
currentBug = rounds[random];
if (rounds.length === 0){
//alert('You have finished all bugs for this language, please contribute more at github.com/bluehats/whatdabug');
looseGame();
}
document.getElementsByTagName('tbody')[0].innerHTML = currentBug.get("code");
rounds.splice(random, 1);
lineClickHandlers();
}
function send_score(){
var HighScore = Parse.Object.extend("HighScore");
var newScore = new HighScore();
newScore.set("username", document.getElementById('scorername').value);
newScore.set("score", streak);
newScore.save(null, {
success: function(newScore)
{
console.log("saved!!!");
restart();
},
error: function(newScore, error)
{
console.log("error saving :(");
}
});
}
| only add once restart=true
| dabug.js | only add once restart=true | <ide><path>abug.js
<ide> }
<ide>
<ide> function restart(){
<del> window.location.search += '&restart=true';
<add> window.location.search = '&restart=true';
<ide> }
<ide>
<ide> function lineClickHandlers(){ |
|
Java | apache-2.0 | a1ece6fa4083bd9b7f4586bf1efc56ad0abf699d | 0 | hujiaweibujidao/textfairy,sachinxagrawal/testocr,sachinxagrawal/testocr,hujiaweibujidao/textfairy,renard314/textfairy,renard314/textfairy,sachinxagrawal/testocr,dankito/TextFairyPlugin,renard314/textfairy,renard314/textfairy,dankito/TextFairyPlugin,renard314/textfairy,dankito/TextFairyPlugin,hujiaweibujidao/textfairy,hujiaweibujidao/textfairy,renard314/textfairy,renard314/textfairy,renard314/textfairy,dankito/TextFairyPlugin,dankito/TextFairyPlugin,hujiaweibujidao/textfairy,sachinxagrawal/testocr,sachinxagrawal/testocr | /*
* Copyright (C) 2012, 2013, 2014, 2015 Renard Wellnitz.
*
* 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.renard.ocr;
import android.app.AlertDialog;
import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.googlecode.leptonica.android.Pix;
import com.googlecode.leptonica.android.Pixa;
import com.googlecode.leptonica.android.WriteFile;
import com.googlecode.tesseract.android.OCR;
import com.renard.documentview.DocumentActivity;
import com.renard.ocr.DocumentContentProvider.Columns;
import com.renard.ocr.LayoutQuestionDialog.LayoutChoseListener;
import com.renard.ocr.LayoutQuestionDialog.LayoutKind;
import com.renard.ocr.cropimage.MonitoredActivity;
import com.renard.util.Screen;
import com.renard.util.Util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
/**
* this activity is shown during the ocr process
*
* @author renard
*/
public class OCRActivity extends MonitoredActivity {
@SuppressWarnings("unused")
private static final String TAG = OCRActivity.class.getSimpleName();
public static final String EXTRA_PARENT_DOCUMENT_ID = "parent_id";
private static final String OCR_LANGUAGE = "ocr_language";
public static final String EXTRA_USE_ACCESSIBILITY_MODE = "ACCESSIBILTY_MODE";
private Button mButtonStartOCR;
private OCRImageView mImageView;
private int mOriginalHeight = 0;
private int mOriginalWidth = 0;
private Pix mFinalPix;
private String mOcrLanguage; // is set by dialog in
private int mAccuracy;
// askUserAboutDocumentLayout
private OCR mOCR;
// receives messages from background task
private Messenger mMessageReceiver = new Messenger(new ProgressActivityHandler());
// if >=0 its the id of the parentdocument to which the current page shall be added
private int mParentId = -1;
/**
* receives progress status messages from the background ocr task and
* displays them in the current activity
*
* @author renard
*/
private class ProgressActivityHandler extends Handler {
private String hocrString;
private String utf8String;
private int layoutPix;
private int mPreviewWith;
private int mPreviewHeight;
public void handleMessage(Message msg) {
switch (msg.what) {
case OCR.MESSAGE_EXPLANATION_TEXT: {
getSupportActionBar().setTitle(msg.arg1);
break;
}
case OCR.MESSAGE_TESSERACT_PROGRESS: {
int percent = msg.arg1;
Bundle data = msg.getData();
mImageView.setProgress(percent,
(RectF) data.getParcelable(OCR.EXTRA_WORD_BOX),
(RectF) data.getParcelable(OCR.EXTRA_OCR_BOX));
break;
}
case OCR.MESSAGE_PREVIEW_IMAGE: {
mImageView.setImageBitmapResetBase((Bitmap) msg.obj, true, 0);
break;
}
case OCR.MESSAGE_FINAL_IMAGE: {
int nativePix = msg.arg1;
if (nativePix != 0) {
mFinalPix = new Pix(nativePix);
}
break;
}
case OCR.MESSAGE_LAYOUT_PIX: {
layoutPix = msg.arg1;
if (layoutPix != 0) {
Pix pix = new Pix(layoutPix);
final Bitmap preview = WriteFile.writeBitmap(pix);
mPreviewHeight = pix.getHeight();
mPreviewWith = pix.getWidth();
mImageView.setImageBitmapResetBase(preview, true, 0);
pix.recycle();
}
break;
}
case OCR.MESSAGE_LAYOUT_ELEMENTS: {
int nativePixaText = msg.arg1;
int nativePixaImages = msg.arg2;
final Pixa texts = new Pixa(nativePixaText, 0, 0);
final Pixa images = new Pixa(nativePixaImages, 0, 0);
ArrayList<Rect> boxes = images.getBoxRects();
ArrayList<RectF> scaledBoxes = new ArrayList<RectF>(boxes.size());
float xScale = (1.0f * mPreviewWith) / mOriginalWidth;
float yScale = (1.0f * mPreviewHeight) / mOriginalHeight;
// scale the to the preview image space
for (Rect r : boxes) {
scaledBoxes.add(new RectF(r.left * xScale, r.top * yScale,
r.right * xScale, r.bottom * yScale));
}
mImageView.setImageRects(scaledBoxes);
boxes = texts.getBoxRects();
scaledBoxes = new ArrayList<RectF>(boxes.size());
for (Rect r : boxes) {
scaledBoxes.add(new RectF(r.left * xScale, r.top * yScale,
r.right * xScale, r.bottom * yScale));
}
mImageView.setTextRects(scaledBoxes);
mButtonStartOCR.setVisibility(View.VISIBLE);
mButtonStartOCR.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int[] selectedTexts = mImageView
.getSelectedTextIndexes();
int[] selectedImages = mImageView
.getSelectedImageIndexes();
if (selectedTexts.length > 0
|| selectedImages.length > 0) {
mImageView.clearAllProgressInfo();
mOCR.startOCRForComplexLayout(OCRActivity.this,
determineOcrLanguage(mOcrLanguage), texts,
images, selectedTexts, selectedImages);
mButtonStartOCR.setVisibility(View.GONE);
} else {
Toast.makeText(getApplicationContext(),
R.string.please_tap_on_column,
Toast.LENGTH_LONG).show();
}
}
});
getSupportActionBar().setTitle(R.string.progress_choose_columns);
break;
}
case OCR.MESSAGE_HOCR_TEXT: {
this.hocrString = (String) msg.obj;
mAccuracy = msg.arg1;
break;
}
case OCR.MESSAGE_UTF8_TEXT: {
this.utf8String = (String) msg.obj;
break;
}
case OCR.MESSAGE_END: {
saveDocument(mFinalPix, hocrString, utf8String, mAccuracy);
break;
}
case OCR.MESSAGE_ERROR: {
Toast.makeText(getApplicationContext(), getText(msg.arg1), Toast.LENGTH_LONG).show();
break;
}
}
}
}
private void saveDocument(final Pix pix, final String hocrString, final String utf8String, final int accuracy) {
Util.startBackgroundJob(OCRActivity.this, "",
getText(R.string.saving_document).toString(), new Runnable() {
@Override
public void run() {
File imageFile = null;
Uri documentUri = null;
try {
imageFile = saveImage(pix);
} catch (IOException ignore) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(
getApplicationContext(),
getText(R.string.error_create_file),
Toast.LENGTH_LONG).show();
}
});
}
try {
documentUri = saveDocumentToDB(imageFile, hocrString, utf8String);
Util.createThumbnail(OCRActivity.this, imageFile, Integer.valueOf(documentUri.getLastPathSegment()));
} catch (RemoteException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(
getApplicationContext(),
getText(R.string.error_create_file),
Toast.LENGTH_LONG).show();
}
});
} finally {
if (pix != null) {
pix.recycle();
}
if (documentUri != null) {
Intent i;
if(utf8String==null || utf8String.isEmpty()){
i = new Intent(OCRActivity.this, DocumentGridActivity.class);
} else {
i = new Intent(OCRActivity.this, DocumentActivity.class);
i.putExtra(DocumentActivity.EXTRA_ACCURACY, accuracy);
i.setData(documentUri);
}
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
Screen.unlockOrientation(OCRActivity.this);
}
}
}
}, new Handler());
}
private File saveImage(Pix p) throws IOException {
CharSequence id = DateFormat.format("ssmmhhddMMyy", new Date(System.currentTimeMillis()));
return Util.savePixToSD(p, id.toString());
}
private Uri saveDocumentToDB(File imageFile, String hocr, String plainText)
throws RemoteException {
ContentProviderClient client = null;
try {
ContentValues v = new ContentValues();
if (imageFile != null) {
v.put(com.renard.ocr.DocumentContentProvider.Columns.PHOTO_PATH,
imageFile.getPath());
}
if (hocr != null) {
v.put(Columns.HOCR_TEXT, hocr);
}
if (plainText != null) {
v.put(Columns.OCR_TEXT, plainText);
}
v.put(Columns.OCR_LANG, mOcrLanguage);
if (mParentId > -1) {
v.put(Columns.PARENT_ID, mParentId);
}
client = getContentResolver().acquireContentProviderClient(
DocumentContentProvider.CONTENT_URI);
return client.insert(DocumentContentProvider.CONTENT_URI, v);
} finally {
if (client != null) {
client.release();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mOCR = new OCR(this, mMessageReceiver);
Screen.lockOrientation(this);
setContentView(R.layout.ocr_visualize);
mImageView = (OCRImageView) findViewById(R.id.progress_image);
mParentId = getIntent().getIntExtra(EXTRA_PARENT_DOCUMENT_ID, -1);
long nativePix = getIntent().getExtras().getLong(DocumentGridActivity.EXTRA_NATIVE_PIX);
Pix pixOrg = new Pix(nativePix);
mOriginalHeight = pixOrg.getHeight();
mOriginalWidth = pixOrg.getWidth();
final boolean accessibility = getIntent().getBooleanExtra(EXTRA_USE_ACCESSIBILITY_MODE, false);
askUserAboutDocumentLayout(pixOrg, accessibility);
mButtonStartOCR = (Button) findViewById(R.id.column_pick_completed);
initAppIcon(this, -1);
}
private void askUserAboutDocumentLayout(final Pix pixOrg, final boolean accessibility) {
AlertDialog alertDialog = LayoutQuestionDialog.createDialog(this,
new LayoutChoseListener() {
@Override
public void onLayoutChosen(final LayoutKind layoutKind,
final String ocrLanguage) {
if (layoutKind == LayoutKind.DO_NOTHING) {
saveDocument(pixOrg, null, null, 0);
} else {
mOcrLanguage = ocrLanguage;
getSupportActionBar().show();
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle(R.string.progress_start);
if (layoutKind == LayoutKind.SIMPLE) {
mOCR.startOCRForSimpleLayout(OCRActivity.this, determineOcrLanguage(ocrLanguage), pixOrg);
} else if (layoutKind == LayoutKind.COMPLEX) {
mAccuracy = 0;
mOCR.startLayoutAnalysis(pixOrg);
}
}
}
}, accessibility);
alertDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
alertDialog.show();
}
private String determineOcrLanguage(String ocrLanguage) {
final String english = "eng";
if (!ocrLanguage.equals(english) && addEnglishData(ocrLanguage)) {
return ocrLanguage + "+" + english;
} else {
return ocrLanguage;
}
}
// when combining languages that have multi byte characters with english
// training data the ocr text gets corrupted
// but adding english will improve overall accuracy for the other languages
private static boolean addEnglishData(String mLanguage) {
if (mLanguage.startsWith("chi") || mLanguage.equalsIgnoreCase("tha")
|| mLanguage.equalsIgnoreCase("kor")
|| mLanguage.equalsIgnoreCase("hin")
|| mLanguage.equalsIgnoreCase("heb")
|| mLanguage.equalsIgnoreCase("jap")
|| mLanguage.equalsIgnoreCase("ell")
|| mLanguage.equalsIgnoreCase("bel")
|| mLanguage.equalsIgnoreCase("ara")
|| mLanguage.equalsIgnoreCase("grc")
|| mLanguage.equalsIgnoreCase("rus")
|| mLanguage.equalsIgnoreCase("vie")) {
return false;
}
return true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mOcrLanguage != null) {
outState.putString(OCR_LANGUAGE, mOcrLanguage);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (mOcrLanguage == null) {
mOcrLanguage = savedInstanceState.getString(OCR_LANGUAGE);
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFinalPix != null) {
mFinalPix.recycle();
mFinalPix = null;
}
BitmapDrawable bd = (BitmapDrawable) mImageView.getDrawable();
if (bd != null) {
bd.getBitmap().recycle();
}
}
}
| app/src/main/java/com/renard/ocr/OCRActivity.java | /*
* Copyright (C) 2012, 2013, 2014, 2015 Renard Wellnitz.
*
* 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.renard.ocr;
import android.app.AlertDialog;
import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.googlecode.leptonica.android.Pix;
import com.googlecode.leptonica.android.Pixa;
import com.googlecode.leptonica.android.WriteFile;
import com.googlecode.tesseract.android.OCR;
import com.renard.documentview.DocumentActivity;
import com.renard.ocr.DocumentContentProvider.Columns;
import com.renard.ocr.LayoutQuestionDialog.LayoutChoseListener;
import com.renard.ocr.LayoutQuestionDialog.LayoutKind;
import com.renard.ocr.cropimage.MonitoredActivity;
import com.renard.util.Screen;
import com.renard.util.Util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
/**
* this activity is shown during the ocr process
*
* @author renard
*/
public class OCRActivity extends MonitoredActivity {
@SuppressWarnings("unused")
private static final String TAG = OCRActivity.class.getSimpleName();
public static final String EXTRA_PARENT_DOCUMENT_ID = "parent_id";
private static final String OCR_LANGUAGE = "ocr_language";
public static final String EXTRA_USE_ACCESSIBILITY_MODE = "ACCESSIBILTY_MODE";
private Button mButtonStartOCR;
private OCRImageView mImageView;
private int mOriginalHeight = 0;
private int mOriginalWidth = 0;
private Pix mFinalPix;
private String mOcrLanguage; // is set by dialog in
private int mAccuracy;
// askUserAboutDocumentLayout
private OCR mOCR;
// receives messages from background task
private Messenger mMessageReceiver = new Messenger(new ProgressActivityHandler());
// if >=0 its the id of the parentdocument to which the current page shall be added
private int mParentId = -1;
/**
* receives progress status messages from the background ocr task and
* displays them in the current activity
*
* @author renard
*/
private class ProgressActivityHandler extends Handler {
private String hocrString;
private String utf8String;
private int layoutPix;
private int mPreviewWith;
private int mPreviewHeight;
public void handleMessage(Message msg) {
switch (msg.what) {
case OCR.MESSAGE_EXPLANATION_TEXT: {
getSupportActionBar().setTitle(msg.arg1);
break;
}
case OCR.MESSAGE_TESSERACT_PROGRESS: {
int percent = msg.arg1;
Bundle data = msg.getData();
mImageView.setProgress(percent,
(RectF) data.getParcelable(OCR.EXTRA_WORD_BOX),
(RectF) data.getParcelable(OCR.EXTRA_OCR_BOX));
break;
}
case OCR.MESSAGE_PREVIEW_IMAGE: {
mImageView.setImageBitmapResetBase((Bitmap) msg.obj, true, 0);
break;
}
case OCR.MESSAGE_FINAL_IMAGE: {
int nativePix = msg.arg1;
if (nativePix != 0) {
mFinalPix = new Pix(nativePix);
}
break;
}
case OCR.MESSAGE_LAYOUT_PIX: {
layoutPix = msg.arg1;
if (layoutPix != 0) {
Pix pix = new Pix(layoutPix);
final Bitmap preview = WriteFile.writeBitmap(pix);
mPreviewHeight = pix.getHeight();
mPreviewWith = pix.getWidth();
mImageView.setImageBitmapResetBase(preview, true, 0);
pix.recycle();
}
break;
}
case OCR.MESSAGE_LAYOUT_ELEMENTS: {
int nativePixaText = msg.arg1;
int nativePixaImages = msg.arg2;
final Pixa texts = new Pixa(nativePixaText, 0, 0);
final Pixa images = new Pixa(nativePixaImages, 0, 0);
ArrayList<Rect> boxes = images.getBoxRects();
ArrayList<RectF> scaledBoxes = new ArrayList<RectF>(boxes.size());
float xScale = (1.0f * mPreviewWith) / mOriginalWidth;
float yScale = (1.0f * mPreviewHeight) / mOriginalHeight;
// scale the to the preview image space
for (Rect r : boxes) {
scaledBoxes.add(new RectF(r.left * xScale, r.top * yScale,
r.right * xScale, r.bottom * yScale));
}
mImageView.setImageRects(scaledBoxes);
boxes = texts.getBoxRects();
scaledBoxes = new ArrayList<RectF>(boxes.size());
for (Rect r : boxes) {
scaledBoxes.add(new RectF(r.left * xScale, r.top * yScale,
r.right * xScale, r.bottom * yScale));
}
mImageView.setTextRects(scaledBoxes);
mButtonStartOCR.setVisibility(View.VISIBLE);
mButtonStartOCR.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int[] selectedTexts = mImageView
.getSelectedTextIndexes();
int[] selectedImages = mImageView
.getSelectedImageIndexes();
if (selectedTexts.length > 0
|| selectedImages.length > 0) {
mImageView.clearAllProgressInfo();
mOCR.startOCRForComplexLayout(OCRActivity.this,
determineOcrLanguage(mOcrLanguage), texts,
images, selectedTexts, selectedImages);
mButtonStartOCR.setVisibility(View.GONE);
} else {
Toast.makeText(getApplicationContext(),
R.string.please_tap_on_column,
Toast.LENGTH_LONG).show();
}
}
});
getSupportActionBar().setTitle(R.string.progress_choose_columns);
break;
}
case OCR.MESSAGE_HOCR_TEXT: {
this.hocrString = (String) msg.obj;
mAccuracy = msg.arg1;
break;
}
case OCR.MESSAGE_UTF8_TEXT: {
this.utf8String = (String) msg.obj;
break;
}
case OCR.MESSAGE_END: {
saveDocument(mFinalPix, hocrString, utf8String, mAccuracy);
break;
}
case OCR.MESSAGE_ERROR: {
Toast.makeText(getApplicationContext(), getText(msg.arg1), Toast.LENGTH_LONG).show();
break;
}
}
}
}
private void saveDocument(final Pix pix, final String hocrString, final String utf8String, final int accuracy) {
Util.startBackgroundJob(OCRActivity.this, "",
getText(R.string.saving_document).toString(), new Runnable() {
@Override
public void run() {
File imageFile = null;
Uri documentUri = null;
try {
imageFile = saveImage(pix);
} catch (IOException ignore) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(
getApplicationContext(),
getText(R.string.error_create_file),
Toast.LENGTH_LONG).show();
}
});
}
try {
documentUri = saveDocumentToDB(imageFile, hocrString, utf8String);
Util.createThumbnail(OCRActivity.this, imageFile, Integer.valueOf(documentUri.getLastPathSegment()));
} catch (RemoteException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(
getApplicationContext(),
getText(R.string.error_create_file),
Toast.LENGTH_LONG).show();
}
});
} finally {
if (pix != null) {
pix.recycle();
}
if (documentUri != null) {
Intent i;
if(utf8String==null || utf8String.isEmpty()){
i = new Intent(OCRActivity.this, DocumentGridActivity.class);
} else {
i = new Intent(OCRActivity.this, DocumentActivity.class);
i.putExtra(DocumentActivity.EXTRA_ACCURACY, accuracy);
i.setData(documentUri);
}
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
Screen.unlockOrientation(OCRActivity.this);
}
}
}
}, new Handler());
}
private File saveImage(Pix p) throws IOException {
CharSequence id = DateFormat.format("ssmmhhddMMyy", new Date(System.currentTimeMillis()));
return Util.savePixToSD(p, id.toString());
}
private Uri saveDocumentToDB(File imageFile, String hocr, String plainText)
throws RemoteException {
ContentProviderClient client = null;
try {
ContentValues v = new ContentValues();
if (imageFile != null) {
v.put(com.renard.ocr.DocumentContentProvider.Columns.PHOTO_PATH,
imageFile.getPath());
}
if (hocr != null) {
v.put(Columns.HOCR_TEXT, hocr);
}
if (plainText != null) {
v.put(Columns.OCR_TEXT, plainText);
}
v.put(Columns.OCR_LANG, mOcrLanguage);
if (mParentId > -1) {
v.put(Columns.PARENT_ID, mParentId);
}
client = getContentResolver().acquireContentProviderClient(
DocumentContentProvider.CONTENT_URI);
return client.insert(DocumentContentProvider.CONTENT_URI, v);
} finally {
if (client != null) {
client.release();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mOCR = new OCR(this, mMessageReceiver);
Screen.lockOrientation(this);
setContentView(R.layout.ocr_visualize);
mImageView = (OCRImageView) findViewById(R.id.progress_image);
mParentId = getIntent().getIntExtra(EXTRA_PARENT_DOCUMENT_ID, -1);
long nativePix = getIntent().getExtras().getLong(DocumentGridActivity.EXTRA_NATIVE_PIX);
Pix pixOrg = new Pix(nativePix);
mOriginalHeight = pixOrg.getHeight();
mOriginalWidth = pixOrg.getWidth();
final boolean accessibility = getIntent().getBooleanExtra(EXTRA_USE_ACCESSIBILITY_MODE, false);
askUserAboutDocumentLayout(pixOrg, accessibility);
mButtonStartOCR = (Button) findViewById(R.id.column_pick_completed);
initAppIcon(this, -1);
}
private void askUserAboutDocumentLayout(final Pix pixOrg, final boolean accessibility) {
AlertDialog alertDialog = LayoutQuestionDialog.createDialog(this,
new LayoutChoseListener() {
@Override
public void onLayoutChosen(final LayoutKind layoutKind,
final String ocrLanguage) {
if (layoutKind == LayoutKind.DO_NOTHING) {
saveDocument(pixOrg, null, null, 0);
} else {
mOcrLanguage = ocrLanguage;
getSupportActionBar().show();
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle(R.string.progress_start);
if (layoutKind == LayoutKind.SIMPLE) {
mOCR.startOCRForSimpleLayout(OCRActivity.this, determineOcrLanguage(ocrLanguage), pixOrg);
} else if (layoutKind == LayoutKind.COMPLEX) {
mAccuracy = 0;
mOCR.startLayoutAnalysis(pixOrg);
}
}
}
}, accessibility);
alertDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
alertDialog.show();
}
private String determineOcrLanguage(String ocrLanguage) {
final String english = "eng";
if (!ocrLanguage.equals(english) && addEnglishData(ocrLanguage)) {
return ocrLanguage + "+" + english;
} else {
return ocrLanguage;
}
}
// when combining languages that have multi byte characters with english
// training data the ocr text gets corrupted
// but adding english will improve overall accuracy for the other languages
private static boolean addEnglishData(String mLanguage) {
if (mLanguage.startsWith("chi") || mLanguage.equalsIgnoreCase("tha")
|| mLanguage.equalsIgnoreCase("kor")
|| mLanguage.equalsIgnoreCase("hin")
|| mLanguage.equalsIgnoreCase("heb")
|| mLanguage.equalsIgnoreCase("ell")
|| mLanguage.equalsIgnoreCase("bel")
|| mLanguage.equalsIgnoreCase("ara")
|| mLanguage.equalsIgnoreCase("grc")
|| mLanguage.equalsIgnoreCase("rus")
|| mLanguage.equalsIgnoreCase("vie")) {
return false;
}
return true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mOcrLanguage != null) {
outState.putString(OCR_LANGUAGE, mOcrLanguage);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (mOcrLanguage == null) {
mOcrLanguage = savedInstanceState.getString(OCR_LANGUAGE);
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFinalPix != null) {
mFinalPix.recycle();
mFinalPix = null;
}
BitmapDrawable bd = (BitmapDrawable) mImageView.getDrawable();
if (bd != null) {
bd.getBitmap().recycle();
}
}
}
| bugfix: Do not add english data when recognising japanese text.
| app/src/main/java/com/renard/ocr/OCRActivity.java | bugfix: Do not add english data when recognising japanese text. | <ide><path>pp/src/main/java/com/renard/ocr/OCRActivity.java
<ide> || mLanguage.equalsIgnoreCase("kor")
<ide> || mLanguage.equalsIgnoreCase("hin")
<ide> || mLanguage.equalsIgnoreCase("heb")
<add> || mLanguage.equalsIgnoreCase("jap")
<ide> || mLanguage.equalsIgnoreCase("ell")
<ide> || mLanguage.equalsIgnoreCase("bel")
<ide> || mLanguage.equalsIgnoreCase("ara") |
|
Java | mit | c0f5d3dd03238db943a3c81454cd5ca765bf0b87 | 0 | mattparks/Flounder-Engine | package flounder.devices;
import flounder.fbos.*;
import flounder.framework.*;
import flounder.logger.*;
import flounder.profiling.*;
import flounder.resources.*;
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
import java.nio.*;
import java.util.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* A module used for the creation, updating and destruction of the display.
*/
public class FlounderDisplay extends Module {
private static final FlounderDisplay INSTANCE = new FlounderDisplay();
public static final String PROFILE_TAB_NAME = "Display";
private int windowWidth;
private int windowHeight;
private int fullscreenWidth;
private int fullscreenHeight;
private String title;
private MyFile[] icons;
private boolean vsync;
private boolean antialiasing;
private int samples;
private boolean fullscreen;
private boolean hiddenDisplay;
private long window;
private boolean closed;
private boolean focused;
private int windowPosX;
private int windowPosY;
private boolean setup;
private GLFWWindowCloseCallback callbackWindowClose;
private GLFWWindowFocusCallback callbackWindowFocus;
private GLFWWindowPosCallback callbackWindowPos;
private GLFWWindowSizeCallback callbackWindowSize;
private GLFWFramebufferSizeCallback callbackFramebufferSize;
/**
* Creates a new GLFW display manager.
*/
public FlounderDisplay() {
super(ModuleUpdate.UPDATE_ALWAYS, PROFILE_TAB_NAME, FlounderLogger.class, FlounderProfiler.class, FlounderDisplaySync.class);
}
/**
* A function called before initialization to configure the display.
*
* @param width The window width in pixels.
* @param height The window height in pixels.
* @param title The window title.
* @param icons A list of icons to load for the window.
* @param vsync If the window will use vSync..
* @param antialiasing If OpenGL will use antialiasing.
* @param samples How many MFAA samples should be done before swapping buffers. Zero disables multisampling. GLFW_DONT_CARE means no preference.
* @param fullscreen If the window will start fullscreen.
* @param hiddenDisplay If the display should be hidden on start, should be true when {@link FlounderDisplayJPanel} is being used.
*/
public static void setup(int width, int height, String title, MyFile[] icons, boolean vsync, boolean antialiasing, int samples, boolean fullscreen, boolean hiddenDisplay) {
if (!INSTANCE.isInitialized()) {
INSTANCE.windowWidth = width;
INSTANCE.windowHeight = height;
INSTANCE.title = title;
INSTANCE.icons = icons;
INSTANCE.vsync = vsync;
INSTANCE.antialiasing = antialiasing;
INSTANCE.samples = samples;
INSTANCE.fullscreen = fullscreen;
INSTANCE.hiddenDisplay = hiddenDisplay;
INSTANCE.setup = true;
} else {
FlounderLogger.error("Flounder Display setup MUST be called before the INSTANCE is initialized.");
}
}
@Override
public void init() {
if (!setup) {
FlounderLogger.error("Flounder Display setup can be used to configure the display, default settings were set!");
this.windowWidth = 1080;
this.windowHeight = 720;
this.title = "Testing 1";
this.icons = new MyFile[]{new MyFile(MyFile.RES_FOLDER, "flounder.png")};
this.vsync = true;
this.antialiasing = true;
this.samples = 0;
this.fullscreen = false;
this.setup = true;
}
// Initialize the GLFW library.
if (!glfwInit()) {
FlounderLogger.error("Could not init GLFW!");
System.exit(-1);
}
// Gets the video mode from the primary monitor.
long monitor = glfwGetPrimaryMonitor();
GLFWVidMode mode = glfwGetVideoMode(monitor);
// Configures the window.
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // The window will stay hidden until after creation.
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // The window will be resizable depending on if its createDisplay.
// Use FBO antialiasing instead!
//if (samples > 0) {
// glfwWindowHint(GLFW_SAMPLES, samples); // The number of MSAA samples to use.
//}
if (fullscreen && mode != null) {
fullscreenWidth = mode.width();
fullscreenHeight = mode.height();
glfwWindowHint(GLFW_RED_BITS, mode.redBits());
glfwWindowHint(GLFW_GREEN_BITS, mode.greenBits());
glfwWindowHint(GLFW_BLUE_BITS, mode.blueBits());
glfwWindowHint(GLFW_REFRESH_RATE, mode.refreshRate());
}
// Create a windowed mode window and its OpenGL context.
window = glfwCreateWindow(fullscreen ? fullscreenWidth : windowWidth, fullscreen ? fullscreenHeight : windowHeight, title, fullscreen ? monitor : NULL, NULL);
// Sets the display to fullscreen or windowed.
focused = true;
// Gets any window errors.
if (window == NULL) {
FlounderLogger.error("Could not create the window!");
glfwTerminate();
System.exit(-1);
}
// Creates the OpenGL context.
glfwMakeContextCurrent(window);
try {
setWindowIcon();
} catch (IOException e) {
FlounderLogger.error("Could not load custom display image!");
FlounderLogger.exception(e);
}
// LWJGL will detect the context that is current in the current thread, creates the GLCapabilities instance and makes the OpenGL bindings available for use.
createCapabilities(true);
// Gets any OpenGL errors.
long glError = glGetError();
if (glError != GL_NO_ERROR) {
FlounderLogger.error("OpenGL Error: " + glError);
glfwDestroyWindow(window);
glfwTerminate();
System.exit(-1);
}
// Enables VSync if requested.
glfwSwapInterval(vsync ? 1 : 0);
if (vsync) {
Framework.setFpsLimit(60);
}
// Centres the window position.
if (!fullscreen && mode != null) {
glfwSetWindowPos(window, (windowPosX = (mode.width() - windowWidth) / 2), (windowPosY = (mode.height() - windowHeight) / 2));
}
// Shows the OpenGl window.
if (hiddenDisplay) {
glfwHideWindow(window);
} else {
glfwShowWindow(window);
}
// Sets the displays callbacks.
glfwSetWindowCloseCallback(window, callbackWindowClose = new GLFWWindowCloseCallback() {
@Override
public void invoke(long window) {
closed = true;
Framework.requestClose();
}
});
glfwSetWindowFocusCallback(window, callbackWindowFocus = new GLFWWindowFocusCallback() {
@Override
public void invoke(long window, boolean focus) {
focused = focus;
}
});
glfwSetWindowPosCallback(window, callbackWindowPos = new GLFWWindowPosCallback() {
@Override
public void invoke(long window, int xpos, int ypos) {
if (!fullscreen) {
windowPosX = xpos;
windowPosY = ypos;
}
}
});
glfwSetWindowSizeCallback(window, callbackWindowSize = new GLFWWindowSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
if (!fullscreen) {
windowWidth = width;
windowHeight = height;
}
}
});
glfwSetFramebufferSizeCallback(window, callbackFramebufferSize = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
glViewport(0, 0, width, height);
}
});
// System logs.
FlounderLogger.log("");
FlounderLogger.log("===== This is not an error message, it is a system info log. =====");
FlounderLogger.log("Flounder Engine Version: " + Framework.getVersion().getVersion());
FlounderLogger.log("Flounder Operating System: " + System.getProperty("os.name"));
FlounderLogger.log("Flounder OpenGL Version: " + glGetString(GL_VERSION));
FlounderLogger.log("Flounder OpenGL Vendor: " + glGetString(GL_VENDOR));
FlounderLogger.log("Flounder Available Processors (cores): " + Runtime.getRuntime().availableProcessors());
FlounderLogger.log("Flounder Free Memory (bytes): " + Runtime.getRuntime().freeMemory());
FlounderLogger.log("Flounder Maximum Memory (bytes): " + (Runtime.getRuntime().maxMemory() == Long.MAX_VALUE ? "Unlimited" : Runtime.getRuntime().maxMemory()));
FlounderLogger.log("Flounder Total Memory Available To JVM (bytes): " + Runtime.getRuntime().totalMemory());
FlounderLogger.log("Flounder Maximum FBO Size: " + FBO.getMaxFBOSize());
FlounderLogger.log("===== End of system info log. =====\n");
}
private void setWindowIcon() throws IOException {
// Creates a GLFWImage Buffer,
GLFWImage.Buffer images = GLFWImage.malloc(icons.length);
for (int i = 0; i < icons.length; i++) {
images.put(i, loadGLFWImage(icons[i])); // Stores a image into a slot.
}
// Loads the buffer into the window.
glfwSetWindowIcon(window, images);
}
private GLFWImage loadGLFWImage(MyFile file) throws IOException {
BufferedImage image = ImageIO.read(file.getInputStream());
int width = image.getWidth();
int height = image.getHeight();
int[] pixels = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0, width);
// Converts image to RGBA format.
ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * 4);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixel = pixels[y * width + x];
buffer.put((byte) ((pixel >> 16) & 0xFF)); // Red.
buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green.
buffer.put((byte) (pixel & 0xFF)); // Blue.
buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha.
}
}
buffer.flip(); // This will flip the cursor image vertically.
// Creates a GLFWImage.
GLFWImage glfwImage = GLFWImage.create();
glfwImage.width(width); // Setup the images' width.
glfwImage.height(height); // Setup the images' height.
glfwImage.pixels(buffer); // Pass image data.
return glfwImage;
}
@Override
public void update() {
// Polls for window events. The key callback will only be invoked during this call.
glfwPollEvents();
}
/**
* Updates the display image by swapping the colour buffers.
*/
public static void swapBuffers() {
if (INSTANCE.window != 0) {
glfwSwapBuffers(INSTANCE.window);
}
}
@Override
public void profile() {
FlounderProfiler.add(PROFILE_TAB_NAME, "Width", windowWidth);
FlounderProfiler.add(PROFILE_TAB_NAME, "Height", windowHeight);
FlounderProfiler.add(PROFILE_TAB_NAME, "Title", title);
FlounderProfiler.add(PROFILE_TAB_NAME, "VSync", vsync);
FlounderProfiler.add(PROFILE_TAB_NAME, "Antialiasing", antialiasing);
FlounderProfiler.add(PROFILE_TAB_NAME, "Samples", samples);
FlounderProfiler.add(PROFILE_TAB_NAME, "Fullscreen", fullscreen);
FlounderProfiler.add(PROFILE_TAB_NAME, "Closed", closed);
FlounderProfiler.add(PROFILE_TAB_NAME, "Focused", focused);
FlounderProfiler.add(PROFILE_TAB_NAME, "Window Pos.X", windowPosX);
FlounderProfiler.add(PROFILE_TAB_NAME, "Window Pos.Y", windowPosY);
}
/**
* Takes a screenshot of the current image of the display and saves it into the screenshots folder a png image.
*/
public static void screenshot() {
// Tries to create an image, otherwise throws an exception.
String name = Calendar.getInstance().get(Calendar.MONTH) + 1 + "." + Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + "." + Calendar.getInstance().get(Calendar.HOUR) + "." + Calendar.getInstance().get(Calendar.MINUTE) + "." + (Calendar.getInstance().get(Calendar.SECOND) + 1);
File saveDirectory = new File(Framework.getRoamingFolder().getPath(), "screenshots");
if (!saveDirectory.exists()) {
try {
if (!saveDirectory.mkdir()) {
FlounderLogger.error("The screenshot directory could not be created.");
}
} catch (SecurityException e) {
FlounderLogger.error("The screenshot directory could not be created.");
FlounderLogger.exception(e);
return;
}
}
File file = new File(saveDirectory + "/" + name + ".png"); // The file to save the pixels too.
String format = "png"; // "PNG" or "JPG".
FlounderLogger.log("Taking screenshot and outputting it to " + file.getAbsolutePath());
// Tries to create image.
try {
ImageIO.write(getImage(null, null), format, file);
} catch (Exception e) {
FlounderLogger.error("Failed to take screenshot.");
FlounderLogger.exception(e);
}
}
/**
* Creates a buffered image from the OpenGL pixel buffer.
*
* @param destination The destination BufferedImage to store in, if null a new one will be created.
* @param buffer The buffer to store OpenGL data into, if null a new one will be created.
*
* @return A new buffered image containing the displays data.
*/
public static BufferedImage getImage(BufferedImage destination, ByteBuffer buffer) {
// Creates a new destination if it does not exist, or fixes a old one,
if (destination == null || buffer == null || destination.getWidth() != getWidth() || destination.getHeight() != getHeight()) {
destination = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
buffer = BufferUtils.createByteBuffer(getWidth() * getHeight() * 4);
}
// Creates a new buffer and stores the displays data into it.
glReadPixels(0, 0, getWidth(), getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// Transfers the data from the buffer into the image. This requires bit shifts to get the components data.
for (int x = destination.getWidth() - 1; x >= 0; x--) {
for (int y = destination.getHeight() - 1; y >= 0; y--) {
int i = (x + getWidth() * y) * 4;
destination.setRGB(x, destination.getHeight() - 1 - y, (((buffer.get(i) & 0xFF) & 0x0ff) << 16) | (((buffer.get(i + 1) & 0xFF) & 0x0ff) << 8) | ((buffer.get(i + 2) & 0xFF) & 0x0ff));
}
}
return destination;
}
/**
* Gets the width of the display in pixels.
*
* @return The width of the display.
*/
public static int getWidth() {
return INSTANCE.fullscreen ? INSTANCE.fullscreenWidth : INSTANCE.windowWidth;
}
public static int getWindowWidth() {
return INSTANCE.windowWidth;
}
/**
* Gets the height of the display in pixels.
*
* @return The height of the display.
*/
public static int getHeight() {
return INSTANCE.fullscreen ? INSTANCE.fullscreenHeight : INSTANCE.windowHeight;
}
public static int getWindowHeight() {
return INSTANCE.windowHeight;
}
/**
* Gets the aspect ratio between the displays width and height.
*
* @return The aspect ratio.
*/
public static float getAspectRatio() {
return ((float) getWidth()) / ((float) getHeight());
}
/**
* Gets the window's title.
*
* @return The window's title.
*/
public static String getTitle() {
return INSTANCE.title;
}
/**
* gets if the display is using vSync.
*
* @return If VSync is enabled.
*/
public static boolean isVSync() {
return INSTANCE.vsync;
}
/**
* Sets the display to use VSync or not.
*
* @param vsync Weather or not to use vSync.
*/
public static void setVSync(boolean vsync) {
INSTANCE.vsync = vsync;
glfwSwapInterval(vsync ? 1 : 0);
if (vsync) {
Framework.setFpsLimit(-1);
}
}
/**
* Gets if the display requests antialiased images.
*
* @return If using antialiased images.
*/
public static boolean isAntialiasing() {
return INSTANCE.antialiasing;
}
/**
* Requests the display to antialias.
*
* @param antialiasing If the display should antialias.
*/
public static void setAntialiasing(boolean antialiasing) {
INSTANCE.antialiasing = antialiasing;
}
/**
* Gets how many MFAA samples should be done before swapping buffers.
*
* @return Amount of MFAA samples.
*/
public static int getSamples() {
return INSTANCE.samples;
}
/**
* Gets how many MFAA samples should be done before swapping buffers. Zero disables multisampling. GLFW_DONT_CARE means no preference.
*
* @param samples The amount of MFSS samples.
*/
public static void setSamples(int samples) {
INSTANCE.samples = samples;
glfwWindowHint(GLFW_SAMPLES, samples);
}
/**
* Gets weather the display is fullscreen or not.
*
* @return Fullscreen or windowed.
*/
public static boolean isFullscreen() {
return INSTANCE.fullscreen;
}
/**
* Sets the display to be fullscreen or windowed.
*
* @param fullscreen Weather or not to be fullscreen.
*/
public static void setFullscreen(boolean fullscreen) {
if (INSTANCE.fullscreen == fullscreen) {
return;
}
INSTANCE.fullscreen = fullscreen;
long monitor = glfwGetPrimaryMonitor();
GLFWVidMode mode = glfwGetVideoMode(monitor);
FlounderLogger.log(fullscreen ? "Display is going fullscreen." : "Display is going windowed.");
if (fullscreen) {
INSTANCE.fullscreenWidth = mode.width();
INSTANCE.fullscreenHeight = mode.height();
glfwSetWindowMonitor(INSTANCE.window, monitor, 0, 0, INSTANCE.fullscreenWidth, INSTANCE.fullscreenHeight, GLFW_DONT_CARE);
} else {
INSTANCE.windowPosX = (mode.width() - INSTANCE.windowWidth) / 2;
INSTANCE.windowPosY = (mode.height() - INSTANCE.windowHeight) / 2;
glfwSetWindowMonitor(INSTANCE.window, NULL, INSTANCE.windowPosX, INSTANCE.windowPosY, INSTANCE.windowWidth, INSTANCE.windowHeight, GLFW_DONT_CARE);
}
}
/**
* Gets the current GLFW window.
*
* @return The current GLFW window.
*/
public static long getWindow() {
return INSTANCE.window;
}
/**
* Gets if the GLFW display is closed.
*
* @return If the GLFW display is closed.
*/
public static boolean isClosed() {
return INSTANCE.closed;
}
/**
* Gets if the GLFW display is selected.
*
* @return If the GLFW display is selected.
*/
public static boolean isFocused() {
return INSTANCE.focused;
}
/**
* Gets the windows Y position of the display in pixels.
*
* @return The windows x position.
*/
public static int getWindowXPos() {
return INSTANCE.windowPosX;
}
/**
* Gets the windows Y position of the display in pixels.
*
* @return The windows Y position.
*/
public static int getWindowYPos() {
return INSTANCE.windowPosY;
}
/**
* @return The current GLFW time time in seconds.
*/
public static float getTime() {
return (float) (glfwGetTime() * 1000.0f);
}
@Override
public Module getInstance() {
return INSTANCE;
}
@Override
public void dispose() {
callbackWindowClose.free();
callbackWindowFocus.free();
callbackWindowPos.free();
callbackWindowSize.free();
callbackFramebufferSize.free();
// destroy(); // Would normally unload LWJGL natives, but for the Founder Engine we want to be able to reload the Engine in runtime.
glfwDestroyWindow(window);
glfwTerminate();
INSTANCE.closed = false;
INSTANCE.setup = false;
}
}
| src/flounder/devices/FlounderDisplay.java | package flounder.devices;
import flounder.fbos.*;
import flounder.framework.*;
import flounder.logger.*;
import flounder.profiling.*;
import flounder.resources.*;
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
import java.nio.*;
import java.util.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* A module used for the creation, updating and destruction of the display.
*/
public class FlounderDisplay extends Module {
private static final FlounderDisplay INSTANCE = new FlounderDisplay();
public static final String PROFILE_TAB_NAME = "Display";
private int windowWidth;
private int windowHeight;
private int fullscreenWidth;
private int fullscreenHeight;
private String title;
private MyFile[] icons;
private boolean vsync;
private boolean antialiasing;
private int samples;
private boolean fullscreen;
private boolean hiddenDisplay;
private long window;
private boolean closed;
private boolean focused;
private int windowPosX;
private int windowPosY;
private boolean setup;
private GLFWWindowCloseCallback callbackWindowClose;
private GLFWWindowFocusCallback callbackWindowFocus;
private GLFWWindowPosCallback callbackWindowPos;
private GLFWWindowSizeCallback callbackWindowSize;
private GLFWFramebufferSizeCallback callbackFramebufferSize;
/**
* Creates a new GLFW display manager.
*/
public FlounderDisplay() {
super(ModuleUpdate.UPDATE_ALWAYS, PROFILE_TAB_NAME, FlounderLogger.class, FlounderProfiler.class, FlounderDisplaySync.class);
}
/**
* A function called before initialization to configure the display.
*
* @param width The window width in pixels.
* @param height The window height in pixels.
* @param title The window title.
* @param icons A list of icons to load for the window.
* @param vsync If the window will use vSync..
* @param antialiasing If OpenGL will use antialiasing.
* @param samples How many MFAA samples should be done before swapping buffers. Zero disables multisampling. GLFW_DONT_CARE means no preference.
* @param fullscreen If the window will start fullscreen.
* @param hiddenDisplay If the display should be hidden on start, should be true when {@link FlounderDisplayJPanel} is being used.
*/
public static void setup(int width, int height, String title, MyFile[] icons, boolean vsync, boolean antialiasing, int samples, boolean fullscreen, boolean hiddenDisplay) {
if (!INSTANCE.isInitialized()) {
INSTANCE.windowWidth = width;
INSTANCE.windowHeight = height;
INSTANCE.title = title;
INSTANCE.icons = icons;
INSTANCE.vsync = vsync;
INSTANCE.antialiasing = antialiasing;
INSTANCE.samples = samples;
INSTANCE.fullscreen = fullscreen;
INSTANCE.hiddenDisplay = hiddenDisplay;
INSTANCE.setup = true;
} else {
FlounderLogger.error("Flounder Display setup MUST be called before the INSTANCE is initialized.");
}
}
@Override
public void init() {
if (!setup) {
FlounderLogger.error("Flounder Display setup can be used to configure the display, default settings were set!");
this.windowWidth = 1080;
this.windowHeight = 720;
this.title = "Testing 1";
this.icons = new MyFile[]{new MyFile(MyFile.RES_FOLDER, "flounder.png")};
this.vsync = true;
this.antialiasing = true;
this.samples = 0;
this.fullscreen = false;
this.setup = true;
}
// Initialize the GLFW library.
if (!glfwInit()) {
FlounderLogger.error("Could not init GLFW!");
System.exit(-1);
}
// Gets the video mode from the primary monitor.
long monitor = glfwGetPrimaryMonitor();
GLFWVidMode mode = glfwGetVideoMode(monitor);
// Configures the window.
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // The window will stay hidden until after creation.
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // The window will be resizable depending on if its createDisplay.
if (samples > 0) {
glfwWindowHint(GLFW_SAMPLES, samples); // The number of MSAA samples to use.
}
if (fullscreen && mode != null) {
fullscreenWidth = mode.width();
fullscreenHeight = mode.height();
glfwWindowHint(GLFW_RED_BITS, mode.redBits());
glfwWindowHint(GLFW_GREEN_BITS, mode.greenBits());
glfwWindowHint(GLFW_BLUE_BITS, mode.blueBits());
glfwWindowHint(GLFW_REFRESH_RATE, mode.refreshRate());
}
// Create a windowed mode window and its OpenGL context.
window = glfwCreateWindow(fullscreen ? fullscreenWidth : windowWidth, fullscreen ? fullscreenHeight : windowHeight, title, fullscreen ? monitor : NULL, NULL);
// Sets the display to fullscreen or windowed.
focused = true;
// Gets any window errors.
if (window == NULL) {
FlounderLogger.error("Could not create the window!");
glfwTerminate();
System.exit(-1);
}
// Creates the OpenGL context.
glfwMakeContextCurrent(window);
try {
setWindowIcon();
} catch (IOException e) {
FlounderLogger.error("Could not load custom display image!");
FlounderLogger.exception(e);
}
// LWJGL will detect the context that is current in the current thread, creates the GLCapabilities instance and makes the OpenGL bindings available for use.
createCapabilities(true);
// Gets any OpenGL errors.
long glError = glGetError();
if (glError != GL_NO_ERROR) {
FlounderLogger.error("OpenGL Error: " + glError);
glfwDestroyWindow(window);
glfwTerminate();
System.exit(-1);
}
// Enables VSync if requested.
glfwSwapInterval(vsync ? 1 : 0);
if (vsync) {
Framework.setFpsLimit(60);
}
// Centres the window position.
if (!fullscreen && mode != null) {
glfwSetWindowPos(window, (windowPosX = (mode.width() - windowWidth) / 2), (windowPosY = (mode.height() - windowHeight) / 2));
}
// Shows the OpenGl window.
if (hiddenDisplay) {
glfwHideWindow(window);
} else {
glfwShowWindow(window);
}
// Sets the displays callbacks.
glfwSetWindowCloseCallback(window, callbackWindowClose = new GLFWWindowCloseCallback() {
@Override
public void invoke(long window) {
closed = true;
Framework.requestClose();
}
});
glfwSetWindowFocusCallback(window, callbackWindowFocus = new GLFWWindowFocusCallback() {
@Override
public void invoke(long window, boolean focus) {
focused = focus;
}
});
glfwSetWindowPosCallback(window, callbackWindowPos = new GLFWWindowPosCallback() {
@Override
public void invoke(long window, int xpos, int ypos) {
if (!fullscreen) {
windowPosX = xpos;
windowPosY = ypos;
}
}
});
glfwSetWindowSizeCallback(window, callbackWindowSize = new GLFWWindowSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
if (!fullscreen) {
windowWidth = width;
windowHeight = height;
}
}
});
glfwSetFramebufferSizeCallback(window, callbackFramebufferSize = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
glViewport(0, 0, width, height);
}
});
// System logs.
FlounderLogger.log("");
FlounderLogger.log("===== This is not an error message, it is a system info log. =====");
FlounderLogger.log("Flounder Engine Version: " + Framework.getVersion().getVersion());
FlounderLogger.log("Flounder Operating System: " + System.getProperty("os.name"));
FlounderLogger.log("Flounder OpenGL Version: " + glGetString(GL_VERSION));
FlounderLogger.log("Flounder OpenGL Vendor: " + glGetString(GL_VENDOR));
FlounderLogger.log("Flounder Available Processors (cores): " + Runtime.getRuntime().availableProcessors());
FlounderLogger.log("Flounder Free Memory (bytes): " + Runtime.getRuntime().freeMemory());
FlounderLogger.log("Flounder Maximum Memory (bytes): " + (Runtime.getRuntime().maxMemory() == Long.MAX_VALUE ? "Unlimited" : Runtime.getRuntime().maxMemory()));
FlounderLogger.log("Flounder Total Memory Available To JVM (bytes): " + Runtime.getRuntime().totalMemory());
FlounderLogger.log("Flounder Maximum FBO Size: " + FBO.getMaxFBOSize());
FlounderLogger.log("===== End of system info log. =====\n");
}
private void setWindowIcon() throws IOException {
// Creates a GLFWImage Buffer,
GLFWImage.Buffer images = GLFWImage.malloc(icons.length);
for (int i = 0; i < icons.length; i++) {
images.put(i, loadGLFWImage(icons[i])); // Stores a image into a slot.
}
// Loads the buffer into the window.
glfwSetWindowIcon(window, images);
}
private GLFWImage loadGLFWImage(MyFile file) throws IOException {
BufferedImage image = ImageIO.read(file.getInputStream());
int width = image.getWidth();
int height = image.getHeight();
int[] pixels = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0, width);
// Converts image to RGBA format.
ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * 4);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixel = pixels[y * width + x];
buffer.put((byte) ((pixel >> 16) & 0xFF)); // Red.
buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green.
buffer.put((byte) (pixel & 0xFF)); // Blue.
buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha.
}
}
buffer.flip(); // This will flip the cursor image vertically.
// Creates a GLFWImage.
GLFWImage glfwImage = GLFWImage.create();
glfwImage.width(width); // Setup the images' width.
glfwImage.height(height); // Setup the images' height.
glfwImage.pixels(buffer); // Pass image data.
return glfwImage;
}
@Override
public void update() {
// Polls for window events. The key callback will only be invoked during this call.
glfwPollEvents();
}
/**
* Updates the display image by swapping the colour buffers.
*/
public static void swapBuffers() {
if (INSTANCE.window != 0) {
glfwSwapBuffers(INSTANCE.window);
}
}
@Override
public void profile() {
FlounderProfiler.add(PROFILE_TAB_NAME, "Width", windowWidth);
FlounderProfiler.add(PROFILE_TAB_NAME, "Height", windowHeight);
FlounderProfiler.add(PROFILE_TAB_NAME, "Title", title);
FlounderProfiler.add(PROFILE_TAB_NAME, "VSync", vsync);
FlounderProfiler.add(PROFILE_TAB_NAME, "Antialiasing", antialiasing);
FlounderProfiler.add(PROFILE_TAB_NAME, "Samples", samples);
FlounderProfiler.add(PROFILE_TAB_NAME, "Fullscreen", fullscreen);
FlounderProfiler.add(PROFILE_TAB_NAME, "Closed", closed);
FlounderProfiler.add(PROFILE_TAB_NAME, "Focused", focused);
FlounderProfiler.add(PROFILE_TAB_NAME, "Window Pos.X", windowPosX);
FlounderProfiler.add(PROFILE_TAB_NAME, "Window Pos.Y", windowPosY);
}
/**
* Takes a screenshot of the current image of the display and saves it into the screenshots folder a png image.
*/
public static void screenshot() {
// Tries to create an image, otherwise throws an exception.
String name = Calendar.getInstance().get(Calendar.MONTH) + 1 + "." + Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + "." + Calendar.getInstance().get(Calendar.HOUR) + "." + Calendar.getInstance().get(Calendar.MINUTE) + "." + (Calendar.getInstance().get(Calendar.SECOND) + 1);
File saveDirectory = new File(Framework.getRoamingFolder().getPath(), "screenshots");
if (!saveDirectory.exists()) {
try {
if (!saveDirectory.mkdir()) {
FlounderLogger.error("The screenshot directory could not be created.");
}
} catch (SecurityException e) {
FlounderLogger.error("The screenshot directory could not be created.");
FlounderLogger.exception(e);
return;
}
}
File file = new File(saveDirectory + "/" + name + ".png"); // The file to save the pixels too.
String format = "png"; // "PNG" or "JPG".
FlounderLogger.log("Taking screenshot and outputting it to " + file.getAbsolutePath());
// Tries to create image.
try {
ImageIO.write(getImage(null, null), format, file);
} catch (Exception e) {
FlounderLogger.error("Failed to take screenshot.");
FlounderLogger.exception(e);
}
}
/**
* Creates a buffered image from the OpenGL pixel buffer.
*
* @param destination The destination BufferedImage to store in, if null a new one will be created.
* @param buffer The buffer to store OpenGL data into, if null a new one will be created.
*
* @return A new buffered image containing the displays data.
*/
public static BufferedImage getImage(BufferedImage destination, ByteBuffer buffer) {
// Creates a new destination if it does not exist, or fixes a old one,
if (destination == null || buffer == null || destination.getWidth() != getWidth() || destination.getHeight() != getHeight()) {
destination = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
buffer = BufferUtils.createByteBuffer(getWidth() * getHeight() * 4);
}
// Creates a new buffer and stores the displays data into it.
glReadPixels(0, 0, getWidth(), getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// Transfers the data from the buffer into the image. This requires bit shifts to get the components data.
for (int x = destination.getWidth() - 1; x >= 0; x--) {
for (int y = destination.getHeight() - 1; y >= 0; y--) {
int i = (x + getWidth() * y) * 4;
destination.setRGB(x, destination.getHeight() - 1 - y, (((buffer.get(i) & 0xFF) & 0x0ff) << 16) | (((buffer.get(i + 1) & 0xFF) & 0x0ff) << 8) | ((buffer.get(i + 2) & 0xFF) & 0x0ff));
}
}
return destination;
}
/**
* Gets the width of the display in pixels.
*
* @return The width of the display.
*/
public static int getWidth() {
return INSTANCE.fullscreen ? INSTANCE.fullscreenWidth : INSTANCE.windowWidth;
}
public static int getWindowWidth() {
return INSTANCE.windowWidth;
}
/**
* Gets the height of the display in pixels.
*
* @return The height of the display.
*/
public static int getHeight() {
return INSTANCE.fullscreen ? INSTANCE.fullscreenHeight : INSTANCE.windowHeight;
}
public static int getWindowHeight() {
return INSTANCE.windowHeight;
}
/**
* Gets the aspect ratio between the displays width and height.
*
* @return The aspect ratio.
*/
public static float getAspectRatio() {
return ((float) getWidth()) / ((float) getHeight());
}
/**
* Gets the window's title.
*
* @return The window's title.
*/
public static String getTitle() {
return INSTANCE.title;
}
/**
* gets if the display is using vSync.
*
* @return If VSync is enabled.
*/
public static boolean isVSync() {
return INSTANCE.vsync;
}
/**
* Sets the display to use VSync or not.
*
* @param vsync Weather or not to use vSync.
*/
public static void setVSync(boolean vsync) {
INSTANCE.vsync = vsync;
glfwSwapInterval(vsync ? 1 : 0);
if (vsync) {
Framework.setFpsLimit(-1);
}
}
/**
* Gets if the display requests antialiased images.
*
* @return If using antialiased images.
*/
public static boolean isAntialiasing() {
return INSTANCE.antialiasing;
}
/**
* Requests the display to antialias.
*
* @param antialiasing If the display should antialias.
*/
public static void setAntialiasing(boolean antialiasing) {
INSTANCE.antialiasing = antialiasing;
}
/**
* Gets how many MFAA samples should be done before swapping buffers.
*
* @return Amount of MFAA samples.
*/
public static int getSamples() {
return INSTANCE.samples;
}
/**
* Gets how many MFAA samples should be done before swapping buffers. Zero disables multisampling. GLFW_DONT_CARE means no preference.
*
* @param samples The amount of MFSS samples.
*/
public static void setSamples(int samples) {
INSTANCE.samples = samples;
glfwWindowHint(GLFW_SAMPLES, samples);
}
/**
* Gets weather the display is fullscreen or not.
*
* @return Fullscreen or windowed.
*/
public static boolean isFullscreen() {
return INSTANCE.fullscreen;
}
/**
* Sets the display to be fullscreen or windowed.
*
* @param fullscreen Weather or not to be fullscreen.
*/
public static void setFullscreen(boolean fullscreen) {
if (INSTANCE.fullscreen == fullscreen) {
return;
}
INSTANCE.fullscreen = fullscreen;
long monitor = glfwGetPrimaryMonitor();
GLFWVidMode mode = glfwGetVideoMode(monitor);
FlounderLogger.log(fullscreen ? "Display is going fullscreen." : "Display is going windowed.");
if (fullscreen) {
INSTANCE.fullscreenWidth = mode.width();
INSTANCE.fullscreenHeight = mode.height();
glfwSetWindowMonitor(INSTANCE.window, monitor, 0, 0, INSTANCE.fullscreenWidth, INSTANCE.fullscreenHeight, GLFW_DONT_CARE);
} else {
INSTANCE.windowPosX = (mode.width() - INSTANCE.windowWidth) / 2;
INSTANCE.windowPosY = (mode.height() - INSTANCE.windowHeight) / 2;
glfwSetWindowMonitor(INSTANCE.window, NULL, INSTANCE.windowPosX, INSTANCE.windowPosY, INSTANCE.windowWidth, INSTANCE.windowHeight, GLFW_DONT_CARE);
}
}
/**
* Gets the current GLFW window.
*
* @return The current GLFW window.
*/
public static long getWindow() {
return INSTANCE.window;
}
/**
* Gets if the GLFW display is closed.
*
* @return If the GLFW display is closed.
*/
public static boolean isClosed() {
return INSTANCE.closed;
}
/**
* Gets if the GLFW display is selected.
*
* @return If the GLFW display is selected.
*/
public static boolean isFocused() {
return INSTANCE.focused;
}
/**
* Gets the windows Y position of the display in pixels.
*
* @return The windows x position.
*/
public static int getWindowXPos() {
return INSTANCE.windowPosX;
}
/**
* Gets the windows Y position of the display in pixels.
*
* @return The windows Y position.
*/
public static int getWindowYPos() {
return INSTANCE.windowPosY;
}
/**
* @return The current GLFW time time in seconds.
*/
public static float getTime() {
return (float) (glfwGetTime() * 1000.0f);
}
@Override
public Module getInstance() {
return INSTANCE;
}
@Override
public void dispose() {
callbackWindowClose.free();
callbackWindowFocus.free();
callbackWindowPos.free();
callbackWindowSize.free();
callbackFramebufferSize.free();
// destroy(); // Would normally unload LWJGL natives, but for the Founder Engine we want to be able to reload the Engine in runtime.
glfwDestroyWindow(window);
glfwTerminate();
INSTANCE.closed = false;
INSTANCE.setup = false;
}
}
| Display tweaks, timings changed.
| src/flounder/devices/FlounderDisplay.java | Display tweaks, timings changed. | <ide><path>rc/flounder/devices/FlounderDisplay.java
<ide> glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // The window will stay hidden until after creation.
<ide> glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // The window will be resizable depending on if its createDisplay.
<ide>
<del> if (samples > 0) {
<del> glfwWindowHint(GLFW_SAMPLES, samples); // The number of MSAA samples to use.
<del> }
<add> // Use FBO antialiasing instead!
<add> //if (samples > 0) {
<add> // glfwWindowHint(GLFW_SAMPLES, samples); // The number of MSAA samples to use.
<add> //}
<ide>
<ide> if (fullscreen && mode != null) {
<ide> fullscreenWidth = mode.width(); |
|
JavaScript | apache-2.0 | c6f06bb6eb3f1542bb1566933ec5fab5c6f592e1 | 0 | stamp-web/stamp-web-aurelia,stamp-web/stamp-web-aurelia | /**
Copyright 2017 Jason Drake
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.
*/
import {LogManager} from 'aurelia-framework';
import {NewInstance} from 'aurelia-dependency-injection';
import {EventAggregator} from 'aurelia-event-aggregator';
import {HttpClient} from 'aurelia-http-client';
import {Preferences} from 'services/preferences';
import environment from './environment';
import Backend from 'i18next-xhr-backend'
import _ from 'lodash';
const logger = LogManager.getLogger('stamp-web');
require.config({catchError: true, waitSeconds: 30});
if (window.location.href.indexOf('debug=true') >= 0) {
LogManager.setLevel(LogManager.logLevel.debug);
}
//Configure Bluebird Promises.
//Note: You may want to use environment-specific configuration.
Promise.config({
warnings: {
wForgottenReturn: false
}
});
function getLang() {
// Ideally we should DI these objects. Investigate how we could do this at this early phase of the app
let httpClient = new HttpClient();
let eventBus = new EventAggregator();
let prefs = new Preferences(httpClient,eventBus);
return new Promise( (resolve,reject) => {
if( prefs ) {
prefs.find({
$filter: "(category eq 'user') and (name eq 'locale')"
}).then(result => {
let lang = 'en';
if( !_.isEmpty(result) ) {
lang = _.first(result.models).value;
}
resolve(lang);
}).catch( e => {
reject(new Error("Failure querying preferences"));
});
} else {
reject(new Error("Preferences services is not available"));
}
});
}
function setRoot(aurelia) {
logger.info('bootstrapped:' + aurelia.setupAureliaFinished + ", localization:" + aurelia.setupI18NFinished);
if(aurelia.setupAureliaFinished && aurelia.setupI18NFinished) {
aurelia.setRoot('app');
}
}
export function configure(aurelia) {
configureGlobalLibraries();
getLang().then(lang => {
initialize( aurelia, lang );
}).catch(e => {
console.log('WARNING: Failure to obtain a language to use for Stamp-Web. Defaulting to "en"');
initialize( aurelia, 'en');
});
}
function configureGlobalLibraries() {
require(['tether', 'jquery', 'popper.js'], (tether, jquery, popper) => {
window.Tether = tether;
window.jQuery = jquery;
window.Popper = popper;
require(['bootstrap']);
});
}
function initialize( aurelia, lang ) {
aurelia.setupAureliaFinished = false;
aurelia.setupI18NFinished = false;
aurelia.use
.standardConfiguration()
.feature('resources')
/*
.plugin('aurelia-html-import-template-loader')
*/
.plugin('aurelia-dialog', config => {
config.useDefaults();
config.settings.lock = true;
config.settings.centerHorizontalOnly = false;
config.settings.startingZIndex = 1000;
})
.plugin('aurelia-validation')
.feature('bootstrap-validation')
.plugin('aurelia-i18n', (instance) => {
instance.i18next.use(Backend);
instance.setup({
backend: { // <-- configure backend settings
loadPath: 'resources/locales/{{lng}}/{{ns}}.json' // <-- XHR settings for where to get the files from
},
lng: lang,
attributes: ['t', 'i18n'],
fallbackLng: 'en',
ns: ['stamp-web'/*, 'translation'*/],
fallbackNS: ['stamp-web'],
defaultNS: 'stamp-web',
debug: false // make true to see un-translated keys
}).then( () => {
aurelia.setupI18NFinished = true;
setRoot(aurelia);
});
})
.plugin('aurelia-ui-virtualization');
if (environment.debug) {
aurelia.use.developmentLogging();
}
if (environment.testing) {
aurelia.use.plugin('aurelia-testing');
}
aurelia.start().then( () => {
aurelia.setupAureliaFinished = true;
setRoot(aurelia);
});
}
| src/main.js | /**
Copyright 2017 Jason Drake
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.
*/
import {LogManager} from 'aurelia-framework';
import {NewInstance} from 'aurelia-dependency-injection';
import {EventAggregator} from 'aurelia-event-aggregator';
import {HttpClient} from 'aurelia-http-client';
import {Preferences} from 'services/preferences';
import environment from './environment';
import Backend from 'i18next-xhr-backend'
import _ from 'lodash';
const logger = LogManager.getLogger('stamp-web');
require.config({catchError: true, waitSeconds: 30});
if (window.location.href.indexOf('debug=true') >= 0) {
LogManager.setLevel(LogManager.logLevel.debug);
}
//Configure Bluebird Promises.
//Note: You may want to use environment-specific configuration.
Promise.config({
warnings: {
wForgottenReturn: false
}
});
function getLang() {
// Ideally we should DI these objects. Investigate how we could do this at this early phase of the app
let httpClient = new HttpClient();
let eventBus = new EventAggregator();
let prefs = new Preferences(httpClient,eventBus);
return new Promise( (resolve,reject) => {
if( prefs ) {
prefs.find({
$filter: "(category eq 'user') and (name eq 'locale')"
}).then(result => {
let lang = 'en';
if( !_.isEmpty(result) ) {
lang = _.first(result.models).value;
}
resolve(lang);
}).catch( e => {
reject(new Error("Failure querying preferences"));
});
} else {
reject(new Error("Preferences services is not available"));
}
});
}
function setRoot(aurelia) {
logger.info('bootstrapped:' + aurelia.setupAureliaFinished + ", localization:" + aurelia.setupI18NFinished);
if(aurelia.setupAureliaFinished && aurelia.setupI18NFinished) {
aurelia.setRoot('app');
}
}
export function configure(aurelia) {
configureGlobalLibraries();
getLang().then(lang => {
initialize( aurelia, lang );
}).catch(e => {
console.log('WARNING: Failure to obtain a language to use for Stamp-Web. Defaulting to "en"');
initialize( aurelia, 'en');
});
}
function configureGlobalLibraries() {
require(['tether', 'jquery'], (tether, jquery) => {
window.Tether = tether;
window.jQuery = jquery;
require(['bootstrap']);
});
}
function initialize( aurelia, lang ) {
aurelia.setupAureliaFinished = false;
aurelia.setupI18NFinished = false;
aurelia.use
.standardConfiguration()
.feature('resources')
/*
.plugin('aurelia-html-import-template-loader')
*/
.plugin('aurelia-dialog', config => {
config.useDefaults();
config.settings.lock = true;
config.settings.centerHorizontalOnly = false;
config.settings.startingZIndex = 1000;
})
.plugin('aurelia-validation')
.feature('bootstrap-validation')
.plugin('aurelia-i18n', (instance) => {
instance.i18next.use(Backend);
instance.setup({
backend: { // <-- configure backend settings
loadPath: 'resources/locales/{{lng}}/{{ns}}.json' // <-- XHR settings for where to get the files from
},
lng: lang,
attributes: ['t', 'i18n'],
fallbackLng: 'en',
ns: ['stamp-web'/*, 'translation'*/],
fallbackNS: ['stamp-web'],
defaultNS: 'stamp-web',
debug: false // make true to see un-translated keys
}).then( () => {
aurelia.setupI18NFinished = true;
setRoot(aurelia);
});
})
.plugin('aurelia-ui-virtualization');
if (environment.debug) {
aurelia.use.developmentLogging();
}
if (environment.testing) {
aurelia.use.plugin('aurelia-testing');
}
aurelia.start().then( () => {
aurelia.setupAureliaFinished = true;
setRoot(aurelia);
});
}
| Initialize Popper.js
| src/main.js | Initialize Popper.js | <ide><path>rc/main.js
<ide> }
<ide>
<ide> function configureGlobalLibraries() {
<del> require(['tether', 'jquery'], (tether, jquery) => {
<add> require(['tether', 'jquery', 'popper.js'], (tether, jquery, popper) => {
<ide> window.Tether = tether;
<ide> window.jQuery = jquery;
<add> window.Popper = popper;
<ide> require(['bootstrap']);
<ide> });
<ide> } |
|
Java | apache-2.0 | e7a43b6e511bd12527eb239f452b54327eac0deb | 0 | bkirschn/sakai,pushyamig/sakai,lorenamgUMU/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,ouit0408/sakai,joserabal/sakai,conder/sakai,pushyamig/sakai,puramshetty/sakai,buckett/sakai-gitflow,bkirschn/sakai,noondaysun/sakai,kwedoff1/sakai,willkara/sakai,liubo404/sakai,surya-janani/sakai,bkirschn/sakai,ktakacs/sakai,Fudan-University/sakai,rodriguezdevera/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,bzhouduke123/sakai,colczr/sakai,liubo404/sakai,kingmook/sakai,pushyamig/sakai,frasese/sakai,ktakacs/sakai,introp-software/sakai,ouit0408/sakai,hackbuteer59/sakai,clhedrick/sakai,introp-software/sakai,introp-software/sakai,kwedoff1/sakai,buckett/sakai-gitflow,surya-janani/sakai,ktakacs/sakai,lorenamgUMU/sakai,joserabal/sakai,colczr/sakai,pushyamig/sakai,clhedrick/sakai,whumph/sakai,frasese/sakai,kwedoff1/sakai,bzhouduke123/sakai,kwedoff1/sakai,Fudan-University/sakai,udayg/sakai,willkara/sakai,joserabal/sakai,joserabal/sakai,kingmook/sakai,liubo404/sakai,lorenamgUMU/sakai,ktakacs/sakai,kwedoff1/sakai,OpenCollabZA/sakai,willkara/sakai,udayg/sakai,udayg/sakai,tl-its-umich-edu/sakai,bkirschn/sakai,Fudan-University/sakai,lorenamgUMU/sakai,zqian/sakai,zqian/sakai,wfuedu/sakai,colczr/sakai,buckett/sakai-gitflow,colczr/sakai,duke-compsci290-spring2016/sakai,zqian/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,bzhouduke123/sakai,tl-its-umich-edu/sakai,ouit0408/sakai,frasese/sakai,clhedrick/sakai,bzhouduke123/sakai,lorenamgUMU/sakai,ouit0408/sakai,frasese/sakai,bzhouduke123/sakai,udayg/sakai,ouit0408/sakai,hackbuteer59/sakai,conder/sakai,rodriguezdevera/sakai,duke-compsci290-spring2016/sakai,conder/sakai,wfuedu/sakai,noondaysun/sakai,pushyamig/sakai,ktakacs/sakai,udayg/sakai,colczr/sakai,liubo404/sakai,introp-software/sakai,bzhouduke123/sakai,clhedrick/sakai,puramshetty/sakai,Fudan-University/sakai,kingmook/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,willkara/sakai,OpenCollabZA/sakai,introp-software/sakai,willkara/sakai,noondaysun/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,pushyamig/sakai,OpenCollabZA/sakai,zqian/sakai,bkirschn/sakai,conder/sakai,noondaysun/sakai,liubo404/sakai,colczr/sakai,noondaysun/sakai,puramshetty/sakai,bkirschn/sakai,whumph/sakai,lorenamgUMU/sakai,bkirschn/sakai,bzhouduke123/sakai,surya-janani/sakai,rodriguezdevera/sakai,willkara/sakai,wfuedu/sakai,whumph/sakai,rodriguezdevera/sakai,clhedrick/sakai,introp-software/sakai,duke-compsci290-spring2016/sakai,kingmook/sakai,Fudan-University/sakai,ktakacs/sakai,kwedoff1/sakai,udayg/sakai,hackbuteer59/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,whumph/sakai,ouit0408/sakai,kingmook/sakai,udayg/sakai,wfuedu/sakai,clhedrick/sakai,zqian/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,OpenCollabZA/sakai,ouit0408/sakai,joserabal/sakai,wfuedu/sakai,rodriguezdevera/sakai,tl-its-umich-edu/sakai,OpenCollabZA/sakai,lorenamgUMU/sakai,ouit0408/sakai,whumph/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,frasese/sakai,frasese/sakai,kingmook/sakai,zqian/sakai,zqian/sakai,Fudan-University/sakai,frasese/sakai,puramshetty/sakai,udayg/sakai,OpenCollabZA/sakai,tl-its-umich-edu/sakai,joserabal/sakai,wfuedu/sakai,whumph/sakai,joserabal/sakai,conder/sakai,hackbuteer59/sakai,kwedoff1/sakai,pushyamig/sakai,noondaysun/sakai,bkirschn/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,whumph/sakai,hackbuteer59/sakai,Fudan-University/sakai,kingmook/sakai,puramshetty/sakai,willkara/sakai,liubo404/sakai,bzhouduke123/sakai,surya-janani/sakai,introp-software/sakai,joserabal/sakai,conder/sakai,hackbuteer59/sakai,liubo404/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,puramshetty/sakai,wfuedu/sakai,zqian/sakai,clhedrick/sakai,clhedrick/sakai,willkara/sakai,conder/sakai,puramshetty/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,introp-software/sakai,surya-janani/sakai,frasese/sakai,kingmook/sakai,wfuedu/sakai,colczr/sakai,surya-janani/sakai,noondaysun/sakai,conder/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,buckett/sakai-gitflow,ktakacs/sakai,Fudan-University/sakai,hackbuteer59/sakai,liubo404/sakai,colczr/sakai,OpenCollabZA/sakai,whumph/sakai,tl-its-umich-edu/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.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.assignment.tool;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.Collator;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import java.util.GregorianCalendar;
import java.nio.channels.*;
import java.nio.*;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.announcement.api.AnnouncementChannel;
import org.sakaiproject.announcement.api.AnnouncementMessage;
import org.sakaiproject.announcement.api.AnnouncementMessageEdit;
import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit;
import org.sakaiproject.announcement.api.AnnouncementService;
import org.sakaiproject.assignment.api.Assignment;
import org.sakaiproject.assignment.api.AssignmentConstants;
import org.sakaiproject.assignment.api.AssignmentContent;
import org.sakaiproject.assignment.api.AssignmentContentEdit;
import org.sakaiproject.assignment.api.AssignmentEdit;
import org.sakaiproject.assignment.api.AssignmentSubmission;
import org.sakaiproject.assignment.api.AssignmentSubmissionEdit;
import org.sakaiproject.assignment.api.model.AssignmentAllPurposeItemAccess;
import org.sakaiproject.assignment.api.model.AssignmentModelAnswerItem;
import org.sakaiproject.assignment.api.model.AssignmentNoteItem;
import org.sakaiproject.assignment.api.model.AssignmentAllPurposeItem;
import org.sakaiproject.assignment.api.model.AssignmentSupplementItemAttachment;
import org.sakaiproject.assignment.api.model.AssignmentSupplementItemService;
import org.sakaiproject.assignment.api.model.AssignmentSupplementItemWithAttachment;
import org.sakaiproject.assignment.cover.AssignmentService;
import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer;
import org.sakaiproject.taggable.api.TaggingHelperInfo;
import org.sakaiproject.taggable.api.TaggingManager;
import org.sakaiproject.taggable.api.TaggingProvider;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarEventEdit;
import org.sakaiproject.calendar.api.CalendarService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.ContentTypeImageService;
import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.content.api.ResourceTypeRegistry;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException;
import org.sakaiproject.service.gradebook.shared.CategoryDefinition;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService;
import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException;
import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException;
import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.RequestFilter;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SortedIterator;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.thread_local.cover.ThreadLocalManager;
import org.sakaiproject.contentreview.service.ContentReviewService;
/**
* <p>
* AssignmentAction is the action class for the assignment tool.
* </p>
*/
public class AssignmentAction extends PagedResourceActionII
{
private static ResourceLoader rb = new ResourceLoader("assignment");
/** Our logger. */
private static Log M_log = LogFactory.getLog(AssignmentAction.class);
private static final String ASSIGNMENT_TOOL_ID = "sakai.assignment.grades";
private static final Boolean allowReviewService = ServerConfigurationService.getBoolean("assignment.useContentReview", false);
/** Is the review service available? */
private static final String ALLOW_REVIEW_SERVICE = "allow_review_service";
private static final String NEW_ASSIGNMENT_USE_REVIEW_SERVICE = "new_assignment_use_review_service";
private static final String NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW = "new_assignment_allow_student_view";
/** The attachments */
private static final String ATTACHMENTS = "Assignment.attachments";
private static final String ATTACHMENTS_FOR = "Assignment.attachments_for";
/** The content type image lookup service in the State. */
private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service";
/** The calendar service in the State. */
private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service";
/** The announcement service in the State. */
private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service";
/** The calendar object */
private static final String CALENDAR = "calendar";
/** The calendar tool */
private static final String CALENDAR_TOOL_EXIST = "calendar_tool_exisit";
/** The announcement tool */
private static final String ANNOUNCEMENT_TOOL_EXIST = "announcement_tool_exist";
/** The announcement channel */
private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel";
/** The state mode */
private static final String STATE_MODE = "Assignment.mode";
/** The context string */
private static final String STATE_CONTEXT_STRING = "Assignment.context_string";
/** The user */
private static final String STATE_USER = "Assignment.user";
// SECTION MOD
/** Used to keep track of the section info not currently being used. */
private static final String STATE_SECTION_STRING = "Assignment.section_string";
/** **************************** sort assignment ********************** */
/** state sort * */
private static final String SORTED_BY = "Assignment.sorted_by";
/** state sort ascendingly * */
private static final String SORTED_ASC = "Assignment.sorted_asc";
/** default sorting */
private static final String SORTED_BY_DEFAULT = "default";
/** sort by assignment title */
private static final String SORTED_BY_TITLE = "title";
/** sort by assignment section */
private static final String SORTED_BY_SECTION = "section";
/** sort by assignment due date */
private static final String SORTED_BY_DUEDATE = "duedate";
/** sort by assignment open date */
private static final String SORTED_BY_OPENDATE = "opendate";
/** sort by assignment status */
private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status";
/** sort by assignment submission status */
private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status";
/** sort by assignment number of submissions */
private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions";
/** sort by assignment number of ungraded submissions */
private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded";
/** sort by assignment submission grade */
private static final String SORTED_BY_GRADE = "grade";
/** sort by assignment maximun grade available */
private static final String SORTED_BY_MAX_GRADE = "max_grade";
/** sort by assignment range */
private static final String SORTED_BY_FOR = "for";
/** sort by group title */
private static final String SORTED_BY_GROUP_TITLE = "group_title";
/** sort by group description */
private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description";
/** *************************** sort submission in instructor grade view *********************** */
/** state sort submission* */
private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by";
/** state sort submission ascendingly * */
private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc";
/** state sort submission by submitters last name * */
private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname";
/** state sort submission by submit time * */
private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time";
/** state sort submission by submission status * */
private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status";
/** state sort submission by submission grade * */
private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade";
/** state sort submission by submission released * */
private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released";
/** state sort submissuib by content review score **/
private static final String SORTED_GRADE_SUBMISSION_CONTENTREVIEW = "sorted_grade_submission_by_contentreview";
/** *************************** sort submission *********************** */
/** state sort submission* */
private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by";
/** state sort submission ascendingly * */
private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc";
/** state sort submission by submitters last name * */
private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname";
/** state sort submission by submit time * */
private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time";
/** state sort submission by submission grade * */
private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade";
/** state sort submission by submission status * */
private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status";
/** state sort submission by submission released * */
private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released";
/** state sort submission by assignment title */
private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment";
/** state sort submission by max grade */
private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade";
/*********************** Sort by user sort name *****************************************/
private static final String SORTED_USER_BY_SORTNAME = "sorted_user_by_sortname";
/** ******************** student's view assignment submission ****************************** */
/** the assignment object been viewing * */
private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference";
/** the submission text to the assignment * */
private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text";
/** the submission answer to Honor Pledge * */
private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes";
/** ***************** student's preview of submission *************************** */
/** the assignment id * */
private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference";
/** the submission text * */
private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text";
/** the submission honor pledge answer * */
private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes";
/** the submission attachments * */
private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments";
/** the flag indicate whether the to show the student view or not */
private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag";
/** the flag indicate whether the to show the assignment info or not */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag";
/** the assignment id */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id";
/** the assignment content id */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id";
/** ************** view assignment ***************************************** */
/** the hide assignment flag in the view assignment page * */
private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag";
/** the hide student view flag in the view assignment page * */
private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag";
/** ******************* instructor's view assignment ***************************** */
private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id";
/** ******************* instructor's edit assignment ***************************** */
private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id";
/** ******************* instructor's delete assignment ids ***************************** */
private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids";
/** ******************* flags controls the grade assignment page layout ******************* */
private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag";
private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag";
private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade";
/** ******************* instructor's grade submission ***************************** */
private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id";
private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id";
private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment";
private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text";
private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment";
private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade";
private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag";
private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit";
private static final String GRADE_SUBMISSION_DONE = "grade_submission_done";
/** ******************* instructor's export assignment ***************************** */
private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref";
/**
* Is review service enabled?
*/
private static final String ENABLE_REVIEW_SERVICE = "enable_review_service";
private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id";
/** ****************** instructor's new assignment ****************************** */
private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title";
// assignment order for default view
private static final String NEW_ASSIGNMENT_ORDER = "new_assignment_order";
// open date
private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth";
private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday";
private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear";
private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour";
private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin";
private static final String NEW_ASSIGNMENT_OPENAMPM = "new_assignment_openampm";
// due date
private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth";
private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday";
private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear";
private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour";
private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin";
private static final String NEW_ASSIGNMENT_DUEAMPM = "new_assignment_dueampm";
private static final String NEW_ASSIGNMENT_PAST_DUE_DATE = "new_assignment_past_due_date";
// close date
private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate";
private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth";
private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday";
private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear";
private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour";
private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin";
private static final String NEW_ASSIGNMENT_CLOSEAMPM = "new_assignment_closeampm";
private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment";
private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section";
private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type";
private static final String NEW_ASSIGNMENT_CATEGORY = "new_assignment_category";
private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type";
private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points";
private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions";
private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled";
private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced";
private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge";
private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus";
private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty";
private static final String NEW_ASSIGNMENT_ADD_TO_GRADEBOOK = "new_assignment_add_to_gradebook";
private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range";
private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups";
private static final String NEW_ASSIGNMENT_PAST_CLOSE_DATE = "new_assignment_past_close_date";
/*************************** assignment model answer attributes *************************/
private static final String NEW_ASSIGNMENT_MODEL_ANSWER = "new_assignment_model_answer";
private static final String NEW_ASSIGNMENT_MODEL_ANSWER_TEXT = "new_assignment_model_answer_text";
private static final String NEW_ASSIGNMENT_MODEL_SHOW_TO_STUDENT = "new_assignment_model_answer_show_to_student";
private static final String NEW_ASSIGNMENT_MODEL_ANSWER_ATTACHMENT = "new_assignment_model_answer_attachment";
/**************************** assignment year range *************************/
private static final String NEW_ASSIGNMENT_YEAR_RANGE_FROM = "new_assignment_year_range_from";
private static final String NEW_ASSIGNMENT_YEAR_RANGE_TO = "new_assignment_year_range_to";
// submission level of resubmit due time
private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth";
private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay";
private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear";
private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour";
private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin";
private static final String ALLOW_RESUBMIT_CLOSEAMPM = "allow_resubmit_closeAMPM";
private static final String ATTACHMENTS_MODIFIED = "attachments_modified";
/** **************************** instructor's view student submission ***************** */
// the show/hide table based on member id
private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE";
/** **************************** student view grade submission id *********** */
private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id";
// alert for grade exceeds max grade setting
private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert";
/** **************************** modes *************************** */
/** The list view of assignments */
private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template
/** The student view of an assignment submission */
private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission";
/** The student view of an assignment submission confirmation */
private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation";
/** The student preview of an assignment submission */
private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission";
/** The student view of graded submission */
private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade";
/** The student view of graded submission */
private static final String MODE_STUDENT_VIEW_GRADE_PRIVATE = "Assignment.mode_student_view_grade_private";
/** The student view of assignments */
private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment";
/** The instructor view of creating a new assignment or editing an existing one */
private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment";
/** The instructor view to reorder assignments */
private static final String MODE_INSTRUCTOR_REORDER_ASSIGNMENT = "reorder";
/** The instructor view to delete an assignment */
private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment";
/** The instructor view to grade an assignment */
private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment";
/** The instructor view to grade a submission */
private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission";
/** The instructor view of preview grading a submission */
private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission";
/** The instructor preview of one assignment */
private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments";
/** The instructor view of one assignment */
private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments";
/** The instructor view to list students of an assignment */
private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template
/** The instructor view of assignment submission report */
private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template
/** The instructor view of download all file */
private static final String MODE_INSTRUCTOR_DOWNLOAD_ALL = "downloadAll";
/** The instructor view of uploading all from archive file */
private static final String MODE_INSTRUCTOR_UPLOAD_ALL = "uploadAll";
/** The student view of assignment submission report */
private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template
/** ************************* vm names ************************** */
/** The list view of assignments */
private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments";
/** The student view of assignment */
private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment";
/** The student view of showing an assignment submission */
private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission";
/** The student view of an assignment submission confirmation */
private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation";
/** The student preview an assignment submission */
private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission";
/** The student view of graded submission */
private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade";
/** The instructor view to create a new assignment or edit an existing one */
private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment";
/** The instructor view to reorder the default assignments */
private static final String TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT = "_instructor_reorder_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission";
/** The instructor preview to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission";
/** The instructor view to grade the assignment */
private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions";
/** The instructor preview of assignment */
private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment";
/** The instructor view of assignment */
private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions";
/** The instructor view to assignment submission report */
private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions";
/** The instructor view to upload all information from archive file */
private static final String TEMPLATE_INSTRUCTOR_UPLOAD_ALL = "_instructor_uploadAll";
/** The opening mark comment */
private static final String COMMENT_OPEN = "{{";
/** The closing mark for comment */
private static final String COMMENT_CLOSE = "}}";
/** The selected view */
private static final String STATE_SELECTED_VIEW = "state_selected_view";
/** The configuration choice of with grading option or not */
private static final String WITH_GRADES = "with_grades";
/** The configuration choice of showing or hiding the number of submissions column */
private static final String SHOW_NUMBER_SUBMISSION_COLUMN = "showNumSubmissionColumn";
/** The alert flag when doing global navigation from improper mode */
private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation";
/** The total list item before paging */
private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items";
/** is current user allowed to grade assignment? */
private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission";
/** property for previous feedback attachments **/
private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments";
/** the user and submission list for list of submissions page */
private static final String USER_SUBMISSIONS = "user_submissions";
/** ************************* Taggable constants ************************** */
/** identifier of tagging provider that will provide the appropriate helper */
private static final String PROVIDER_ID = "providerId";
/** Reference to an activity */
private static final String ACTIVITY_REF = "activityRef";
/** Reference to an item */
private static final String ITEM_REF = "itemRef";
/** session attribute for list of decorated tagging providers */
private static final String PROVIDER_LIST = "providerList";
// whether the choice of emails instructor submission notification is available in the installation
private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications";
// default for whether or how the instructor receive submission notification emails, none(default)|each|digest
private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default";
// name for release grade notification
private static final String ASSIGNMENT_RELEASEGRADE_NOTIFICATION = "assignment.releasegrade.notification";
/****************************** Upload all screen ***************************/
private static final String UPLOAD_ALL_HAS_SUBMISSION_TEXT = "upload_all_has_submission_text";
private static final String UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT = "upload_all_has_submission_attachment";
private static final String UPLOAD_ALL_HAS_GRADEFILE = "upload_all_has_gradefile";
private static final String UPLOAD_ALL_HAS_COMMENTS= "upload_all_has_comments";
private static final String UPLOAD_ALL_HAS_FEEDBACK_TEXT= "upload_all_has_feedback_text";
private static final String UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT = "upload_all_has_feedback_attachment";
private static final String UPLOAD_ALL_RELEASE_GRADES = "upload_all_release_grades";
// this is to track whether the site has multiple assignment, hence if true, show the reorder link
private static final String HAS_MULTIPLE_ASSIGNMENTS = "has_multiple_assignments";
// view all or grouped submission list
private static final String VIEW_SUBMISSION_LIST_OPTION = "view_submission_list_option";
private ContentHostingService m_contentHostingService = null;
private EventTrackingService m_eventTrackingService = null;
private NotificationService m_notificationService = null;
/********************** Supplement item ************************/
private AssignmentSupplementItemService m_assignmentSupplementItemService = null;
/******** Model Answer ************/
private static final String MODELANSWER = "modelAnswer";
private static final String MODELANSWER_TEXT = "modelAnswer.text";
private static final String MODELANSWER_SHOWTO = "modelAnswer.showTo";
private static final String MODELANSWER_ATTACHMENTS = "modelanswer_attachments";
private static final String MODELANSWER_TO_DELETE = "modelanswer.toDelete";
/******** Note ***********/
private static final String NOTE = "note";
private static final String NOTE_TEXT = "note.text";
private static final String NOTE_SHAREWITH = "note.shareWith";
private static final String NOTE_TO_DELETE = "note.toDelete";
/******** AllPurpose *******/
private static final String ALLPURPOSE = "allPurpose";
private static final String ALLPURPOSE_TITLE = "allPurpose.title";
private static final String ALLPURPOSE_TEXT = "allPurpose.text";
private static final String ALLPURPOSE_HIDE = "allPurpose.hide";
private static final String ALLPURPOSE_SHOW_FROM = "allPurpose.show.from";
private static final String ALLPURPOSE_SHOW_TO = "allPurpose.show.to";
private static final String ALLPURPOSE_RELEASE_DATE = "allPurpose.releaseDate";
private static final String ALLPURPOSE_RETRACT_DATE= "allPurpose.retractDate";
private static final String ALLPURPOSE_ACCESS = "allPurpose.access";
private static final String ALLPURPOSE_ATTACHMENTS = "allPurpose_attachments";
private static final String ALLPURPOSE_RELEASE_YEAR = "allPurpose.releaseYear";
private static final String ALLPURPOSE_RELEASE_MONTH = "allPurpose.releaseMonth";
private static final String ALLPURPOSE_RELEASE_DAY = "allPurpose.releaseDay";
private static final String ALLPURPOSE_RELEASE_HOUR = "allPurpose.releaseHour";
private static final String ALLPURPOSE_RELEASE_MIN = "allPurpose.releaseMin";
private static final String ALLPURPOSE_RELEASE_AMPM = "allPurpose.releaseAMPM";
private static final String ALLPURPOSE_RETRACT_YEAR = "allPurpose.retractYear";
private static final String ALLPURPOSE_RETRACT_MONTH = "allPurpose.retractMonth";
private static final String ALLPURPOSE_RETRACT_DAY = "allPurpose.retractDay";
private static final String ALLPURPOSE_RETRACT_HOUR = "allPurpose.retractHour";
private static final String ALLPURPOSE_RETRACT_MIN = "allPurpose.retractMin";
private static final String ALLPURPOSE_RETRACT_AMPM = "allPurpose.retractAMPM";
private static final String ALLPURPOSE_TO_DELETE = "allPurpose.toDelete";
private static final String SHOW_ALLOW_RESUBMISSION = "show_allow_resubmission";
private static final int INPUT_BUFFER_SIZE = 102400;
/**
* central place for dispatching the build routines based on the state name
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
String template = null;
context.put("tlang", rb);
context.put("dateFormat", getDateFormatString());
context.put("cheffeedbackhelper", this);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// allow add assignment?
boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString);
context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment));
Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION);
// allow update site?
context.put("allowUpdateSite", Boolean
.valueOf(SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))));
// allow all.groups?
boolean allowAllGroups = AssignmentService.allowAllGroups(contextString);
context.put("allowAllGroups", Boolean.valueOf(allowAllGroups));
//Is the review service allowed?
Site s = null;
try {
s = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (IdUnusedException iue) {
M_log.warn(this + ":buildMainPanelContext: Site not found!" + iue.getMessage());
}
// Check whether content review service is enabled, present and enabled for this site
getContentReviewService();
context.put("allowReviewService", allowReviewService && contentReviewService != null && contentReviewService.isSiteAcceptable(s));
if (allowReviewService && contentReviewService != null && contentReviewService.isSiteAcceptable(s)) {
//put the review service stings in context
String reviewServiceName = contentReviewService.getServiceName();
String reviewServiceTitle = rb.getFormattedMessage("review.title", new Object[]{reviewServiceName});
String reviewServiceUse = rb.getFormattedMessage("review.use", new Object[]{reviewServiceName});
context.put("reviewServiceName", reviewServiceTitle);
context.put("reviewServiceUse", reviewServiceUse);
}
// grading option
context.put("withGrade", state.getAttribute(WITH_GRADES));
// the grade type table
context.put("gradeTypeTable", gradeTypeTable());
String mode = (String) state.getAttribute(STATE_MODE);
if (!MODE_LIST_ASSIGNMENTS.equals(mode))
{
// allow grade assignment?
if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null)
{
state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE);
}
context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION));
}
if (MODE_LIST_ASSIGNMENTS.equals(mode))
{
// build the context for the student assignment view
template = build_list_assignments_context(portlet, context, data, state);
}
else if (MODE_STUDENT_VIEW_ASSIGNMENT.equals(mode))
{
// the student view of assignment
template = build_student_view_assignment_context(portlet, context, data, state);
}
else if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for showing one assignment submission
template = build_student_view_submission_context(portlet, context, data, state);
}
else if (MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION.equals(mode))
{
// build the context for showing one assignment submission confirmation
template = build_student_view_submission_confirmation_context(portlet, context, data, state);
}
else if (MODE_STUDENT_PREVIEW_SUBMISSION.equals(mode))
{
// build the context for showing one assignment submission
template = build_student_preview_submission_context(portlet, context, data, state);
}
else if (MODE_STUDENT_VIEW_GRADE.equals(mode) || MODE_STUDENT_VIEW_GRADE_PRIVATE.equals(mode))
{
// disable auto-updates while leaving the list view
justDelivered(state);
if(MODE_STUDENT_VIEW_GRADE_PRIVATE.equals(mode)){
context.put("privateView", true);
}
// build the context for showing one graded submission
template = build_student_view_grade_context(portlet, context, data, state);
}
else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode))
{
// allow add assignment?
boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString);
context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment));
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's create new assignment view
template = build_instructor_new_edit_assignment_context(portlet, context, data, state);
}
else if (MODE_INSTRUCTOR_DELETE_ASSIGNMENT.equals(mode))
{
if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null)
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's delete assignment
template = build_instructor_delete_assignment_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode))
{
if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's grade assignment
template = build_instructor_grade_assignment_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode))
{
if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's grade submission
template = build_instructor_grade_submission_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's preview grade submission
template = build_instructor_preview_grade_submission_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode))
{
// build the context for preview one assignment
template = build_instructor_preview_assignment_context(portlet, context, data, state);
}
else if (MODE_INSTRUCTOR_VIEW_ASSIGNMENT.equals(mode))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for view one assignment
template = build_instructor_view_assignment_context(portlet, context, data, state);
}
else if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's create new assignment view
template = build_instructor_view_students_assignment_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of report submissions
template = build_instructor_report_submissions(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_DOWNLOAD_ALL.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of uploading all info from archive file
template = build_instructor_download_upload_all(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_UPLOAD_ALL.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of uploading all info from archive file
template = build_instructor_download_upload_all(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's create new assignment view
template = build_instructor_reorder_assignment_context(portlet, context, data, state);
}
if (template == null)
{
// default to student list view
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
template = build_list_assignments_context(portlet, context, data, state);
}
// this is a check for seeing if there are any assignments. The check is used to see if we display a Reorder link in the vm files
if (state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS) != null)
{
context.put("assignmentscheck", state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS));
}
return template;
} // buildNormalContext
/**
* local function for getting assignment object
* @param assignmentId
* @param callingFunctionName
* @param state
* @return
*/
private Assignment getAssignment(String assignmentId, String callingFunctionName, SessionState state)
{
Assignment rv = null;
try
{
rv = AssignmentService.getAssignment(assignmentId);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentId}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("youarenot_viewAssignment", new Object[]{assignmentId}));
}
return rv;
}
/**
* local function for getting assignment submission object
* @param submissionId
* @param callingFunctionName
* @param state
* @return
*/
private AssignmentSubmission getSubmission(String submissionId, String callingFunctionName, SessionState state)
{
AssignmentSubmission rv = null;
try
{
rv = AssignmentService.getSubmission(submissionId);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("cannotfin_submission", new Object[]{submissionId}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission", new Object[]{submissionId}));
}
return rv;
}
/**
* local function for editing assignment submission object
* @param submissionId
* @param callingFunctionName
* @param state
* @return
*/
private AssignmentSubmissionEdit editSubmission(String submissionId, String callingFunctionName, SessionState state)
{
AssignmentSubmissionEdit rv = null;
try
{
rv = AssignmentService.editSubmission(submissionId);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("cannotfin_submission", new Object[]{submissionId}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("youarenot_editSubmission", new Object[]{submissionId}));
}
catch (InUseException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("somelsis_submission", new Object[]{submissionId}));
}
return rv;
}
/**
* local function for editing assignment object
* @param assignmentId
* @param callingFunctionName
* @param state
* @param allowToAdd
* @return
*/
private AssignmentEdit editAssignment(String assignmentId, String callingFunctionName, SessionState state, boolean allowAdd)
{
AssignmentEdit rv = null;
if (assignmentId.length() == 0 && allowAdd)
{
// create a new assignment
try
{
rv = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot_addAssignment"));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage());
}
}
else
{
try
{
rv = AssignmentService.editAssignment(assignmentId);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentId}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("youarenot_editAssignment", new Object[]{assignmentId}));
}
catch (InUseException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("somelsis_assignment", new Object[]{assignmentId}));
}
} // if-else
return rv;
}
/**
* local function for getting assignment submission object
* @param submissionId
* @param callingFunctionName
* @param state
* @return
*/
private AssignmentSubmission getSubmission(String assignmentRef, User user, String callingFunctionName, SessionState state)
{
AssignmentSubmission rv = null;
try
{
rv = AssignmentService.getSubmission(assignmentRef, user);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":build_student_view_submission " + e.getMessage() + " " + assignmentRef + " " + user.getId());
if (state != null)
addAlert(state, rb.getFormattedMessage("cannotfin_submission_1", new Object[]{assignmentRef, user.getId()}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentRef + " " + user.getId());
if (state != null)
addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission_1", new Object[]{assignmentRef, user.getId()}));
}
return rv;
}
/**
* build the student view of showing an assignment submission
*/
protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("context", contextString);
User user = (User) state.getAttribute(STATE_USER);
String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
AssignmentSubmission s = null;
Assignment assignment = getAssignment(currentAssignmentReference, "build_student_view_submission_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit(contextString, assignment)));
if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
context.put("nonElectronicType", Boolean.TRUE);
}
s = getSubmission(assignment.getReference(), user, "build_student_view_submission_context", state);
if (s != null)
{
context.put("submission", s);
ResourceProperties p = s.getProperties();
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null)
{
context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT));
}
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null)
{
context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT));
}
if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null)
{
context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p));
}
// put the resubmit information into context
assignment_resubmission_option_into_context(context, state);
}
// can the student view model answer or not
canViewAssignmentIntoContext(context, assignment, s);
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
// name value pairs for the vm
context.put("name_submission_text", VIEW_SUBMISSION_TEXT);
context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT));
context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES);
context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES));
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("currentTime", TimeService.newTime());
boolean allowSubmit = AssignmentService.allowAddSubmission((String) state.getAttribute(STATE_CONTEXT_STRING));
if (!allowSubmit)
{
addAlert(state, rb.getString("not_allowed_to_submit"));
}
context.put("allowSubmit", Boolean.valueOf(allowSubmit));
// put supplement item into context
supplementItemIntoContext(state, context, assignment, s);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_SUBMISSION;
} // build_student_view_submission_context
/**
* build the student view of showing an assignment submission confirmation
*/
protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("context", contextString);
// get user information
User user = (User) state.getAttribute(STATE_USER);
context.put("user_name", user.getDisplayName());
context.put("user_id", user.getDisplayId());
if (StringUtil.trimToNull(user.getEmail()) != null)
context.put("user_email", user.getEmail());
// get site information
try
{
// get current site
Site site = SiteService.getSite(contextString);
context.put("site_title", site.getTitle());
}
catch (Exception ignore)
{
M_log.warn(this + ":buildStudentViewSubmission " + ignore.getMessage() + " siteId= " + contextString);
}
// get assignment and submission information
String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment currentAssignment = getAssignment(currentAssignmentReference, "build_student_view_submission_confirmation_context", state);
if (currentAssignment != null)
{
context.put("assignment_title", currentAssignment.getTitle());
// differenciate submission type
int submissionType = currentAssignment.getContent().getTypeOfSubmission();
if (submissionType == Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION || submissionType == Assignment.SINGLE_ATTACHMENT_SUBMISSION)
{
context.put("attachmentSubmissionOnly", Boolean.TRUE);
}
else
{
context.put("attachmentSubmissionOnly", Boolean.FALSE);
}
if (submissionType == Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION)
{
context.put("textSubmissionOnly", Boolean.TRUE);
}
else
{
context.put("textSubmissionOnly", Boolean.FALSE);
}
AssignmentSubmission s = getSubmission(currentAssignmentReference, user, "build_student_view_submission_confirmation_context",state);
if (s != null)
{
context.put("submitted", Boolean.valueOf(s.getSubmitted()));
context.put("submission_id", s.getId());
if (s.getTimeSubmitted() != null)
{
context.put("submit_time", s.getTimeSubmitted().toStringLocalFull());
}
List attachments = s.getSubmittedAttachments();
if (attachments != null && attachments.size()>0)
{
context.put("submit_attachments", s.getSubmittedAttachments());
}
context.put("submit_text", StringUtil.trimToNull(s.getSubmittedText()));
context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true)));
}
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION;
} // build_student_view_submission_confirmation_context
/**
* build the student view of assignment
*/
protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("context", state.getAttribute(STATE_CONTEXT_STRING));
String aReference = (String) state.getAttribute(VIEW_ASSIGNMENT_ID);
User user = (User) state.getAttribute(STATE_USER);
AssignmentSubmission submission = null;
Assignment assignment = getAssignment(aReference, "build_student_view_assignment_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
// put creator information into context
putCreatorIntoContext(context, assignment);
submission = getSubmission(aReference, user, "build_student_view_assignment_context", state);
context.put("submission", submission);
// can the student view model answer or not
canViewAssignmentIntoContext(context, assignment, submission);
// put resubmit information into context
assignment_resubmission_option_into_context(context, state);
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("userDirectoryService", UserDirectoryService.getInstance());
// put supplement item into context
supplementItemIntoContext(state, context, assignment, submission);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT;
} // build_student_view_submission_context
/**
* build the student preview of showing an assignment submission
*/
protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
User user = (User) state.getAttribute(STATE_USER);
String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment assignment = getAssignment(aReference, "build_student_preview_submission_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
AssignmentSubmission submission = getSubmission(aReference, user, "build_student_preview_submission_context", state);
context.put("submission", submission);
context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit((String) state.getAttribute(STATE_CONTEXT_STRING), assignment)));
// can the student view model answer or not
canViewAssignmentIntoContext(context, assignment, submission);
// put the resubmit information into context
assignment_resubmission_option_into_context(context, state);
}
context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT));
context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES));
context.put("attachments", state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION;
} // build_student_preview_submission_context
private void canViewAssignmentIntoContext(Context context,
Assignment assignment, AssignmentSubmission submission) {
boolean canViewModelAnswer = m_assignmentSupplementItemService.canViewModelAnswer(assignment, submission);
context.put("allowViewModelAnswer", Boolean.valueOf(canViewModelAnswer));
if (canViewModelAnswer)
{
context.put("modelAnswer", m_assignmentSupplementItemService.getModelAnswer(assignment.getId()));
}
}
/**
* build the student view of showing a graded submission
*/
protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
Session session = SessionManager.getCurrentSession();
SecurityAdvisor contentAdvisor = (SecurityAdvisor)session.getAttribute("assignment.content.security.advisor");
String decoratedContentWrapper = (String)session.getAttribute("assignment.content.decoration.wrapper");
session.removeAttribute("assignment.content.decoration.wrapper");
String[] contentRefs = (String[])session.getAttribute("assignment.content.decoration.wrapper.refs");
session.removeAttribute("assignment.content.decoration.wrapper.refs");
if (contentAdvisor != null && contentRefs != null) {
SecurityService.pushAdvisor(contentAdvisor);
Map urlMap = new HashMap();
for (String refStr:contentRefs) {
Reference ref = EntityManager.newReference(refStr);
String url = ref.getUrl();
urlMap.put(url, url.replaceFirst("access/content", "access/" + decoratedContentWrapper + "/content"));
}
context.put("decoratedUrlMap", urlMap);
}
SecurityAdvisor asgnAdvisor = (SecurityAdvisor)session.getAttribute("assignment.security.advisor");
if (asgnAdvisor != null) {
SecurityService.pushAdvisor(asgnAdvisor);
session.removeAttribute("assignment.security.advisor");
}
AssignmentSubmission submission = null;
Assignment assignment = null;
String submissionId = (String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID);
submission = getSubmission(submissionId, "build_student_view_grade_context", state);
if (submission != null)
{
assignment = submission.getAssignment();
context.put("assignment", assignment);
if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
context.put("nonElectronicType", Boolean.TRUE);
}
context.put("submission", submission);
// can the student view model answer or not
canViewAssignmentIntoContext(context, assignment, submission);
SecurityService.popAdvisor();
//should be the asgnAdvisor that gets popped
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && submission != null)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
List<DecoratedTaggingProvider> providers = addProviders(context, state);
List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>();
for (DecoratedTaggingProvider provider : providers)
{
TaggingHelperInfo helper = provider.getProvider()
.getItemHelperInfo(
assignmentActivityProducer.getItem(
submission,
UserDirectoryService.getCurrentUser()
.getId()).getReference());
if (helper != null)
{
itemHelpers.add(helper);
}
}
addItem(context, submission, UserDirectoryService.getCurrentUser().getId());
addActivity(context, submission.getAssignment());
context.put("itemHelpers", itemHelpers);
context.put("taggable", Boolean.valueOf(true));
}
// put supplement item into context
supplementItemIntoContext(state, context, assignment, submission);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_GRADE;
} // build_student_view_grade_context
/**
* build the view of assignments list
*/
protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable())
{
context.put("producer", ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"));
context.put("providers", taggingManager.getProviders());
context.put("taggable", Boolean.valueOf(true));
}
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("contextString", contextString);
context.put("user", state.getAttribute(STATE_USER));
context.put("service", AssignmentService.getInstance());
context.put("TimeService", TimeService.getInstance());
context.put("LongObject", Long.valueOf(TimeService.newTime().getTime()));
context.put("currentTime", TimeService.newTime());
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
// clean sort criteria
if (SORTED_BY_GROUP_TITLE.equals(sortedBy) || SORTED_BY_GROUP_DESCRIPTION.equals(sortedBy))
{
sortedBy = SORTED_BY_DUEDATE;
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sortedBy);
state.setAttribute(SORTED_ASC, sortedAsc);
}
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
if (state.getAttribute(STATE_SELECTED_VIEW) != null)
{
context.put("view", state.getAttribute(STATE_SELECTED_VIEW));
}
List assignments = prepPage(state);
context.put("assignments", assignments.iterator());
// allow get assignment
context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString)));
// test whether user user can grade at least one assignment
// and update the state variable.
boolean allowGradeSubmission = false;
for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); )
{
if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference()))
{
allowGradeSubmission = true;
}
}
state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.valueOf(allowGradeSubmission));
context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION));
// allow remove assignment?
boolean allowRemoveAssignment = false;
for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); )
{
if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference()))
{
allowRemoveAssignment = true;
}
}
context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment));
add2ndToolbarFields(data, context);
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
justDelivered(state);
pagingInfoToContext(state, context);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite(contextString);
context.put("site", site);
// any group in the site?
Collection groups = site.getGroups();
context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE);
// add active user list
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString));
if (realm != null)
{
context.put("activeUserIds", realm.getUsers());
}
}
catch (Exception ignore)
{
M_log.warn(this + ":build_list_assignments_context " + ignore.getMessage());
M_log.warn(this + ignore.getMessage() + " siteId= " + contextString);
}
boolean allowSubmit = AssignmentService.allowAddSubmission(contextString);
context.put("allowSubmit", Boolean.valueOf(allowSubmit));
// related to resubmit settings
context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
// the type int for non-electronic submission
context.put("typeNonElectronic", Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION));
// show or hide the number of submission column
context.put(SHOW_NUMBER_SUBMISSION_COLUMN, state.getAttribute(SHOW_NUMBER_SUBMISSION_COLUMN));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_LIST_ASSIGNMENTS;
} // build_list_assignments_context
private HashSet<String> getSubmittersIdSet(List submissions)
{
HashSet<String> rv = new HashSet<String>();
for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext();)
{
List submitterIds = ((AssignmentSubmission) iSubmissions.next()).getSubmitterIds();
if (submitterIds != null && submitterIds.size() > 0)
{
rv.add((String) submitterIds.get(0));
}
}
return rv;
}
private HashSet<String> getAllowAddSubmissionUsersIdSet(List users)
{
HashSet<String> rv = new HashSet<String>();
for (Iterator iUsers=users.iterator(); iUsers.hasNext();)
{
rv.add(((User) iUsers.next()).getId());
}
return rv;
}
/**
* build the instructor view of creating a new assignment or editing an existing one
*/
protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
// is the assignment an new assignment
String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID);
if (assignmentId != null)
{
Assignment a = getAssignment(assignmentId, "build_instructor_new_edit_assignment_context", state);
if (a != null)
{
context.put("assignment", a);
}
}
// set up context variables
setAssignmentFormContext(state, context);
context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS));
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT;
} // build_instructor_new_assignment_context
protected void setAssignmentFormContext(SessionState state, Context context)
{
// put the names and values into vm file
context.put("name_UseReviewService", NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
context.put("name_AllowStudentView", NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW);
context.put("name_title", NEW_ASSIGNMENT_TITLE);
context.put("name_order", NEW_ASSIGNMENT_ORDER);
// set open time context variables
putTimePropertiesInContext(context, state, "Open", NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM);
// set due time context variables
putTimePropertiesInContext(context, state, "Due", NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM);
context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE);
// set close time context variables
putTimePropertiesInContext(context, state, "Close", NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM);
context.put("name_Section", NEW_ASSIGNMENT_SECTION);
context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE);
context.put("name_Category", NEW_ASSIGNMENT_CATEGORY);
context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE);
context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS);
context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION);
// do not show the choice when there is no Schedule tool yet
if (state.getAttribute(CALENDAR) != null)
context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
//don't show the choice when there is no Announcement tool yet
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null)
context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
// set the values
Assignment a = null;
String assignmentRef = (String) state.getAttribute(EDIT_ASSIGNMENT_ID);
if (assignmentRef != null)
{
a = getAssignment(assignmentRef, "setAssignmentFormContext", state);
}
// put the re-submission info into context
putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE));
context.put("value_position_order", state.getAttribute(NEW_ASSIGNMENT_ORDER));
context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE));
context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION));
context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE));
// information related to gradebook categories
putGradebookCategoryInfoIntoContext(state, context);
context.put("value_totalSubmissionTypes", Assignment.SUBMISSION_TYPES.length);
context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE));
// format to show one decimal place
String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
context.put("value_GradePoints", displayGrade(state, maxGrade));
context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION));
// Keep the use review service setting
context.put("value_UseReviewService", state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE));
context.put("value_AllowStudentView", state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW));
// don't show the choice when there is no Schedule tool yet
if (state.getAttribute(CALENDAR) != null)
context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
// don't show the choice when there is no Announcement tool yet
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null)
context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
if (s == null) s = "1";
context.put("value_CheckAddHonorPledge", s);
// put resubmission option into context
assignment_resubmission_option_into_context(context, state);
// get all available assignments from Gradebook tool except for those created fromcategoryTable
boolean gradebookExists = isGradebookDefined();
if (gradebookExists)
{
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
try
{
// get all assignments in Gradebook
List gradebookAssignments = g.getAssignments(gradebookUid);
List gradebookAssignmentsExceptSamigo = new Vector();
// filtering out those from Samigo
for (Iterator i=gradebookAssignments.iterator(); i.hasNext();)
{
org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next();
if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle()))
{
gradebookAssignmentsExceptSamigo.add(gAssignment);
}
}
context.put("gradebookAssignments", gradebookAssignmentsExceptSamigo);
if (StringUtil.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null)
{
state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
}
context.put("withGradebook", Boolean.TRUE);
// offer the gradebook integration choice only in the Assignments with Grading tool
boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue();
if (withGrade)
{
context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
}
context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO);
context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD);
context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE);
String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (associateGradebookAssignment != null)
{
context.put("associateGradebookAssignment", associateGradebookAssignment);
if (a != null)
{
context.put("noAddToGradebookChoice", Boolean.valueOf(associateGradebookAssignment.equals(a.getReference())));
}
}
}
catch (Exception e)
{
// not able to link to Gradebook
M_log.warn(this + "setAssignmentFormContext " + e.getMessage());
}
if (StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null)
{
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
}
}
context.put("monthTable", monthTable());
context.put("submissionTypeTable", submissionTypeTable());
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String range = StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_RANGE));
context.put("range", range != null?range:"site");
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
context.put("site", site);
}
catch (Exception ignore)
{
M_log.warn(this + ":setAssignmentFormContext " + ignore.getMessage());
}
if (AssignmentService.getAllowGroupAssignments())
{
Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString);
if (range == null)
{
if (AssignmentService.allowAddSiteAssignment(contextString))
{
// default to make site selection
context.put("range", "site");
}
else if (groupsAllowAddAssignment.size() > 0)
{
// to group otherwise
context.put("range", "groups");
}
}
// group list which user can add message to
if (groupsAllowAddAssignment.size() > 0)
{
String sort = (String) state.getAttribute(SORTED_BY);
String asc = (String) state.getAttribute(SORTED_ASC);
if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION)))
{
sort = SORTED_BY_GROUP_TITLE;
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sort);
state.setAttribute(SORTED_ASC, asc);
}
context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), new AssignmentComparator(state, sort, asc)));
context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS));
}
}
context.put("allowGroupAssignmentsInGradebook", Boolean.valueOf(AssignmentService.getAllowGroupAssignmentsInGradebook()));
// the notification email choices
// whether the choice of emails instructor submission notification is available in the installation
// system installation allowed assignment submission notification
boolean allowNotification = ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true);
if (allowNotification)
{
// whether current user can receive notification. If not, don't show the notification choices in the create/edit assignment page
allowNotification = AssignmentService.allowReceiveSubmissionNotification(contextString);
}
if (allowNotification)
{
context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS);
if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null)
{
// set the notification value using site default
// whether or how the instructor receive submission notification emails, none(default)|each|digest
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE));
}
context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
// the option values
context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE);
context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH);
context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST);
}
// release grade notification option
putReleaseGradeNotificationOptionIntoContext(state, context);
// the supplement information
// model answers
context.put("modelanswer", state.getAttribute(MODELANSWER) != null?Boolean.TRUE:Boolean.FALSE);
context.put("modelanswer_text", state.getAttribute(MODELANSWER_TEXT));
context.put("modelanswer_showto", state.getAttribute(MODELANSWER_SHOWTO));
// get attachment for model answer object
putSupplementItemAttachmentStateIntoContext(state, context, MODELANSWER_ATTACHMENTS);
// private notes
context.put("allowReadAssignmentNoteItem", m_assignmentSupplementItemService.canReadNoteItem(a, contextString));
context.put("allowEditAssignmentNoteItem", m_assignmentSupplementItemService.canEditNoteItem(a));
context.put("note", state.getAttribute(NOTE) != null?Boolean.TRUE:Boolean.FALSE);
context.put("note_text", state.getAttribute(NOTE_TEXT));
context.put("note_to", state.getAttribute(NOTE_SHAREWITH) != null?state.getAttribute(NOTE_SHAREWITH):String.valueOf(0));
// all purpose item
context.put("allPurpose", state.getAttribute(ALLPURPOSE) != null?Boolean.TRUE:Boolean.FALSE);
context.put("value_allPurposeTitle", state.getAttribute(ALLPURPOSE_TITLE));
context.put("value_allPurposeText", state.getAttribute(ALLPURPOSE_TEXT));
context.put("value_allPurposeHide", state.getAttribute(ALLPURPOSE_HIDE) != null?state.getAttribute(ALLPURPOSE_HIDE):Boolean.FALSE);
context.put("value_allPurposeShowFrom", state.getAttribute(ALLPURPOSE_SHOW_FROM) != null?state.getAttribute(ALLPURPOSE_SHOW_FROM):Boolean.FALSE);
context.put("value_allPurposeShowTo", state.getAttribute(ALLPURPOSE_SHOW_TO) != null?state.getAttribute(ALLPURPOSE_SHOW_TO):Boolean.FALSE);
context.put("value_allPurposeAccessList", state.getAttribute(ALLPURPOSE_ACCESS));
putTimePropertiesInContext(context, state, "allPurposeRelease", ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, ALLPURPOSE_RELEASE_AMPM);
putTimePropertiesInContext(context, state, "allPurposeRetract", ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, ALLPURPOSE_RETRACT_AMPM);
// get attachment for all purpose object
putSupplementItemAttachmentStateIntoContext(state, context, ALLPURPOSE_ATTACHMENTS);
// put role information into context
Hashtable<String, List> roleUsers = new Hashtable<String, List>();
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString));
Set<Role> roles = realm.getRoles();
for(Iterator iRoles = roles.iterator(); iRoles.hasNext();)
{
Role r = (Role) iRoles.next();
Set<String> users = realm.getUsersHasRole(r.getId());
if (users!=null && users.size() > 0)
{
List<User> usersList = new Vector();
for (Iterator<String> iUsers = users.iterator(); iUsers.hasNext();)
{
String userId = iUsers.next();
try
{
User u = UserDirectoryService.getUser(userId);
usersList.add(u);
}
catch (Exception e)
{
M_log.warn(this + ":setAssignmentFormContext cannot get user " + e.getMessage() + " user id=" + userId);
}
}
roleUsers.put(r.getId(), usersList);
}
}
context.put("roleUsers", roleUsers);
}
catch (Exception e)
{
M_log.warn(this + ":setAssignmentFormContext role cast problem " + e.getMessage() + " site =" + contextString);
}
} // setAssignmentFormContext
private void putGradebookCategoryInfoIntoContext(SessionState state,
Context context) {
Hashtable<Long, String> categoryTable = categoryTable();
if (categoryTable != null)
{
context.put("value_totalCategories", Integer.valueOf(categoryTable.size()));
// selected category
context.put("value_Category", state.getAttribute(NEW_ASSIGNMENT_CATEGORY));
Enumeration<Long> categories = categoryTable.keys();
List<Long> categoryList = new Vector<Long>();
while(categories.hasMoreElements())
{
categoryList.add(categories.nextElement());
}
Collections.sort(categoryList);
context.put("categoryKeys", categoryList);
context.put("categoryTable", categoryTable());
}
else
{
context.put("value_totalCategories", Integer.valueOf(0));
}
}
/**
* put the release grade notification options into context
* @param state
* @param context
*/
private void putReleaseGradeNotificationOptionIntoContext(SessionState state, Context context) {
if (state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) == null)
{
// set the notification value using site default to be none: no email will be sent to student when the grade is released
state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_NONE);
}
// input fields
context.put("name_assignment_releasegrade_notification", ASSIGNMENT_RELEASEGRADE_NOTIFICATION);
context.put("value_assignment_releasegrade_notification", state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE));
// the option values
context.put("value_assignment_releasegrade_notification_none", Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_NONE);
context.put("value_assignment_releasegrade_notification_each", Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_EACH);
}
/**
* build the instructor view of create a new assignment
*/
protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("time", TimeService.newTime());
context.put("user", UserDirectoryService.getCurrentUser());
context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE));
context.put("name_order", NEW_ASSIGNMENT_ORDER);
context.put("value_position_order", (String) state.getAttribute(NEW_ASSIGNMENT_ORDER));
Time openTime = getTimeFromState(state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM);
context.put("value_OpenDate", openTime);
// due time
Time dueTime = getTimeFromState(state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM);
context.put("value_DueDate", dueTime);
// close time
Time closeTime = TimeService.newTime();
Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE);
context.put("value_EnableCloseDate", enableCloseDate);
if ((enableCloseDate).booleanValue())
{
closeTime = getTimeFromState(state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM);
context.put("value_CloseDate", closeTime);
}
context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION));
context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE));
context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE));
String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
context.put("value_GradePoints", displayGrade(state, maxGrade));
context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION));
context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE));
// get all available assignments from Gradebook tool except for those created from
if (isGradebookDefined())
{
context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
// information related to gradebook categories
putGradebookCategoryInfoIntoContext(state, context);
}
context.put("monthTable", monthTable());
context.put("submissionTypeTable", submissionTypeTable());
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG));
context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG));
String assignmentId = StringUtil.trimToNull((String) state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID));
if (assignmentId != null)
{
// editing existing assignment
context.put("value_assignment_id", assignmentId);
Assignment a = getAssignment(assignmentId, "build_instructor_preview_assignment_context", state);
if (a != null)
{
context.put("isDraft", Boolean.valueOf(a.getDraft()));
}
}
else
{
// new assignment
context.put("isDraft", Boolean.TRUE);
}
context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID));
context.put("currentTime", TimeService.newTime());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT;
} // build_instructor_preview_assignment_context
/**
* build the instructor view to delete an assignment
*/
protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
Vector assignments = new Vector();
Vector assignmentIds = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
Hashtable<String, Integer> submissionCountTable = new Hashtable<String, Integer>();
for (int i = 0; i < assignmentIds.size(); i++)
{
String assignmentId = (String) assignmentIds.get(i);
Assignment a = getAssignment(assignmentId, "build_instructor_delete_assignment_context", state);
if (a != null)
{
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
int submittedCount = 0;
while (submissions.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getSubmitted() && s.getTimeSubmitted() != null)
{
submittedCount++;
}
}
if (submittedCount > 0)
{
// if there is submission to the assignment, show the alert
addAlert(state, rb.getFormattedMessage("areyousur_withSubmission", new Object[]{a.getTitle()}));
}
assignments.add(a);
submissionCountTable.put(a.getReference(), Integer.valueOf(submittedCount));
}
}
context.put("assignments", assignments);
context.put("confirmMessage", assignments.size() > 1 ? rb.getString("areyousur_multiple"):rb.getString("areyousur_single"));
context.put("currentTime", TimeService.newTime());
context.put("submissionCountTable", submissionCountTable);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT;
} // build_instructor_delete_assignment_context
/**
* build the instructor view to grade an submission
*/
protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String submissionId="";
int gradeType = -1;
// need to show the alert for grading drafts?
boolean addGradeDraftAlert = false;
// assignment
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
Assignment a = getAssignment(assignmentId, "build_instructor_grade_submission_context", state);
if (a != null)
{
context.put("assignment", a);
if (a.getContent() != null)
{
gradeType = a.getContent().getTypeOfGrade();
}
boolean allowToGrade=true;
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if (associateGradebookAssignment != null)
{
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
if (g != null && g.isGradebookDefined(gradebookUid))
{
if (!g.currentUserHasGradingPerm(gradebookUid))
{
context.put("notAllowedToGradeWarning", rb.getString("not_allowed_to_grade_in_gradebook"));
allowToGrade=false;
}
}
}
context.put("allowToGrade", Boolean.valueOf(allowToGrade));
}
// assignment submission
AssignmentSubmission s = getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_instructor_grade_submission_context", state);
if (s != null)
{
submissionId = s.getId();
context.put("submission", s);
// show alert if student is working on a draft
if (!s.getSubmitted() // not submitted
&& ((s.getSubmittedText() != null && s.getSubmittedText().length()> 0) // has some text
|| (s.getSubmittedAttachments() != null && s.getSubmittedAttachments().size() > 0))) // has some attachment
{
if (s.getCloseTime().after(TimeService.newTime()))
{
// not pass the close date yet
addGradeDraftAlert = true;
}
else
{
// passed the close date already
addGradeDraftAlert = false;
}
}
ResourceProperties p = s.getProperties();
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null)
{
context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT));
}
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null)
{
context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT));
}
if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null)
{
context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p));
}
// put the re-submission info into context
putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
assignment_resubmission_option_into_context(context, state);
}
context.put("user", state.getAttribute(STATE_USER));
context.put("submissionTypeTable", submissionTypeTable());
context.put("instructorAttachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
// names
context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID);
context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT);
context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT);
context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
context.put("name_grade", GRADE_SUBMISSION_GRADE);
context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// values
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT));
context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS));
// format to show one decimal place in grade
context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE))
: state.getAttribute(GRADE_SUBMISSION_GRADE));
context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG));
// is this a non-electronic submission type of assignment
context.put("nonElectronic", (a!=null && a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)?Boolean.TRUE:Boolean.FALSE);
if (addGradeDraftAlert)
{
addAlert(state, rb.getString("grading.alert.draft.beforeclosedate"));
}
context.put("alertGradeDraft", Boolean.valueOf(addGradeDraftAlert));
// for the navigation purpose
List<UserSubmission> userSubmissions = state.getAttribute(USER_SUBMISSIONS) != null ? (List<UserSubmission>) state.getAttribute(USER_SUBMISSIONS):null;
if (userSubmissions != null)
{
for (int i = 0; i < userSubmissions.size(); i++)
{
if (((UserSubmission) userSubmissions.get(i)).getSubmission().getId().equals(submissionId))
{
boolean goPT = false;
boolean goNT = false;
if ((i - 1) >= 0)
{
goPT = true;
}
if ((i + 1) < userSubmissions.size())
{
goNT = true;
}
context.put("goPTButton", Boolean.valueOf(goPT));
context.put("goNTButton", Boolean.valueOf(goNT));
if (i>0)
{
// retrieve the previous submission id
context.put("prevSubmissionId", ((UserSubmission) userSubmissions.get(i-1)).getSubmission().getReference());
}
if (i < userSubmissions.size() - 1)
{
// retrieve the next submission id
context.put("nextSubmissionId", ((UserSubmission) userSubmissions.get(i+1)).getSubmission().getReference());
}
}
}
}
// put supplement item into context
supplementItemIntoContext(state, context, a, null);
// put the grade confirmation message if applicable
if (state.getAttribute(GRADE_SUBMISSION_DONE) != null)
{
context.put("gradingDone", Boolean.TRUE);
state.removeAttribute(GRADE_SUBMISSION_DONE);
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION;
} // build_instructor_grade_submission_context
/**
* Checks whether the time is already past.
* If yes, return the time of three days from current time;
* Otherwise, return the original time
* @param originalTime
* @return
*/
private Time getProperFutureTime(Time originalTime) {
// check whether the time is past already.
// If yes, add three days to the current time
Time time = originalTime;
if (TimeService.newTime().after(time))
{
time = TimeService.newTime(TimeService.newTime().getTime() + 3*24*60*60*1000/*add three days*/);
}
return time;
}
/**
* Responding to the request of submission navigation
* @param rundata
* @param option
*/
public void doPrev_back_next_submission(RunData rundata, String option)
{
SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid());
// save the instructor input
boolean hasChange = readGradeForm(rundata, state, "save");
if (state.getAttribute(STATE_MESSAGE) == null && hasChange)
{
grade_submission_option(rundata, "save");
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if ("next".equals(option))
{
navigateToSubmission(rundata, "nextSubmissionId");
}
else if ("prev".equals(option))
{
navigateToSubmission(rundata, "prevSubmissionId");
}
else if ("back".equals(option))
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
}
}
} // doPrev_back_next_submission
private void navigateToSubmission(RunData rundata, String paramString) {
ParameterParser params = rundata.getParameters();
SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid());
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
String submissionId = StringUtil.trimToNull(params.getString(paramString));
if (submissionId != null)
{
// put submission information into state
putSubmissionInfoIntoState(state, assignmentId, submissionId);
}
}
/**
* Parse time value and put corresponding values into state
* @param context
* @param state
* @param a
* @param timeValue
* @param timeName
* @param month
* @param day
* @param year
* @param hour
* @param min
* @param ampm
*/
private void putTimePropertiesInState(SessionState state, Time timeValue,
String month, String day, String year, String hour, String min, String ampm) {
TimeBreakdown bTime = timeValue.breakdownLocal();
state.setAttribute(month, Integer.valueOf(bTime.getMonth()));
state.setAttribute(day, Integer.valueOf(bTime.getDay()));
state.setAttribute(year, Integer.valueOf(bTime.getYear()));
int bHour = bTime.getHour();
if (bHour >= 12)
{
state.setAttribute(ampm, "PM");
}
else
{
state.setAttribute(ampm, "AM");
}
if (bHour == 0)
{
// for midnight point, we mark it as 12AM
bHour = 12;
}
state.setAttribute(hour, Integer.valueOf((bHour > 12) ? bHour - 12 : bHour));
state.setAttribute(min, Integer.valueOf(bTime.getMin()));
}
/**
* put related time information into context variable
* @param context
* @param state
* @param timeName
* @param month
* @param day
* @param year
* @param hour
* @param min
* @param ampm
*/
private void putTimePropertiesInContext(Context context, SessionState state, String timeName,
String month, String day, String year, String hour, String min, String ampm) {
// get the submission level of close date setting
context.put("name_" + timeName + "Month", month);
context.put("name_" + timeName + "Day", day);
context.put("name_" + timeName + "Year", year);
context.put("name_" + timeName + "Hour", hour);
context.put("name_" + timeName + "Min", min);
context.put("name_" + timeName + "AMPM", ampm);
context.put("value_" + timeName + "Month", (Integer) state.getAttribute(month));
context.put("value_" + timeName + "Day", (Integer) state.getAttribute(day));
context.put("value_" + timeName + "Year", (Integer) state.getAttribute(year));
context.put("value_" + timeName + "AMPM", (String) state.getAttribute(ampm));
context.put("value_" + timeName + "Hour", (Integer) state.getAttribute(hour));
context.put("value_" + timeName + "Min", (Integer) state.getAttribute(min));
}
private List getPrevFeedbackAttachments(ResourceProperties p) {
String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS);
String[] attachmentsReferences = attachmentsString.split(",");
List prevFeedbackAttachments = EntityManager.newReferenceList();
for (int k =0; k < attachmentsReferences.length; k++)
{
prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k]));
}
return prevFeedbackAttachments;
}
/**
* build the instructor preview of grading submission
*/
protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
// assignment
int gradeType = -1;
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
Assignment a = getAssignment(assignmentId, "build_instructor_preview_grade_submission_context", state);
if (a != null)
{
context.put("assignment", a);
gradeType = a.getContent().getTypeOfGrade();
}
// submission
context.put("submission", getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_instructor_preview_grade_submission_context", state));
User user = (User) state.getAttribute(STATE_USER);
context.put("user", user);
context.put("submissionTypeTable", submissionTypeTable());
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
// filter the feedback text for the instructor comment and mark it as red
String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
context.put("feedback_text", feedbackText);
context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT));
// format to show one decimal place
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
if (gradeType == 3)
{
grade = displayGrade(state, grade);
}
context.put("grade", grade);
context.put("comment_open", COMMENT_OPEN);
context.put("comment_close", COMMENT_CLOSE);
context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
if (closeTimeString != null)
{
// close time for resubmit
Time time = TimeService.newTime(Long.parseLong(closeTimeString));
context.put("allowResubmitCloseTime", time.toStringLocalFull());
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION;
} // build_instructor_preview_grade_submission_context
/**
* build the instructor view to grade an assignment
*/
protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("user", state.getAttribute(STATE_USER));
// sorting related fields
context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY));
context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC));
context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME);
context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME);
context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS);
context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE);
context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED);
context.put("sort_submitReview", SORTED_GRADE_SUBMISSION_CONTENTREVIEW);
String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
Assignment assignment = getAssignment(assignmentRef, "build_instructor_grade_assignment_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId());
if (assignment.getContent() != null)
{
context.put("value_SubmissionType", Integer.valueOf(assignment.getContent().getTypeOfSubmission()));
}
// put creator information into context
putCreatorIntoContext(context, assignment);
// ever set the default grade for no-submissions
String defaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE);
if (defaultGrade != null)
{
context.put("defaultGrade", defaultGrade);
}
initViewSubmissionListOption(state);
String view = (String)state.getAttribute(VIEW_SUBMISSION_LIST_OPTION);
context.put("view", view);
// access point url for zip file download
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference(
contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)));
if (!view.equals(rb.getString("gen.viewallgroupssections")))
{
// append the group info to the end
accessPointUrl = accessPointUrl.concat(view);
}
context.put("accessPointUrl", accessPointUrl);
if (AssignmentService.getAllowGroupAssignments())
{
Collection groupsAllowGradeAssignment = AssignmentService.getGroupsAllowGradeAssignment((String) state.getAttribute(STATE_CONTEXT_STRING), assignment.getReference());
// group list which user can add message to
if (groupsAllowGradeAssignment.size() > 0)
{
String sort = (String) state.getAttribute(SORTED_BY);
String asc = (String) state.getAttribute(SORTED_ASC);
if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION)))
{
sort = SORTED_BY_GROUP_TITLE;
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sort);
state.setAttribute(SORTED_ASC, asc);
}
context.put("groups", new SortedIterator(groupsAllowGradeAssignment.iterator(), new AssignmentComparator(state, sort, asc)));
}
}
List<UserSubmission> userSubmissions = prepPage(state);
state.setAttribute(USER_SUBMISSIONS, userSubmissions);
context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS));
// whether to show the resubmission choice
if (state.getAttribute(SHOW_ALLOW_RESUBMISSION) != null)
{
context.put("showAllowResubmission", Boolean.TRUE);
}
// put the re-submission info into context
putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
assignment_resubmission_option_into_context(context, state);
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
context.put("producer", ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"));
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
context.put("submissionTypeTable", submissionTypeTable());
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG));
context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG));
add2ndToolbarFields(data, context);
pagingInfoToContext(state, context);
// put supplement item into context
supplementItemIntoContext(state, context, assignment, null);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT;
} // build_instructor_grade_assignment_context
/**
* make sure the state variable VIEW_SUBMISSION_LIST_OPTION is not null
* @param state
*/
private void initViewSubmissionListOption(SessionState state) {
if (state.getAttribute(VIEW_SUBMISSION_LIST_OPTION) == null)
{
state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, rb.getString("gen.viewallgroupssections"));
}
}
/**
* put the supplement item information into context
* @param state
* @param context
* @param assignment
* @param s
*/
private void supplementItemIntoContext(SessionState state, Context context, Assignment assignment, AssignmentSubmission s) {
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// for model answer
boolean allowViewModelAnswer = m_assignmentSupplementItemService.canViewModelAnswer(assignment, s);
context.put("allowViewModelAnswer", allowViewModelAnswer);
if (allowViewModelAnswer)
{
context.put("assignmentModelAnswerItem", m_assignmentSupplementItemService.getModelAnswer(assignment.getId()));
}
// for note item
boolean allowReadAssignmentNoteItem = m_assignmentSupplementItemService.canReadNoteItem(assignment, contextString);
context.put("allowReadAssignmentNoteItem", allowReadAssignmentNoteItem);
if (allowReadAssignmentNoteItem)
{
context.put("assignmentNoteItem", m_assignmentSupplementItemService.getNoteItem(assignment.getId()));
}
// for all purpose item
boolean allowViewAllPurposeItem = m_assignmentSupplementItemService.canViewAllPurposeItem(assignment);
context.put("allowViewAllPurposeItem", allowViewAllPurposeItem);
if (allowViewAllPurposeItem)
{
context.put("assignmentAllPurposeItem", m_assignmentSupplementItemService.getAllPurposeItem(assignment.getId()));
}
}
/**
* build the instructor view of an assignment
*/
protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("tlang", rb);
String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID);
Assignment assignment = getAssignment(assignmentId, "build_instructor_view_assignment_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
// put the resubmit information into context
assignment_resubmission_option_into_context(context, state);
// put creator information into context
putCreatorIntoContext(context, assignment);
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
List<DecoratedTaggingProvider> providers = addProviders(context, state);
List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>();
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
for (DecoratedTaggingProvider provider : providers)
{
TaggingHelperInfo helper = provider.getProvider()
.getActivityHelperInfo(
assignmentActivityProducer.getActivity(
assignment).getReference());
if (helper != null)
{
activityHelpers.add(helper);
}
}
addActivity(context, assignment);
context.put("activityHelpers", activityHelpers);
context.put("taggable", Boolean.valueOf(true));
}
context.put("currentTime", TimeService.newTime());
context.put("submissionTypeTable", submissionTypeTable());
context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG));
context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT;
} // build_instructor_view_assignment_context
private void putCreatorIntoContext(Context context, Assignment assignment) {
// the creator
String creatorId = assignment.getCreator();
try
{
User creator = UserDirectoryService.getUser(creatorId);
context.put("creator", creator.getDisplayName());
}
catch (Exception ee)
{
context.put("creator", creatorId);
M_log.warn(this + ":build_instructor_view_assignment_context " + ee.getMessage());
}
}
/**
* build the instructor view of reordering assignments
*/
protected String build_instructor_reorder_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("context", state.getAttribute(STATE_CONTEXT_STRING));
List assignments = prepPage(state);
context.put("assignments", assignments.iterator());
context.put("assignmentsize", assignments.size());
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
context.put("site", site);
}
catch (Exception ignore)
{
M_log.warn(this + ":build_instructor_reorder_assignment_context " + ignore.getMessage());
}
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("userDirectoryService", UserDirectoryService.getInstance());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT;
} // build_instructor_reorder_assignment_context
/**
* build the instructor view to view the list of students for an assignment
*/
protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// get the realm and its member
List studentMembers = new Vector();
List allowSubmitMembers = AssignmentService.allowAddAnySubmissionUsers(contextString);
for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();)
{
// get user
try
{
String userId = (String) allowSubmitMembersIterator.next();
User user = UserDirectoryService.getUser(userId);
studentMembers.add(user);
}
catch (Exception ee)
{
M_log.warn(this + ":build_instructor_view_student_assignment_context " + ee.getMessage());
}
}
context.put("studentMembers", new SortedIterator(studentMembers.iterator(), new AssignmentComparator(state, SORTED_USER_BY_SORTNAME, Boolean.TRUE.toString())));
context.put("assignmentService", AssignmentService.getInstance());
Hashtable showStudentAssignments = new Hashtable();
if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null)
{
Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
context.put("studentListShowSet", showStudentListSet);
for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();)
{
// get user
try
{
String userId = (String) showStudentListSetIterator.next();
User user = UserDirectoryService.getUser(userId);
// sort the assignments into the default order before adding
Iterator assignmentSorter = AssignmentService.getAssignmentsForContext(contextString, userId);
// filter to obtain only grade-able assignments
List rv = new Vector();
while (assignmentSorter.hasNext())
{
Assignment a = (Assignment) assignmentSorter.next();
if (AssignmentService.allowGradeSubmission(a.getReference()))
{
rv.add(a);
}
}
Iterator assignmentSortFinal = new SortedIterator(rv.iterator(), new AssignmentComparator(state, SORTED_BY_DEFAULT, Boolean.TRUE.toString()));
showStudentAssignments.put(user, assignmentSortFinal);
}
catch (Exception ee)
{
M_log.warn(this + ":build_instructor_view_student_assignment_context " + ee.getMessage());
}
}
}
context.put("studentAssignmentsTable", showStudentAssignments);
add2ndToolbarFields(data, context);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT;
} // build_instructor_view_students_assignment_context
/**
* build the instructor view to report the submissions
*/
protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("submissions", prepPage(state));
context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY));
context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC));
context.put("sortedBy_lastName", SORTED_SUBMISSION_BY_LASTNAME);
context.put("sortedBy_submitTime", SORTED_SUBMISSION_BY_SUBMIT_TIME);
context.put("sortedBy_grade", SORTED_SUBMISSION_BY_GRADE);
context.put("sortedBy_status", SORTED_SUBMISSION_BY_STATUS);
context.put("sortedBy_released", SORTED_SUBMISSION_BY_RELEASED);
context.put("sortedBy_assignment", SORTED_SUBMISSION_BY_ASSIGNMENT);
context.put("sortedBy_maxGrade", SORTED_SUBMISSION_BY_MAX_GRADE);
add2ndToolbarFields(data, context);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("accessPointUrl", ServerConfigurationService.getAccessUrl()
+ AssignmentService.gradesSpreadsheetReference(contextString, null));
pagingInfoToContext(state, context);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS;
} // build_instructor_report_submissions
// Is Gradebook defined for the site?
protected boolean isGradebookDefined()
{
boolean rv = false;
try
{
GradebookService g = (GradebookService) ComponentManager
.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
if (g.isGradebookDefined(gradebookUid) && (g.currentUserHasEditPerm(gradebookUid) || g.currentUserHasGradingPerm(gradebookUid)))
{
rv = true;
}
}
catch (Exception e)
{
M_log.debug(this + "isGradebookDefined " + rb.getString("addtogradebook.alertMessage") + "\n" + e.getMessage());
}
return rv;
} // isGradebookDefined()
/**
* build the instructor view to download/upload information from archive file
*/
protected String build_instructor_download_upload_all(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
boolean download = (((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_DOWNLOAD_ALL));
context.put("download", Boolean.valueOf(download));
context.put("hasSubmissionText", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT));
context.put("hasSubmissionAttachment", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT));
context.put("hasGradeFile", state.getAttribute(UPLOAD_ALL_HAS_GRADEFILE));
context.put("hasComments", state.getAttribute(UPLOAD_ALL_HAS_COMMENTS));
context.put("hasFeedbackText", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT));
context.put("hasFeedbackAttachment", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT));
context.put("releaseGrades", state.getAttribute(UPLOAD_ALL_RELEASE_GRADES));
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference(
contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF))));
String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
Assignment a = getAssignment(assignmentRef, "build_instructor_download_upload_all", state);
if (a != null)
{
String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference(
contextString, assignmentRef));
context.put("accessPointUrl", accessPointUrl);
// if the assignment is of text-only or allow both text and attachment, include option for uploading student submit text
context.put("includeSubmissionText", Boolean.valueOf(Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION == a.getContent().getTypeOfSubmission() || Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION == a.getContent().getTypeOfSubmission()));
// if the assignment is of attachment-only or allow both text and attachment, include option for uploading student attachment
context.put("includeSubmissionAttachment", Boolean.valueOf(Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION == a.getContent().getTypeOfSubmission() || Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION == a.getContent().getTypeOfSubmission()));
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_UPLOAD_ALL;
} // build_instructor_upload_all
/**
** Retrieve tool title from Tool configuration file or use default
** (This should return i18n version of tool title if available)
**/
private String getToolTitle()
{
Tool tool = ToolManager.getTool(ASSIGNMENT_TOOL_ID);
String toolTitle = null;
if (tool == null)
toolTitle = "Assignments";
else
toolTitle = tool.getTitle();
return toolTitle;
}
/**
* integration with gradebook
*
* @param state
* @param assignmentRef Assignment reference
* @param associateGradebookAssignment The title for the associated GB assignment
* @param addUpdateRemoveAssignment "add" for adding the assignment; "update" for updating the assignment; "remove" for remove assignment
* @param oldAssignment_title The original assignment title
* @param newAssignment_title The updated assignment title
* @param newAssignment_maxPoints The maximum point of the assignment
* @param newAssignment_dueTime The due time of the assignment
* @param submissionRef Any submission grade need to be updated? Do bulk update if null
* @param updateRemoveSubmission "update" for update submission;"remove" for remove submission
*/
protected void integrateGradebook (SessionState state, String assignmentRef, String associateGradebookAssignment, String addUpdateRemoveAssignment, String oldAssignment_title, String newAssignment_title, int newAssignment_maxPoints, Time newAssignment_dueTime, String submissionRef, String updateRemoveSubmission, long category)
{
associateGradebookAssignment = StringUtil.trimToNull(associateGradebookAssignment);
// add or remove external grades to gradebook
// a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden
// b. if Gradebook exists, just call addExternal and removeExternal and swallow any exception. The
// exception are indication that the assessment is already in the Gradebook or there is nothing
// to remove.
String assignmentToolTitle = getToolTitle();
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
GradebookExternalAssessmentService gExternal = (GradebookExternalAssessmentService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
if (g.isGradebookDefined(gradebookUid) && g.currentUserHasGradingPerm(gradebookUid))
{
boolean isExternalAssignmentDefined=gExternal.isExternalAssignmentDefined(gradebookUid, assignmentRef);
boolean isExternalAssociateAssignmentDefined = gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment);
boolean isAssignmentDefined = g.isAssignmentDefined(gradebookUid, associateGradebookAssignment);
if (addUpdateRemoveAssignment != null)
{
// add an entry into Gradebook for newly created assignment or modified assignment, and there wasn't a correspond record in gradebook yet
if ((addUpdateRemoveAssignment.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD) || ("update".equals(addUpdateRemoveAssignment) && !isExternalAssignmentDefined)) && associateGradebookAssignment == null)
{
// add assignment into gradebook
try
{
// add assignment to gradebook
gExternal.addExternalAssessment(gradebookUid, assignmentRef, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), assignmentToolTitle, false, category != -1?Long.valueOf(category):null);
}
catch (AssignmentHasIllegalPointsException e)
{
addAlert(state, rb.getString("addtogradebook.illegalPoints"));
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
catch (ConflictingAssignmentNameException e)
{
// add alert prompting for change assignment title
addAlert(state, rb.getFormattedMessage("addtogradebook.nonUniqueTitle", new Object[]{"\"" + newAssignment_title + "\""}));
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
catch (ConflictingExternalIdException e)
{
// this shouldn't happen, as we have already checked for assignment reference before. Log the error
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
catch (GradebookNotFoundException e)
{
// this shouldn't happen, as we have checked for gradebook existence before
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
catch (Exception e)
{
// ignore
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
}
else if ("update".equals(addUpdateRemoveAssignment))
{
if (associateGradebookAssignment != null && isExternalAssociateAssignmentDefined)
{
// if there is an external entry created in Gradebook based on this assignment, update it
try
{
// update attributes if the GB assignment was created for the assignment
gExternal.updateExternalAssessment(gradebookUid, associateGradebookAssignment, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), false);
}
catch(Exception e)
{
addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef}));
M_log.warn(this + ":integrateGradebook " + rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef}));
}
}
} // addUpdateRemove != null
else if ("remove".equals(addUpdateRemoveAssignment))
{
// remove assignment and all submission grades
removeNonAssociatedExternalGradebookEntry((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentRef, associateGradebookAssignment, gExternal, gradebookUid);
}
}
if (updateRemoveSubmission != null)
{
Assignment a = getAssignment(assignmentRef, "integrateGradebook", state);
if (a != null)
{
if ("update".equals(updateRemoveSubmission)
&& a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null
&& !a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK).equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)
&& a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
if (submissionRef == null)
{
// bulk add all grades for assignment into gradebook
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
Map m = new HashMap();
// any score to copy over? get all the assessmentGradingData and copy over
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
if (aSubmission.getGradeReleased())
{
User[] submitters = aSubmission.getSubmitters();
if (submitters != null && submitters.length > 0) {
String submitterId = submitters[0].getId();
String gradeString = StringUtil.trimToNull(aSubmission.getGrade(false));
String grade = gradeString != null ? displayGrade(state,gradeString) : null;
m.put(submitterId, grade);
}
}
}
// need to update only when there is at least one submission
if (!m.isEmpty())
{
if (associateGradebookAssignment != null)
{
if (isExternalAssociateAssignmentDefined)
{
// the associated assignment is externally maintained
gExternal.updateExternalAssessmentScoresString(gradebookUid, associateGradebookAssignment, m);
}
else if (isAssignmentDefined)
{
// the associated assignment is internal one, update records one by one
Iterator mKeys = m.keySet().iterator();
while (mKeys.hasNext())
{
String submitterId = (String) mKeys.next();
String grade = StringUtil.trimToNull(displayGrade(state, (String) m.get(submitterId)));
if (grade != null)
{
g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitterId, grade, "");
}
}
}
}
else if (isExternalAssignmentDefined)
{
gExternal.updateExternalAssessmentScoresString(gradebookUid, assignmentRef, m);
}
}
}
else
{
// only update one submission
AssignmentSubmission aSubmission = getSubmission(submissionRef, "integrateGradebook", state);
if (aSubmission != null)
{
User[] submitters = aSubmission.getSubmitters();
String gradeString = displayGrade(state, StringUtil.trimToNull(aSubmission.getGrade(false)));
if (submitters != null && submitters.length > 0)
{
if (associateGradebookAssignment != null)
{
if (gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment))
{
// the associated assignment is externally maintained
gExternal.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? gradeString : "");
}
else if (g.isAssignmentDefined(gradebookUid, associateGradebookAssignment))
{
// the associated assignment is internal one, update records
g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? gradeString : "", "");
}
}
else
{
gExternal.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? gradeString : "");
}
}
}
}
}
else if ("remove".equals(updateRemoveSubmission))
{
if (submissionRef == null)
{
// remove all submission grades (when changing the associated entry in Gradebook)
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
// any score to copy over? get all the assessmentGradingData and copy over
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
User[] submitters = aSubmission.getSubmitters();
if (submitters != null && submitters.length > 0)
{
if (isExternalAssociateAssignmentDefined)
{
// if the old associated assignment is an external maintained one
gExternal.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null);
}
else if (isAssignmentDefined)
{
g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null, assignmentToolTitle);
}
}
}
}
else
{
// remove only one submission grade
AssignmentSubmission aSubmission = getSubmission(submissionRef, "integrateGradebook", state);
if (aSubmission != null)
{
User[] submitters = aSubmission.getSubmitters();
if (submitters != null && submitters.length > 0)
{
gExternal.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), null);
}
}
}
}
}
}
}
} // integrateGradebook
/**
* Go to the instructor view
*/
public void doView_instructor(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doView_instructor
/**
* Go to the student view
*/
public void doView_student(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// to the student list of assignment view
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doView_student
/**
* Action is to view the content of one specific assignment submission
*/
public void doView_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the submission context
resetViewSubmission(state);
ParameterParser params = data.getParameters();
String assignmentReference = params.getString("assignmentReference");
state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference);
User u = (User) state.getAttribute(STATE_USER);
Assignment a = getAssignment(assignmentReference, "doView_submission", state);
if (a != null)
{
AssignmentSubmission submission = getSubmission(assignmentReference, u, "doView_submission", state);
if (submission != null)
{
state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText());
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (Boolean.valueOf(submission.getHonorPledgeFlag())).toString());
List v = EntityManager.newReferenceList();
Iterator l = submission.getSubmittedAttachments().iterator();
while (l.hasNext())
{
v.add(l.next());
}
state.setAttribute(ATTACHMENTS, v);
}
else
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false");
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
// put resubmission option into state
assignment_resubmission_option_into_state(a, submission, state);
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION);
if (submission != null)
{
// submission read event
m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submission.getId(), false));
}
else
{
// otherwise, the student just read assignment description and prepare for submission
m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, a.getId(), false));
}
}
} // doView_submission
/**
* Action is to view the content of one specific assignment submission
*/
public void doView_submission_list_option(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String view = params.getString("view");
state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, view);
} // doView_submission_list_option
/**
* Preview of the submission
*/
public void doPreview_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, aReference);
Assignment a = getAssignment(aReference, "doPreview_submission", state);
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
state.setAttribute(PREVIEW_SUBMISSION_TEXT, text);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
// assign the honor pledge attribute
String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honor_pledge_yes == null)
{
honor_pledge_yes = "false";
}
state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes);
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes);
// get attachment input and generate alert message according to assignment submission type
checkSubmissionTextAttachmentInput(data, state, a, text);
state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION);
}
} // doPreview_submission
/**
* Preview of the grading of submission
*/
public void doPreview_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read user input
readGradeForm(data, state, "read");
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION);
}
} // doPreview_grade_submission
/**
* Action is to end the preview submission process
*/
public void doDone_preview_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION);
} // doDone_preview_submission
/**
* Action is to end the view assignment process
*/
public void doDone_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doDone_view_assignments
/**
* Action is to end the preview new assignment process
*/
public void doDone_preview_new_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the new assignment page
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
} // doDone_preview_new_assignment
/**
* Action is to end the user view assignment process and redirect him to the assignment list view
*/
public void doCancel_student_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view assignment
state.setAttribute(VIEW_ASSIGNMENT_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_student_view_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_show_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view assignment
state.setAttribute(VIEW_ASSIGNMENT_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_show_submission
/**
* Action is to cancel the delete assignment process
*/
public void doCancel_delete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the show assignment object
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
// back to the instructor list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_delete_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_edit_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the assignment object
resetAssignment(state);
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
// reset sorting
setDefaultSort(state);
} // doCancel_edit_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_new_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the assignment object
resetAssignment(state);
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
// reset sorting
setDefaultSort(state);
} // doCancel_new_assignment
/**
* Action is to cancel the grade submission process
*/
public void doCancel_grade_submission(RunData data)
{
// put submission information into state
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
putSubmissionInfoIntoState(state, assignmentId, sId);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
} // doCancel_grade_submission
/**
* clean the state variables related to grading page
* @param state
*/
private void resetGradeSubmission(SessionState state) {
// reset the grade parameters
state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT);
state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
state.removeAttribute(GRADE_SUBMISSION_GRADE);
state.removeAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
state.removeAttribute(GRADE_SUBMISSION_DONE);
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
resetAllowResubmitParams(state);
}
/**
* Action is to cancel the preview grade process
*/
public void doCancel_preview_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the instructor view of grading a submission
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
} // doCancel_preview_grade_submission
/**
* Action is to cancel the reorder process
*/
public void doCancel_reorder(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_reorder
/**
* Action is to cancel the preview grade process
*/
public void doCancel_preview_to_list_submission(RunData data)
{
doCancel_grade_submission(data);
} // doCancel_preview_to_list_submission
/**
* Action is to return to the view of list assignments
*/
public void doList_assignments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doList_assignments
/**
* Action is to cancel the student view grade process
*/
public void doCancel_view_grade(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view grade submission id
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_view_grade
/**
* Action is to save the grade to submission
*/
public void doSave_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "save");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "save");
}
} // doSave_grade_submission
/**
* Action is to release the grade to submission
*/
public void doRelease_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "release");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "release");
}
} // doRelease_grade_submission
/**
* Action is to return submission with or without grade
*/
public void doReturn_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "return");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "return");
}
} // doReturn_grade_submission
/**
* Action is to return submission with or without grade from preview
*/
public void doReturn_preview_grade_submission(RunData data)
{
grade_submission_option(data, "return");
} // doReturn_grade_preview_submission
/**
* Action is to save submission with or without grade from preview
*/
public void doSave_preview_grade_submission(RunData data)
{
grade_submission_option(data, "save");
} // doSave_grade_preview_submission
/**
* Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade.
*/
private void grade_submission_option(RunData data, String gradeOption)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false;
String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
// for points grading, one have to enter number as the points
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
AssignmentSubmissionEdit sEdit = editSubmission(sId, "grade_submission_option", state);
if (sEdit != null)
{
Assignment a = sEdit.getAssignment();
int typeOfGrade = a.getContent().getTypeOfGrade();
if (!withGrade)
{
// no grade input needed for the without-grade version of assignment tool
sEdit.setGraded(true);
if ("return".equals(gradeOption) || "release".equals(gradeOption))
{
sEdit.setGradeReleased(true);
}
}
else if (grade == null)
{
sEdit.setGrade("");
sEdit.setGraded(false);
sEdit.setGradeReleased(false);
}
else
{
sEdit.setGrade(grade);
if (grade.length() != 0)
{
sEdit.setGraded(true);
}
else
{
sEdit.setGraded(false);
}
}
if ("release".equals(gradeOption))
{
sEdit.setGradeReleased(true);
sEdit.setGraded(true);
// clear the returned flag
sEdit.setReturned(false);
sEdit.setTimeReturned(null);
}
else if ("return".equals(gradeOption))
{
sEdit.setGradeReleased(true);
sEdit.setGraded(true);
sEdit.setReturned(true);
sEdit.setTimeReturned(TimeService.newTime());
sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue());
}
else if ("save".equals(gradeOption))
{
sEdit.setGradeReleased(false);
sEdit.setReturned(false);
sEdit.setTimeReturned(null);
}
ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit();
if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// get resubmit number
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null)
{
// get resubmit time
Time closeTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
}
else
{
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
}
else
{
// clean resubmission property
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
// the instructor comment
String feedbackCommentString = StringUtil
.trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
if (feedbackCommentString != null)
{
sEdit.setFeedbackComment(feedbackCommentString);
}
// the instructor inline feedback
String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
if (feedbackTextString != null)
{
sEdit.setFeedbackText(feedbackTextString);
}
List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
if (v != null)
{
// clear the old attachments first
sEdit.clearFeedbackAttachments();
for (int i = 0; i < v.size(); i++)
{
sEdit.addFeedbackAttachment((Reference) v.get(i));
}
}
String sReference = sEdit.getReference();
AssignmentService.commitEdit(sEdit);
// update grades in gradebook
String aReference = a.getReference();
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if ("release".equals(gradeOption) || "return".equals(gradeOption))
{
// update grade in gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update", -1);
}
else
{
// remove grade from gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "remove", -1);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// put submission information into state
putSubmissionInfoIntoState(state, assignmentId, sId);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
state.setAttribute(GRADE_SUBMISSION_DONE, Boolean.TRUE);
}
else
{
state.removeAttribute(GRADE_SUBMISSION_DONE);
}
} // grade_submission_option
/**
* Action is to save the submission as a draft
*/
public void doSave_submission(RunData data)
{
// save submission
post_save_submission(data, false);
} // doSave_submission
/**
* set the resubmission related properties in AssignmentSubmission object
* @param a
* @param edit
*/
private void setResubmissionProperties(Assignment a,
AssignmentSubmissionEdit edit) {
// get the assignment setting for resubmitting
ResourceProperties assignmentProperties = a.getProperties();
String assignmentAllowResubmitNumber = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (assignmentAllowResubmitNumber != null)
{
edit.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
edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, assignmentAllowResubmitCloseDate != null?assignmentAllowResubmitCloseDate:String.valueOf(a.getCloseTime().getTime()));
}
}
/**
* Action is to post the submission
*/
public void doPost_submission(RunData data)
{
// post submission
post_save_submission(data, true);
} // doPost_submission
/**
* Inner method used for post or save submission
* @param data
* @param post
*/
private void post_save_submission(RunData data, boolean post)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment a = getAssignment(aReference, "post_save_submission", state);
if (a != null && AssignmentService.canSubmit(contextString, a))
{
ParameterParser params = data.getParameters();
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // check formatting error whether the student is posting or saving
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
if (text == null)
{
text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT);
}
else
{
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
}
String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honorPledgeYes == null)
{
honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
}
if (honorPledgeYes == null)
{
honorPledgeYes = "false";
}
User u = (User) state.getAttribute(STATE_USER);
String assignmentId = "";
if (state.getAttribute(STATE_MESSAGE) == null)
{
assignmentId = a.getId();
if (a.getContent().getHonorPledge() != 1)
{
if (!Boolean.valueOf(honorPledgeYes).booleanValue())
{
addAlert(state, rb.getString("youarenot18"));
}
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes);
}
// get attachment input and generate alert message according to assignment submission type
checkSubmissionTextAttachmentInput(data, state, a, text);
}
if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null))
{
AssignmentSubmission submission = getSubmission(a.getReference(), u, "post_save_submission", state);
if (submission != null)
{
// the submission already exists, change the text and honor pledge value, post it
AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "post_save_submission", state);
if (sEdit != null)
{
ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit();
sEdit.setSubmittedText(text);
sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
sEdit.setTimeSubmitted(TimeService.newTime());
sEdit.setSubmitted(post);
// decrease the allow_resubmit_number, if this submission has been submitted.
if (sEdit.getSubmitted() && sEdit.getTimeSubmitted() != null && sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
// minus 1 from the submit number, if the number is not -1 (not unlimited)
if (number>=1)
{
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1));
}
}
// for resubmissions
// when resubmit, keep the Returned flag on till the instructor grade again.
Time now = TimeService.newTime();
if (sEdit.getGraded() && sEdit.getReturned() && sEdit.getGradeReleased())
{
// add the current grade into previous grade histroy
String previousGrades = (String) sEdit.getProperties().getProperty(
ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES);
if (previousGrades == null)
{
previousGrades = (String) sEdit.getProperties().getProperty(
ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES);
if (previousGrades != null)
{
int typeOfGrade = a.getContent().getTypeOfGrade();
if (typeOfGrade == 3)
{
// point grade assignment type
// some old unscaled grades, need to scale the number and remove the old property
String[] grades = StringUtil.split(previousGrades, " ");
String newGrades = "";
for (int jj = 0; jj < grades.length; jj++)
{
String grade = grades[jj];
if (grade.indexOf(".") == -1)
{
// show the grade with decimal point
grade = grade.concat(".0");
}
newGrades = newGrades.concat(grade + " ");
}
previousGrades = newGrades;
}
sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES);
}
else
{
previousGrades = "";
}
}
previousGrades = "<h4>" + now.toStringLocalFull() + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getGradeDisplay() + "</div>" +previousGrades;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES,
previousGrades);
// clear the current grade and make the submission ungraded
sEdit.setGraded(false);
sEdit.setGrade("");
sEdit.setGradeReleased(false);
// keep the history of assignment feed back text
String feedbackTextHistory = sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)
: "";
feedbackTextHistory = "<h4>" + now.toStringLocalFull() + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getFeedbackText() + "</div>" + feedbackTextHistory;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT,
feedbackTextHistory);
// keep the history of assignment feed back comment
String feedbackCommentHistory = sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)
: "";
feedbackCommentHistory = "<h4>" + now.toStringLocalFull() + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getFeedbackComment() + "</div>" + feedbackCommentHistory;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT,
feedbackCommentHistory);
// keep the history of assignment feed back comment
String feedbackAttachmentHistory = sPropertiesEdit
.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit
.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS)
: "";
List feedbackAttachments = sEdit.getFeedbackAttachments();
String att = "";
for (int k = 0; k<feedbackAttachments.size();k++)
{
// use comma as separator for attachments
att = att + ((Reference) feedbackAttachments.get(k)).getReference() + ",";
}
feedbackAttachmentHistory = att + feedbackAttachmentHistory;
sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS,
feedbackAttachmentHistory);
// reset the previous grading context
sEdit.setFeedbackText("");
sEdit.setFeedbackComment("");
sEdit.clearFeedbackAttachments();
}
sEdit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
//Post the attachments before clearing so that we don't sumbit duplicate attachments
//Check if we need to post the attachments
if (a.getContent().getAllowReviewService()) {
if (!attachments.isEmpty()) {
sEdit.postAttachment(attachments);
}
}
// clear the old attachments first
sEdit.clearSubmittedAttachments();
// add each new attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
sEdit.addSubmittedAttachment((Reference) it.next());
}
}
AssignmentService.commitEdit(sEdit);
}
}
else
{
// new submission
try
{
AssignmentSubmissionEdit edit = AssignmentService.addSubmission(contextString, assignmentId, SessionManager.getCurrentSessionUserId());
edit.setSubmittedText(text);
edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
edit.setTimeSubmitted(TimeService.newTime());
edit.setSubmitted(post);
edit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
// add each attachment
if ((!attachments.isEmpty()) && a.getContent().getAllowReviewService())
edit.postAttachment(attachments);
// add each attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
edit.addSubmittedAttachment((Reference) it.next());
}
}
// set the resubmission properties
setResubmissionProperties(a, edit);
AssignmentService.commitEdit(edit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot13"));
M_log.warn(this + ":post_save_submission " + e.getMessage());
}
} // if-else
} // if
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION);
}
} // if
} // post_save_submission
private void checkSubmissionTextAttachmentInput(RunData data,
SessionState state, Assignment a, String text) {
if (a != null)
{
// check the submission inputs based on the submission type
int submissionType = a.getContent().getTypeOfSubmission();
if (submissionType == 1)
{
// for the inline only submission
if (text.length() == 0)
{
addAlert(state, rb.getString("youmust7"));
}
}
else if (submissionType == 2)
{
// dealing with single file uplaod
doAttachUpload(data, false);
// for the attachment only submission
Vector v = (Vector) state.getAttribute(ATTACHMENTS);
if ((v == null) || (v.size() == 0))
{
addAlert(state, rb.getString("youmust1"));
}
}
else if (submissionType == 3)
{
// dealing with single file uplaod
doAttachUpload(data, false);
// for the inline and attachment submission
Vector v = (Vector) state.getAttribute(ATTACHMENTS);
if ((text.length() == 0 || "<br/>".equals(text)) && ((v == null) || (v.size() == 0)))
{
addAlert(state, rb.getString("youmust2"));
}
}
else if (submissionType == Assignment.SINGLE_ATTACHMENT_SUBMISSION)
{
// dealing with single file uplaod
doAttachUpload(data, true);
}
}
}
/**
* Action is to confirm the submission and return to list view
*/
public void doConfirm_assignment_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
/**
* Action is to show the new assignment screen
*/
public void doNew_assignment(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
initializeAssignment(state);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot_addAssignment"));
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
}
} // doNew_Assignment
/**
* Action is to show the reorder assignment screen
*/
public void doReorder(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// this insures the default order is loaded into the reordering tool
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
if (!alertGlobalNavigation(state, data))
{
if (AssignmentService.allowAllGroups((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REORDER_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot19"));
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
}
} // doReorder
/**
* Action is to save the input infos for assignment fields
*
* @param validify
* Need to validify the inputs or not
*/
protected void setNewAssignmentParameters(RunData data, boolean validify)
{
// read the form inputs
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// put the input value into the state attributes
String title = params.getString(NEW_ASSIGNMENT_TITLE);
state.setAttribute(NEW_ASSIGNMENT_TITLE, title);
String order = params.getString(NEW_ASSIGNMENT_ORDER);
state.setAttribute(NEW_ASSIGNMENT_ORDER, order);
if (title == null || title.length() == 0)
{
// empty assignment title
addAlert(state, rb.getString("plespethe1"));
}
// open time
Time openTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM, "date.opendate");
// due time
Time dueTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM, "date.duedate");
// show alert message when due date is in past. Remove it after user confirms the choice.
if (dueTime != null && dueTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) == null)
{
state.setAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE, Boolean.TRUE);
}
else
{
// clean the attribute after user confirm
state.removeAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE);
}
if (state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) != null && validify)
{
addAlert(state, rb.getString("assig4"));
}
if (openTime != null && dueTime != null && !dueTime.after(openTime))
{
addAlert(state, rb.getString("assig3"));
}
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true));
// close time
Time closeTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM, "date.closedate");
if (openTime != null && closeTime != null && !closeTime.after(openTime))
{
addAlert(state, rb.getString("acesubdea3"));
}
if (dueTime != null && closeTime != null && closeTime.before(dueTime))
{
addAlert(state, rb.getString("acesubdea2"));
}
// SECTION MOD
String sections_string = "";
String mode = (String) state.getAttribute(STATE_MODE);
if (mode == null) mode = "";
state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string);
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE)));
// Skip category if it was never set.
Long catInt = Long.valueOf(-1);
if(params.getString(NEW_ASSIGNMENT_CATEGORY) != null)
catInt = Long.valueOf(params.getString(NEW_ASSIGNMENT_CATEGORY));
state.setAttribute(NEW_ASSIGNMENT_CATEGORY, catInt);
int gradeType = -1;
// grade type and grade points
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE));
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(gradeType));
}
String r = params.getString(NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
String b;
// set whether we use the review service or not
if (r == null) b = Boolean.FALSE.toString();
else b = Boolean.TRUE.toString();
state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, b);
//set whether students can view the review service results
r = params.getString(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW);
if (r == null) b = Boolean.FALSE.toString();
else b = Boolean.TRUE.toString();
state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, b);
// treat the new assignment description as formatted text
boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors
String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION),
checkForFormattingErrors);
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description);
if (state.getAttribute(CALENDAR) != null)
{
// calendar enabled for the site
if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null
&& params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString());
}
else
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString());
}
}
else
{
// no calendar yet for the site
state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
}
if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null
&& params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)
.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString());
}
else
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString());
}
String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
// set the honor pledge to be "no honor pledge"
if (s == null) s = "1";
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s);
String grading = params.getString(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading);
// only when choose to associate with assignment in Gradebook
String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (grading != null)
{
if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE))
{
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment);
}
else
{
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, "");
}
if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// gradebook integration only available to point-grade assignment
if (gradeType != Assignment.SCORE_GRADE_TYPE)
{
addAlert(state, rb.getString("addtogradebook.wrongGradeScale"));
}
// if chosen as "associate", have to choose one assignment from Gradebook
if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtil.trimToNull(associateAssignment) == null)
{
addAlert(state, rb.getString("grading.associate.alert"));
}
}
}
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments == null || attachments.isEmpty())
{
// read from vm file
String[] attachmentIds = data.getParameters().getStrings("attachments");
if (attachmentIds != null && attachmentIds.length != 0)
{
attachments = new Vector();
for (int i= 0; i<attachmentIds.length;i++)
{
attachments.add(EntityManager.newReference(attachmentIds[i]));
}
}
}
state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments);
if (validify)
{
if ((description == null) || (description.length() == 0) || ("<br/>".equals(description)) && ((attachments == null || attachments.size() == 0)))
{
// if there is no description nor an attachment, show the following alert message.
// One could ignore the message and still post the assignment
if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null)
{
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString());
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
}
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
}
}
if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null)
{
addAlert(state, rb.getString("thiasshas"));
}
// assignment range?
String range = data.getParameters().getString("range");
state.setAttribute(NEW_ASSIGNMENT_RANGE, range);
if ("groups".equals(range))
{
String[] groupChoice = data.getParameters().getStrings("selectedGroups");
if (groupChoice != null && groupChoice.length != 0)
{
state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice)));
}
else
{
state.setAttribute(NEW_ASSIGNMENT_GROUPS, null);
addAlert(state, rb.getString("java.alert.youchoosegroup"));
}
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
}
// allow resubmission numbers
if (params.getString("allowResToggle") != null && params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// read in allowResubmit params
readAllowResubmitParams(params, state, null);
}
else
{
resetAllowResubmitParams(state);
}
// assignment notification option
String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS);
if (notiOption != null)
{
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption);
}
// release grade notification option
String releaseGradeOption = params.getString(ASSIGNMENT_RELEASEGRADE_NOTIFICATION);
if (releaseGradeOption != null)
{
state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, releaseGradeOption);
}
// read inputs for supplement items
setNewAssignmentParametersSupplementItems(validify, state, params);
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
// the grade point
String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS);
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints);
if (gradePoints != null)
{
if (gradeType == 3)
{
if ((gradePoints.length() == 0))
{
// in case of point grade assignment, user must specify maximum grade point
addAlert(state, rb.getString("plespethe3"));
}
else
{
validPointGrade(state, gradePoints);
// when scale is points, grade must be integer and less than maximum value
if (state.getAttribute(STATE_MESSAGE) == null)
{
gradePoints = scalePointGrade(state, gradePoints);
}
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints);
}
}
}
}
} // setNewAssignmentParameters
/**
* read inputs for supplement items
* @param validify
* @param state
* @param params
*/
private void setNewAssignmentParametersSupplementItems(boolean validify,
SessionState state, ParameterParser params) {
/********************* MODEL ANSWER ITEM *********************/
String modelAnswer_to_delete = StringUtil.trimToNull(params.getString("modelanswer_to_delete"));
if (modelAnswer_to_delete != null)
{
state.setAttribute(MODELANSWER_TO_DELETE, modelAnswer_to_delete);
}
String modelAnswer_text = StringUtil.trimToNull(params.getString("modelanswer_text"));
if (modelAnswer_text != null)
{
state.setAttribute(MODELANSWER_TEXT, modelAnswer_text);
}
String modelAnswer_showto = StringUtil.trimToNull(params.getString("modelanswer_showto"));
if (modelAnswer_showto != null)
{
state.setAttribute(MODELANSWER_SHOWTO, modelAnswer_showto);
}
if (modelAnswer_text != null || !"0".equals(modelAnswer_showto) || state.getAttribute(MODELANSWER_ATTACHMENTS) != null)
{
// there is Model Answer input
state.setAttribute(MODELANSWER, Boolean.TRUE);
if (validify && !"true".equalsIgnoreCase(modelAnswer_to_delete))
{
// show alert when there is no model answer input
if (modelAnswer_text == null)
{
addAlert(state, rb.getString("modelAnswer.alert.modelAnswer"));
}
// show alert when user didn't select show-to option
if ("0".equals(modelAnswer_showto))
{
addAlert(state, rb.getString("modelAnswer.alert.showto"));
}
}
}
else
{
state.removeAttribute(MODELANSWER);
}
/**************** NOTE ITEM ********************/
String note_to_delete = StringUtil.trimToNull(params.getString("note_to_delete"));
if (note_to_delete != null)
{
state.setAttribute(NOTE_TO_DELETE, note_to_delete);
}
String note_text = StringUtil.trimToNull(params.getString("note_text"));
if (note_text != null)
{
state.setAttribute(NOTE_TEXT, note_text);
}
String note_to = StringUtil.trimToNull(params.getString("note_to"));
if (note_to != null)
{
state.setAttribute(NOTE_SHAREWITH, note_to);
}
if (note_text != null || !"0".equals(note_to))
{
// there is Note Item input
state.setAttribute(NOTE, Boolean.TRUE);
if (validify && !"true".equalsIgnoreCase(note_to_delete))
{
// show alert when there is no note text
if (note_text == null)
{
addAlert(state, rb.getString("note.alert.text"));
}
// show alert when there is no share option
if ("0".equals(note_to))
{
addAlert(state, rb.getString("note.alert.to"));
}
}
}
else
{
state.removeAttribute(NOTE);
}
/****************** ALL PURPOSE ITEM **********************/
String allPurpose_to_delete = StringUtil.trimToNull(params.getString("allPurpose_to_delete"));
if ( allPurpose_to_delete != null)
{
state.setAttribute(ALLPURPOSE_TO_DELETE, allPurpose_to_delete);
}
String allPurposeTitle = StringUtil.trimToNull(params.getString("allPurposeTitle"));
if (allPurposeTitle != null)
{
state.setAttribute(ALLPURPOSE_TITLE, allPurposeTitle);
}
String allPurposeText = StringUtil.trimToNull(params.getString("allPurposeText"));
if (allPurposeText != null)
{
state.setAttribute(ALLPURPOSE_TEXT, allPurposeText);
}
if (StringUtil.trimToNull(params.getString("allPurposeHide")) != null)
{
state.setAttribute(ALLPURPOSE_HIDE, Boolean.valueOf(params.getString("allPurposeHide")));
}
if (StringUtil.trimToNull(params.getString("allPurposeShowFrom")) != null)
{
state.setAttribute(ALLPURPOSE_SHOW_FROM, Boolean.valueOf(params.getString("allPurposeShowFrom")));
// allpurpose release time
putTimeInputInState(params, state, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, ALLPURPOSE_RELEASE_AMPM, "date.allpurpose.releasedate");
}
else
{
state.removeAttribute(ALLPURPOSE_SHOW_FROM);
}
if (StringUtil.trimToNull(params.getString("allPurposeShowTo")) != null)
{
state.setAttribute(ALLPURPOSE_SHOW_TO, Boolean.valueOf(params.getString("allPurposeShowTo")));
// allpurpose retract time
putTimeInputInState(params, state, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, ALLPURPOSE_RETRACT_AMPM, "date.allpurpose.retractdate");
}
else
{
state.removeAttribute(ALLPURPOSE_SHOW_TO);
}
String siteId = (String)state.getAttribute(STATE_CONTEXT_STRING);
List<String> accessList = new Vector<String>();
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(siteId));
Set<Role> roles = realm.getRoles();
for(Iterator iRoles = roles.iterator(); iRoles.hasNext();)
{
// iterator through roles first
Role role = (Role) iRoles.next();
if (params.getString("allPurpose_" + role.getId()) != null)
{
accessList.add(role.getId());
}
else
{
// if the role is not selected, iterate through the users with this role
Set userIds = realm.getUsersHasRole(role.getId());
for(Iterator iUserIds = userIds.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
if (params.getString("allPurpose_" + userId) != null)
{
accessList.add(userId);
}
}
}
}
}
catch (Exception e)
{
M_log.warn(this + ":setNewAssignmentParameters" + e.toString() + "error finding authzGroup for = " + siteId);
}
state.setAttribute(ALLPURPOSE_ACCESS, accessList);
if (allPurposeTitle != null || allPurposeText != null || (accessList != null && !accessList.isEmpty()) || state.getAttribute(ALLPURPOSE_ATTACHMENTS) != null)
{
// there is allpupose item input
state.setAttribute(ALLPURPOSE, Boolean.TRUE);
if (validify && !"true".equalsIgnoreCase(allPurpose_to_delete))
{
if (allPurposeTitle == null)
{
// missing title
addAlert(state, rb.getString("allPurpose.alert.title"));
}
if (allPurposeText == null)
{
// missing text
addAlert(state, rb.getString("allPurpose.alert.text"));
}
if (accessList == null || accessList.isEmpty())
{
// missing access choice
addAlert(state, rb.getString("allPurpose.alert.access"));
}
}
}
else
{
state.removeAttribute(ALLPURPOSE);
}
}
/**
* read time input and assign it to state attributes
* @param params
* @param state
* @param monthString
* @param dayString
* @param yearString
* @param hourString
* @param minString
* @param ampmString
* @param invalidBundleMessage
* @return
*/
Time putTimeInputInState(ParameterParser params, SessionState state, String monthString, String dayString, String yearString, String hourString, String minString, String ampmString, String invalidBundleMessage)
{
int month = (Integer.valueOf(params.getString(monthString))).intValue();
state.setAttribute(monthString, Integer.valueOf(month));
int day = (Integer.valueOf(params.getString(dayString))).intValue();
state.setAttribute(dayString, Integer.valueOf(day));
int year = (Integer.valueOf(params.getString(yearString))).intValue();
state.setAttribute(yearString, Integer.valueOf(year));
int hour = (Integer.valueOf(params.getString(hourString))).intValue();
state.setAttribute(hourString, Integer.valueOf(hour));
int min = (Integer.valueOf(params.getString(minString))).intValue();
state.setAttribute(minString, Integer.valueOf(min));
String ampm = params.getString(ampmString);
state.setAttribute(ampmString, ampm);
if (("PM".equals(ampm)) && (hour != 12))
{
hour = hour + 12;
}
if ((hour == 12) && ("AM".equals(ampm)))
{
hour = 0;
}
// validate date
if (!Validator.checkDate(day, month, year))
{
addAlert(state, rb.getFormattedMessage("date.invalid", new Object[]{rb.getString(invalidBundleMessage)}));
}
return TimeService.newTimeLocal(year, month, day, hour, min, 0, 0);
}
/**
* Action is to hide the preview assignment student view
*/
public void doHide_submission_assignment_instruction(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false));
// save user input
readGradeForm(data, state, "read");
} // doHide_preview_assignment_student_view
/**
* Action is to show the preview assignment student view
*/
public void doShow_submission_assignment_instruction(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true));
// save user input
readGradeForm(data, state, "read");
} // doShow_submission_assignment_instruction
/**
* Action is to hide the preview assignment student view
*/
public void doHide_preview_assignment_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(true));
} // doHide_preview_assignment_student_view
/**
* Action is to show the preview assignment student view
*/
public void doShow_preview_assignment_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(false));
} // doShow_preview_assignment_student_view
/**
* Action is to hide the preview assignment assignment infos
*/
public void doHide_preview_assignment_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(true));
} // doHide_preview_assignment_assignment
/**
* Action is to show the preview assignment assignment info
*/
public void doShow_preview_assignment_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false));
} // doShow_preview_assignment_assignment
/**
* Action is to hide the assignment content in the view assignment page
*/
public void doHide_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(true));
} // doHide_view_assignment
/**
* Action is to show the assignment content in the view assignment page
*/
public void doShow_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(false));
} // doShow_view_assignment
/**
* Action is to hide the student view in the view assignment page
*/
public void doHide_view_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(true));
} // doHide_view_student_view
/**
* Action is to show the student view in the view assignment page
*/
public void doShow_view_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(false));
} // doShow_view_student_view
/**
* Action is to post assignment
*/
public void doPost_assignment(RunData data)
{
// post assignment
post_save_assignment(data, "post");
} // doPost_assignment
/**
* Action is to tag items via an items tagging helper
*/
public void doHelp_items(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String activityRef = params.getString(ACTIVITY_REF);
TaggingHelperInfo helperInfo = provider
.getItemsHelperInfo(activityRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (Iterator<String> keys = helperParms.keySet().iterator(); keys
.hasNext();) {
String key = keys.next();
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_items
/**
* Action is to tag an individual item via an item tagging helper
*/
public void doHelp_item(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String itemRef = params.getString(ITEM_REF);
TaggingHelperInfo helperInfo = provider
.getItemHelperInfo(itemRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (Iterator<String> keys = helperParms.keySet().iterator(); keys
.hasNext();) {
String key = keys.next();
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_item
/**
* Action is to tag an activity via an activity tagging helper
*/
public void doHelp_activity(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String activityRef = params.getString(ACTIVITY_REF);
TaggingHelperInfo helperInfo = provider
.getActivityHelperInfo(activityRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (String key : helperParms.keySet()) {
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_activity
/**
* post or save assignment
*/
private void post_save_assignment(RunData data, String postOrSave)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING);
boolean post = (postOrSave != null) && "post".equals(postOrSave);
// assignment old title
String aOldTitle = null;
// assignment old associated Gradebook entry if any
String oAssociateGradebookAssignment = null;
String mode = (String) state.getAttribute(STATE_MODE);
if (!MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode))
{
// read input data if the mode is not preview mode
setNewAssignmentParameters(data, true);
}
String assignmentId = params.getString("assignmentId");
String assignmentContentId = params.getString("assignmentContentId");
// whether this is an editing which changes non-electronic assignment to any other type?
boolean bool_change_from_non_electronic = false;
// whether this is an editing which changes non-point graded assignment to point graded assignment?
boolean bool_change_from_non_point = false;
// whether there is a change in the assignment resubmission choice
boolean bool_change_resubmit_option = false;
if (state.getAttribute(STATE_MESSAGE) == null)
{
// AssignmentContent object
AssignmentContentEdit ac = editAssignmentContent(assignmentContentId, "post_save_assignment", state, true);
bool_change_from_non_electronic = change_from_non_electronic(state, assignmentId, assignmentContentId, ac);
bool_change_from_non_point = change_from_non_point(state, assignmentId, assignmentContentId, ac);
// Assignment
AssignmentEdit a = editAssignment(assignmentId, "post_save_assignment", state, true);
bool_change_resubmit_option = change_resubmit_option(state, a);
// put the names and values into vm file
String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE);
String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER);
// open time
Time openTime = getTimeFromState(state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM);
// due time
Time dueTime = getTimeFromState(state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM);
// close time
Time closeTime = dueTime;
boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue();
if (enableCloseDate)
{
closeTime = getTimeFromState(state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM);
}
// sections
String section = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION);
int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue();
int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue();
String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION);
String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null;
String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ;
long category = state.getAttribute(NEW_ASSIGNMENT_CATEGORY) != null ? ((Long) state.getAttribute(NEW_ASSIGNMENT_CATEGORY)).longValue() : -1;
String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null;
if (ac != null && ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// resubmit option is not allowed for non-electronic type
allowResubmitNumber = null;
}
boolean useReviewService = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE));
boolean allowStudentViewReport = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW));
// the attachments
List attachments = (List) state.getAttribute(NEW_ASSIGNMENT_ATTACHMENT);
// set group property
String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE);
Collection groups = new Vector();
try
{
Site site = SiteService.getSite(siteId);
Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS);
if (Assignment.AssignmentAccess.GROUPED.equals(range) && (groupChoice == null || groupChoice.size() == 0))
{
// show alert if no group is selected for the group access assignment
addAlert(state, rb.getString("java.alert.youchoosegroup"));
}
else if (groupChoice != null)
{
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupId = (String) iGroups.next();
groups.add(site.getGroup(groupId));
}
}
}
catch (Exception e)
{
M_log.warn(this + ":post_save_assignment " + e.getMessage());
}
if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null))
{
aOldTitle = a.getTitle();
// old open time
Time oldOpenTime = a.getOpenTime();
// old due time
Time oldDueTime = a.getDueTime();
// commit the changes to AssignmentContent object
commitAssignmentContentEdit(state, ac, title, submissionType,useReviewService,allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments);
// set the Assignment Properties object
ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit();
oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
Time resubmitCloseTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit, post, resubmitCloseTime);
// the notification option
if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null)
{
aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
}
// the release grade notification option
if (state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null)
{
aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE));
}
// comment the changes to Assignment object
commitAssignmentEdit(state, post, ac, a, title, openTime, dueTime, closeTime, enableCloseDate, section, range, groups);
if (post)
{
// we need to update the submission
if (bool_change_from_non_electronic || bool_change_from_non_point || bool_change_resubmit_option)
{
List submissions = AssignmentService.getSubmissions(a);
if (submissions != null && submissions.size() >0)
{
// assignment already exist and with submissions
for (Iterator iSubmissions = submissions.iterator(); iSubmissions.hasNext();)
{
AssignmentSubmission s = (AssignmentSubmission) iSubmissions.next();
AssignmentSubmissionEdit sEdit = editSubmission(s.getReference(), "post_save_assignment", state);
if (sEdit != null)
{
ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit();
if (bool_change_from_non_electronic)
{
sEdit.setSubmitted(false);
sEdit.setTimeSubmitted(null);
}
else if (bool_change_from_non_point)
{
// set the grade to be empty for now
sEdit.setGrade("");
sEdit.setGraded(false);
sEdit.setGradeReleased(false);
sEdit.setReturned(false);
}
if (bool_change_resubmit_option)
{
String aAllowResubmitNumber = a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (aAllowResubmitNumber == null || aAllowResubmitNumber.length() == 0 || "0".equals(aAllowResubmitNumber))
{
sPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
sPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
else
{
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME));
}
}
AssignmentService.commitEdit(sEdit);
}
}
}
}
} //if
// save supplement item information
saveAssignmentSupplementItem(state, params, siteId, a);
// set default sorting
setDefaultSort(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// set the state navigation variables
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
resetAssignment(state);
// integrate with other tools only if the assignment is posted
if (post)
{
// add the due date to schedule if the schedule exists
integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit);
// the open date been announced
integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime);
// integrate with Gradebook
try
{
initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range, category);
}
catch (AssignmentHasIllegalPointsException e)
{
addAlert(state, rb.getString("addtogradebook.illegalPoints"));
M_log.warn(this + ":post_save_assignment " + e.getMessage());
}
}
}
} // if
} // if
} // post_save_assignment
/**
* supplement item related information
* @param state
* @param params
* @param siteId
* @param a
*/
private void saveAssignmentSupplementItem(SessionState state,
ParameterParser params, String siteId, AssignmentEdit a) {
// assignment supplement items
String aId = a.getId();
//model answer
if (state.getAttribute(MODELANSWER_TO_DELETE) != null && "true".equals((String) state.getAttribute(MODELANSWER_TO_DELETE)))
{
// to delete the model answer
AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId);
if (mAnswer != null)
m_assignmentSupplementItemService.removeModelAnswer(mAnswer);
}
else if (state.getAttribute(MODELANSWER_TEXT) != null)
{
// edit/add model answer
AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId);
if (mAnswer == null)
{
mAnswer = m_assignmentSupplementItemService.newModelAnswer();
m_assignmentSupplementItemService.saveModelAnswer(mAnswer);
}
mAnswer.setAssignmentId(a.getId());
mAnswer.setText((String) state.getAttribute(MODELANSWER_TEXT));
mAnswer.setShowTo(state.getAttribute(MODELANSWER_SHOWTO) != null ? Integer.parseInt((String) state.getAttribute(MODELANSWER_SHOWTO)) : 0);
mAnswer.setAttachmentSet(getAssignmentSupplementItemAttachment(state, mAnswer, MODELANSWER_ATTACHMENTS));
m_assignmentSupplementItemService.saveModelAnswer(mAnswer);
}
// note
if (state.getAttribute(NOTE_TO_DELETE) != null && "true".equals((String) state.getAttribute(NOTE_TO_DELETE)))
{
// to remove note item
AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId);
if (nNote != null)
m_assignmentSupplementItemService.removeNoteItem(nNote);
}
else if (state.getAttribute(NOTE_TEXT) != null)
{
// edit/add private note
AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId);
if (nNote == null)
nNote = m_assignmentSupplementItemService.newNoteItem();
nNote.setAssignmentId(a.getId());
nNote.setNote((String) state.getAttribute(NOTE_TEXT));
nNote.setShareWith(state.getAttribute(NOTE_SHAREWITH) != null ? Integer.parseInt((String) state.getAttribute(NOTE_SHAREWITH)) : 0);
nNote.setCreatorId(UserDirectoryService.getCurrentUser().getId());
m_assignmentSupplementItemService.saveNoteItem(nNote);
}
// all purpose
if (state.getAttribute(ALLPURPOSE_TO_DELETE) != null && "true".equals((String) state.getAttribute(ALLPURPOSE_TO_DELETE)))
{
// to remove allPurpose item
AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId);
if (nAllPurpose != null)
m_assignmentSupplementItemService.removeAllPurposeItem(nAllPurpose);
}
else if (state.getAttribute(ALLPURPOSE_TITLE) != null)
{
// edit/add private note
AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId);
if (nAllPurpose == null)
{
nAllPurpose = m_assignmentSupplementItemService.newAllPurposeItem();
m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose);
}
nAllPurpose.setAssignmentId(a.getId());
nAllPurpose.setTitle((String) state.getAttribute(ALLPURPOSE_TITLE));
nAllPurpose.setText((String) state.getAttribute(ALLPURPOSE_TEXT));
boolean allPurposeShowFrom = state.getAttribute(ALLPURPOSE_SHOW_FROM) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_FROM)).booleanValue() : false;
boolean allPurposeShowTo = state.getAttribute(ALLPURPOSE_SHOW_TO) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_TO)).booleanValue() : false;
boolean allPurposeHide = state.getAttribute(ALLPURPOSE_HIDE) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_HIDE)).booleanValue() : false;
nAllPurpose.setHide(allPurposeHide);
// save the release and retract dates
if (allPurposeShowFrom && !allPurposeHide)
{
// save release date
Time releaseTime = getTimeFromState(state, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, ALLPURPOSE_RELEASE_AMPM);
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(releaseTime.getTime());
nAllPurpose.setReleaseDate(cal.getTime());
}
else
{
nAllPurpose.setReleaseDate(null);
}
if (allPurposeShowTo && !allPurposeHide)
{
// save retract date
Time retractTime = getTimeFromState(state, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, ALLPURPOSE_RETRACT_AMPM);
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(retractTime.getTime());
nAllPurpose.setRetractDate(cal.getTime());
}
else
{
nAllPurpose.setRetractDate(null);
}
nAllPurpose.setAttachmentSet(getAssignmentSupplementItemAttachment(state, nAllPurpose, ALLPURPOSE_ATTACHMENTS));
// clean the access list first
if (state.getAttribute(ALLPURPOSE_ACCESS) != null)
{
// get the access settings
List<String> accessList = (List<String>) state.getAttribute(ALLPURPOSE_ACCESS);
m_assignmentSupplementItemService.cleanAllPurposeItemAccess(nAllPurpose);
Set<AssignmentAllPurposeItemAccess> accessSet = new HashSet<AssignmentAllPurposeItemAccess>();
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(siteId));
Set<Role> roles = realm.getRoles();
for(Iterator iRoles = roles.iterator(); iRoles.hasNext();)
{
// iterator through roles first
Role r = (Role) iRoles.next();
if (accessList.contains(r.getId()))
{
AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService.newAllPurposeItemAccess();
access.setAccess(r.getId());
access.setAssignmentAllPurposeItem(nAllPurpose);
m_assignmentSupplementItemService.saveAllPurposeItemAccess(access);
accessSet.add(access);
}
else
{
// if the role is not selected, iterate through the users with this role
Set userIds = realm.getUsersHasRole(r.getId());
for(Iterator iUserIds = userIds.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
if (accessList.contains(userId))
{
AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService.newAllPurposeItemAccess();
access.setAccess(userId);
access.setAssignmentAllPurposeItem(nAllPurpose);
m_assignmentSupplementItemService.saveAllPurposeItemAccess(access);
accessSet.add(access);
}
}
}
}
}
catch (Exception e)
{
M_log.warn(this + ":post_save_assignment " + e.toString() + "error finding authzGroup for = " + siteId);
}
nAllPurpose.setAccessSet(accessSet);
}
m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose);
}
}
private Set<AssignmentSupplementItemAttachment> getAssignmentSupplementItemAttachment(SessionState state, AssignmentSupplementItemWithAttachment mItem, String attachmentString) {
Set<AssignmentSupplementItemAttachment> sAttachments = new HashSet<AssignmentSupplementItemAttachment>();
List<String> attIdList = m_assignmentSupplementItemService.getAttachmentListForSupplementItem(mItem);
if (state.getAttribute(attachmentString) != null)
{
List currentAttachments = (List) state.getAttribute(attachmentString);
for (Iterator aIterator = currentAttachments.iterator(); aIterator.hasNext();)
{
Reference attRef = (Reference) aIterator.next();
String attRefId = attRef.getReference();
// if the attachment is not exist, add it into db
if (!attIdList.contains(attRefId))
{
AssignmentSupplementItemAttachment mAttach = m_assignmentSupplementItemService.newAttachment();
mAttach.setAssignmentSupplementItemWithAttachment(mItem);
mAttach.setAttachmentId(attRefId);
m_assignmentSupplementItemService.saveAttachment(mAttach);
sAttachments.add(mAttach);
}
}
}
return sAttachments;
}
/**
*
*/
private boolean change_from_non_electronic(SessionState state, String assignmentId, String assignmentContentId, AssignmentContentEdit ac)
{
// whether this is an editing which changes non-electronic assignment to any other type?
if (StringUtil.trimToNull(assignmentId) != null && StringUtil.trimToNull(assignmentContentId) != null)
{
// editing
if (ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION
&& ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// changing from non-electronic type
return true;
}
}
return false;
}
/**
*
*/
private boolean change_from_non_point(SessionState state, String assignmentId, String assignmentContentId, AssignmentContentEdit ac)
{
// whether this is an editing which changes non point_grade type to point grade type?
if (StringUtil.trimToNull(assignmentId) != null && StringUtil.trimToNull(assignmentContentId) != null)
{
// editing
if (ac.getTypeOfGrade() != Assignment.SCORE_GRADE_TYPE
&& ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue() == Assignment.SCORE_GRADE_TYPE)
{
// changing from non-point grade type to point grade type?
return true;
}
}
return false;
}
/**
* whether the resubmit option has been changed
* @param state
* @param a
* @return
*/
private boolean change_resubmit_option(SessionState state, Entity entity)
{
if (entity != null)
{
// editing
return propertyValueChanged(state, entity, AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) || propertyValueChanged(state, entity, AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
return false;
}
/**
* whether there is a change between state variable and object's property value
* @param state
* @param entity
* @param propertyName
* @return
*/
private boolean propertyValueChanged(SessionState state, Entity entity, String propertyName) {
String o_property_value = entity.getProperties().getProperty(propertyName);
String n_property_value = state.getAttribute(propertyName) != null? (String) state.getAttribute(propertyName):null;
if (o_property_value == null && n_property_value != null
|| o_property_value != null && n_property_value == null
|| o_property_value != null && n_property_value != null && !o_property_value.equals(n_property_value))
{
// there is a change
return true;
}
return false;
}
/**
* default sorting
*/
private void setDefaultSort(SessionState state) {
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
}
/**
* Add submission objects if necessary for non-electronic type of assignment
* @param state
* @param a
*/
private void addRemoveSubmissionsForNonElectronicAssignment(SessionState state, List submissions, HashSet<String> addSubmissionForUsers, HashSet<String> removeSubmissionForUsers, Assignment a)
{
// create submission object for those user who doesn't have one yet
for (Iterator iUserIds = addSubmissionForUsers.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
// only include those users that can submit to this assignment
if (u != null)
{
// construct fake submissions for grading purpose
AssignmentSubmissionEdit submission = AssignmentService.addSubmission(a.getContext(), a.getId(), userId);
submission.setTimeSubmitted(TimeService.newTime());
submission.setSubmitted(true);
submission.setAssignment(a);
AssignmentService.commitEdit(submission);
}
}
catch (Exception e)
{
M_log.warn(this + ":addRemoveSubmissionsForNonElectronicAssignment " + e.toString() + "error adding submission for userId = " + userId);
}
}
// remove submission object for those who no longer in the site
for (Iterator iUserIds = removeSubmissionForUsers.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
String submissionRef = null;
// TODO: we don't have an efficient way to retrieve specific user's submission now, so until then, we still need to iterate the whole submission list
for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext() && submissionRef == null;)
{
AssignmentSubmission submission = (AssignmentSubmission) iSubmissions.next();
List submitterIds = submission.getSubmitterIds();
if (submitterIds != null && submitterIds.size() > 0 && userId.equals((String) submitterIds.get(0)))
{
submissionRef = submission.getReference();
}
}
if (submissionRef != null)
{
AssignmentSubmissionEdit submissionEdit = editSubmission(submissionRef, "addRemoveSubmissionsForNonElectronicAssignment", state);
if (submissionEdit != null)
{
try
{
AssignmentService.removeSubmission(submissionEdit);
}
catch (PermissionException e)
{
addAlert(state, rb.getFormattedMessage("youarenot_removeSubmission", new Object[]{submissionEdit.getReference()}));
M_log.warn(this + ":deleteAssignmentObjects " + e.getMessage() + " " + submissionEdit.getReference());
}
}
}
}
}
private void initIntegrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range, long category) {
GradebookExternalAssessmentService gExternal = (GradebookExternalAssessmentService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService");
String context = (String) state.getAttribute(STATE_CONTEXT_STRING);
boolean gradebookExists = isGradebookDefined();
// only if the gradebook is defined
if (gradebookExists)
{
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
String aReference = a.getReference();
String addUpdateRemoveAssignment = "remove";
if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// if integrate with Gradebook
if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && ("groups".equals(range)))
{
// if grouped assignment is not allowed to add into Gradebook
addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB"));
String ref = a.getReference();
AssignmentEdit aEdit = editAssignment(a.getReference(), "initINtegrateWithGradebook", state, false);
if (aEdit != null)
{
aEdit.getPropertiesEdit().removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
AssignmentService.commitEdit(aEdit);
}
integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null, category);
}
else
{
if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD))
{
addUpdateRemoveAssignment = AssignmentService.GRADEBOOK_INTEGRATION_ADD;
}
else if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE))
{
addUpdateRemoveAssignment = "update";
}
if (!"remove".equals(addUpdateRemoveAssignment) && gradeType == 3)
{
try
{
integrateGradebook(state, aReference, associateGradebookAssignment, addUpdateRemoveAssignment, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, null, category);
// add all existing grades, if any, into Gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update", category);
// if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook
if (StringUtil.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment))
{
// if the old assoicated assignment entry in GB is an external one, but doesn't have anything assoicated with it in Assignment tool, remove it
removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,gExternal, gradebookUid);
}
}
catch (NumberFormatException nE)
{
alertInvalidPoint(state, gradePoints);
M_log.warn(this + ":initIntegrateWithGradebook " + nE.getMessage());
}
}
else
{
integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null, category);
}
}
}
else
{
// need to remove the associated gradebook entry if 1) it is external and 2) no other assignment are associated with it
removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,gExternal, gradebookUid);
}
}
}
private void removeNonAssociatedExternalGradebookEntry(String context, String assignmentReference, String associateGradebookAssignment, GradebookExternalAssessmentService gExternal, String gradebookUid) {
boolean isExternalAssignmentDefined=gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment);
if (isExternalAssignmentDefined)
{
// iterate through all assignments currently in the site, see if any is associated with this GB entry
Iterator i = AssignmentService.getAssignmentsForContext(context);
boolean found = false;
while (!found && i.hasNext())
{
Assignment aI = (Assignment) i.next();
String gbEntry = aI.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (aI.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED) == null && gbEntry != null && gbEntry.equals(associateGradebookAssignment) && !aI.getReference().equals(assignmentReference))
{
found = true;
}
}
// so if none of the assignment in this site is associated with the entry, remove the entry
if (!found)
{
gExternal.removeExternalAssessment(gradebookUid, associateGradebookAssignment);
}
}
}
private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime)
{
if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString()))
{
AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL);
if (channel != null)
{
// whether the assignment's title or open date has been updated
boolean updatedTitle = false;
boolean updatedOpenDate = false;
String openDateAnnounced = StringUtil.trimToNull(a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED));
String openDateAnnouncementId = StringUtil.trimToNull(a.getPropertiesEdit().getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID));
if (openDateAnnounced != null && openDateAnnouncementId != null)
{
try
{
AnnouncementMessage message = channel.getAnnouncementMessage(openDateAnnouncementId);
if (!message.getAnnouncementHeader().getSubject().contains(title))/*whether title has been changed*/
{
updatedTitle = true;
}
if (!message.getBody().contains(openTime.toStringLocalFull())) /*whether open date has been changed*/
{
updatedOpenDate = true;
}
}
catch (IdUnusedException e)
{
M_log.warn(this + ":integrateWithAnnouncement " + e.getMessage());
}
catch (PermissionException e)
{
M_log.warn(this + ":integrateWithAnnouncement " + e.getMessage());
}
}
// need to create announcement message if assignment is added or assignment has been updated
if (openDateAnnounced == null || updatedTitle || updatedOpenDate)
{
try
{
AnnouncementMessageEdit message = channel.addAnnouncementMessage();
if (message != null)
{
AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit();
header.setDraft(/* draft */false);
header.replaceAttachments(/* attachment */EntityManager.newReferenceList());
if (openDateAnnounced == null)
{
// making new announcement
header.setSubject(/* subject */rb.getFormattedMessage("assig6", new Object[]{title}));
}
else
{
// updated title
header.setSubject(/* subject */rb.getFormattedMessage("assig5", new Object[]{title}));
}
if (updatedOpenDate)
{
// revised assignment open date
message.setBody(/* body */rb.getFormattedMessage("newope", new Object[]{FormattedText.convertPlaintextToFormattedText(title), openTime.toStringLocalFull()}));
}
else
{
// assignment open date
message.setBody(/* body */rb.getFormattedMessage("opedat", new Object[]{FormattedText.convertPlaintextToFormattedText(title), openTime.toStringLocalFull()}));
}
// group information
if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED))
{
try
{
// get the group ids selected
Collection groupRefs = a.getGroups();
// make a collection of Group objects
Collection groups = new Vector();
//make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();)
{
String groupRef = (String) iGroupRefs.next();
groups.add(site.getGroup(groupRef));
}
// set access
header.setGroupAccess(groups);
}
catch (Exception exception)
{
// log
M_log.warn(this + ":integrateWithAnnouncement " + exception.getMessage());
}
}
else
{
// site announcement
header.clearGroupAccess();
}
channel.commitMessage(message, m_notificationService.NOTI_NONE);
}
// commit related properties into Assignment object
AssignmentEdit aEdit = editAssignment(a.getReference(), "integrateWithAnnouncement", state, false);
if (aEdit != null)
{
aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString());
if (message != null)
{
aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId());
}
AssignmentService.commitEdit(aEdit);
}
}
catch (PermissionException ee)
{
M_log.warn(this + ":IntegrateWithAnnouncement " + rb.getString("cannotmak"));
}
}
}
} // if
}
private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit)
{
Calendar c = (Calendar) state.getAttribute(CALENDAR);
if (c != null)
{
String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
String oldEventId = aPropertiesEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
CalendarEvent e = null;
if (dueDateScheduled != null || oldEventId != null)
{
// find the old event
boolean found = false;
if (oldEventId != null)
{
try
{
e = c.getEvent(oldEventId);
found = true;
}
catch (IdUnusedException ee)
{
M_log.warn(this + ":integrateWithCalender The old event has been deleted: event id=" + oldEventId + ". ");
}
catch (PermissionException ee)
{
M_log.warn(this + ":integrateWithCalender You do not have the permission to view the schedule event id= "
+ oldEventId + ".");
}
}
else
{
TimeBreakdown b = oldDueTime.breakdownLocal();
// TODO: check- this was new Time(year...), not local! -ggolden
Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0);
Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999);
try
{
Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null)
.iterator();
while ((!found) && (events.hasNext()))
{
e = (CalendarEvent) events.next();
if (((String) e.getDisplayName()).indexOf(rb.getString("gen.assig") + " " + title) != -1)
{
found = true;
}
}
}
catch (PermissionException ignore)
{
// ignore PermissionException
}
}
if (found)
{
// remove the founded old event
try
{
c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
}
catch (PermissionException ee)
{
M_log.warn(this + ":integrateWithCalender " + rb.getFormattedMessage("cannotrem", new Object[]{title}));
}
catch (InUseException ee)
{
M_log.warn(this + ":integrateWithCalender " + rb.getString("somelsis_calendar"));
}
catch (IdUnusedException ee)
{
M_log.warn(this + ":integrateWithCalender " + rb.getFormattedMessage("cannotfin6", new Object[]{e.getId()}));
}
}
}
if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString()))
{
// commit related properties into Assignment object
AssignmentEdit aEdit = editAssignment(a.getReference(), "integrateWithCalendar", state, false);
if (aEdit != null)
{
try
{
e = null;
CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE;
Collection eGroups = new Vector();
if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED))
{
eAccess = CalendarEvent.EventAccess.GROUPED;
Collection groupRefs = aEdit.getGroups();
// make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();)
{
String groupRef = (String) iGroupRefs.next();
eGroups.add(site.getGroup(groupRef));
}
}
e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000),
/* title */rb.getString("gen.due") + " " + title,
/* description */rb.getFormattedMessage("assign_due_event_desc", new Object[]{title, dueTime.toStringLocalFull()}),
/* type */rb.getString("deadl"),
/* location */"",
/* access */ eAccess,
/* groups */ eGroups,
/* attachments */EntityManager.newReferenceList());
aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString());
if (e != null)
{
aEdit.getProperties().addProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID, e.getId());
// edit the calendar ojbject and add an assignment id field
CalendarEventEdit edit = c.getEditEvent(e.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_ADD_CALENDAR);
edit.setField(AssignmentConstants.NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID, a.getId());
c.commitEvent(edit);
}
// TODO do we care if the event is null?
}
catch (IdUnusedException ee)
{
M_log.warn(this + ":integrateWithCalender " + ee.getMessage());
}
catch (PermissionException ee)
{
M_log.warn(this + ":integrateWithCalender " + rb.getString("cannotfin1"));
}
catch (Exception ee)
{
M_log.warn(this + ":integrateWithCalender " + ee.getMessage());
}
// try-catch
AssignmentService.commitEdit(aEdit);
}
} // if
}
}
private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups)
{
a.setTitle(title);
a.setContent(ac);
a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING));
a.setSection(s);
a.setOpenTime(openTime);
a.setDueTime(dueTime);
// set the drop dead date as the due date
a.setDropDeadTime(dueTime);
if (enableCloseDate)
{
a.setCloseTime(closeTime);
}
else
{
// if editing an old assignment with close date
if (a.getCloseTime() != null)
{
a.setCloseTime(null);
}
}
// post the assignment
a.setDraft(!post);
try
{
if ("site".equals(range))
{
a.setAccess(Assignment.AssignmentAccess.SITE);
a.clearGroupAccess();
}
else if ("groups".equals(range))
{
a.setGroupAccess(groups);
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot1"));
M_log.warn(this + ":commitAssignmentEdit " + rb.getString("youarenot1") + e.getMessage());
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// commit assignment first
AssignmentService.commitEdit(a);
}
}
private void editAssignmentProperties(AssignmentEdit a, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit, boolean post, Time closeTime)
{
if (aPropertiesEdit.getProperty("newAssignment") != null)
{
if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString()))
{
// not a newly created assignment, been added.
aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString());
}
}
else
{
// for newly created assignment
aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString());
}
if (checkAddDueTime != null)
{
aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime);
}
else
{
aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
}
aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce);
aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook);
aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment);
if (post && addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD))
{
// if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then
aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE);
aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, a.getReference());
}
// allow resubmit number and default assignment resubmit closeTime (dueTime)
if (allowResubmitNumber != null && closeTime != null)
{
aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber);
aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
}
else if (allowResubmitNumber == null || allowResubmitNumber.length() == 0 || "0".equals(allowResubmitNumber))
{
aPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
aPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
}
private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String title, int submissionType,boolean useReviewService, boolean allowStudentViewReport, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments)
{
ac.setTitle(title);
ac.setInstructions(description);
ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge));
ac.setTypeOfSubmission(submissionType);
ac.setAllowReviewService(useReviewService);
ac.setAllowStudentViewReport(allowStudentViewReport);
ac.setTypeOfGrade(gradeType);
if (gradeType == 3)
{
try
{
ac.setMaxGradePoint(Integer.parseInt(gradePoints));
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, gradePoints);
M_log.warn(this + ":commitAssignmentContentEdit " + e.getMessage());
}
}
ac.setGroupProject(true);
ac.setIndividuallyGraded(false);
if (submissionType != 1)
{
ac.setAllowAttachments(true);
}
else
{
ac.setAllowAttachments(false);
}
// clear attachments
ac.clearAttachments();
if (attachments != null)
{
// add each attachment
Iterator it = EntityManager.newReferenceList(attachments).iterator();
while (it.hasNext())
{
Reference r = (Reference) it.next();
ac.addAttachment(r);
}
}
state.setAttribute(ATTACHMENTS_MODIFIED, Boolean.valueOf(false));
// commit the changes
AssignmentService.commitEdit(ac);
}
/**
* reorderAssignments
*/
private void reorderAssignments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List assignments = prepPage(state);
Iterator it = assignments.iterator();
// temporarily allow the user to read and write from assignments (asn.revise permission)
enableSecurityAdvisor();
while (it.hasNext()) // reads and writes the parameter for default ordering
{
Assignment a = (Assignment) it.next();
String assignmentid = a.getId();
String assignmentposition = params.getString("position_" + assignmentid);
AssignmentEdit ae = editAssignment(assignmentid, "reorderAssignments", state, true);
if (ae != null)
{
ae.setPosition_order(Long.valueOf(assignmentposition).intValue());
AssignmentService.commitEdit(ae);
}
}
// clear the permission
disableSecurityAdvisor();
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
} // reorderAssignments
private AssignmentContentEdit editAssignmentContent(String assignmentContentId, String callingFunctionName, SessionState state, boolean allowAdd)
{
AssignmentContentEdit ac = null;
if (assignmentContentId.length() == 0 && allowAdd)
{
// new assignment
try
{
ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot_addAssignmentContent"));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + (String) state.getAttribute(STATE_CONTEXT_STRING));
}
}
else
{
try
{
// edit assignment
ac = AssignmentService.editAssignmentContent(assignmentContentId);
}
catch (InUseException e)
{
addAlert(state, rb.getFormattedMessage("somelsis_assignmentContent", new Object[]{assignmentContentId}));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage());
}
catch (IdUnusedException e)
{
addAlert(state, rb.getFormattedMessage("cannotfin_assignmentContent", new Object[]{assignmentContentId}));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage());
}
catch (PermissionException e)
{
addAlert(state, rb.getFormattedMessage("youarenot_viewAssignmentContent", new Object[]{assignmentContentId}));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage());
}
}
return ac;
}
/**
* construct time object based on various state variables
* @param state
* @param monthString
* @param dayString
* @param yearString
* @param hourString
* @param minString
* @param ampmString
* @return
*/
private Time getTimeFromState(SessionState state, String monthString, String dayString, String yearString, String hourString, String minString, String ampmString)
{
if (state.getAttribute(monthString) != null ||
state.getAttribute(dayString) != null ||
state.getAttribute(yearString) != null ||
state.getAttribute(hourString) != null ||
state.getAttribute(minString) != null ||
state.getAttribute(ampmString) != null)
{
int month = ((Integer) state.getAttribute(monthString)).intValue();
int day = ((Integer) state.getAttribute(dayString)).intValue();
int year = ((Integer) state.getAttribute(yearString)).intValue();
int hour = ((Integer) state.getAttribute(hourString)).intValue();
int min = ((Integer) state.getAttribute(minString)).intValue();
String ampm = (String) state.getAttribute(ampmString);
if (("PM".equals(ampm)) && (hour != 12))
{
hour = hour + 12;
}
if ((hour == 12) && ("AM".equals(ampm)))
{
hour = 0;
}
return TimeService.newTimeLocal(year, month, day, hour, min, 0, 0);
}
else
{
return null;
}
}
/**
* Action is to post new assignment
*/
public void doSave_assignment(RunData data)
{
post_save_assignment(data, "save");
} // doSave_assignment
/**
* Action is to reorder assignments
*/
public void doReorder_assignment(RunData data)
{
reorderAssignments(data);
} // doReorder_assignments
/**
* Action is to preview the selected assignment
*/
public void doPreview_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
setNewAssignmentParameters(data, true);
String assignmentId = data.getParameters().getString("assignmentId");
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId);
String assignmentContentId = data.getParameters().getString("assignmentContentId");
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId);
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false));
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(true));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT);
}
} // doPreview_assignment
/**
* Action is to view the selected assignment
*/
public void doView_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// show the assignment portion
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(false));
// show the student view portion
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(true));
String assignmentId = params.getString("assignmentId");
state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId);
Assignment a = getAssignment(assignmentId, "doView_assignment", state);
// get resubmission option into state
assignment_resubmission_option_into_state(a, null, state);
// assignment read event
m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, assignmentId, false));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT);
}
} // doView_Assignment
/**
* Action is for student to view one assignment content
*/
public void doView_assignment_as_student(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = params.getString("assignmentId");
state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT);
}
} // doView_assignment_as_student
/**
* Action is to show the edit assignment screen
*/
public void doEdit_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = StringUtil.trimToNull(params.getString("assignmentId"));
if (AssignmentService.allowUpdateAssignment(assignmentId))
{
// whether the user can modify the assignment
state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId);
Assignment a = getAssignment(assignmentId, "doEdit_assignment", state);
if (a != null)
{
// for the non_electronice assignment, submissions are auto-generated by the time that assignment is created;
// don't need to go through the following checkings.
if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
if (submissions.hasNext())
{
// any submitted?
boolean anySubmitted = false;
for (;submissions.hasNext() && !anySubmitted;)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getSubmitted() && s.getTimeSubmitted() != null)
{
anySubmitted = true;
}
}
// any draft submission
boolean anyDraft = false;
for (;submissions.hasNext() && !anyDraft;)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (!s.getSubmitted())
{
anyDraft = true;
}
}
if (anySubmitted)
{
// if there is any submitted submission to this assignment, show alert
addAlert(state, rb.getString("gen.assig") + " " + a.getTitle() + " " + rb.getString("hassum"));
}
if (anyDraft)
{
// otherwise, show alert about someone has started working on the assignment, not necessarily submitted
addAlert(state, rb.getString("hasDraftSum"));
}
}
}
// SECTION MOD
state.setAttribute(STATE_SECTION_STRING, a.getSection());
// put the names and values into vm file
state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle());
state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order());
putTimePropertiesInState(state, a.getOpenTime(), NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM);
// generate alert when editing an assignment past open date
if (a.getOpenTime().before(TimeService.newTime()))
{
addAlert(state, rb.getString("youarenot20"));
}
putTimePropertiesInState(state, a.getDueTime(), NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM);
// generate alert when editing an assignment past due date
if (a.getDueTime().before(TimeService.newTime()))
{
addAlert(state, rb.getString("youarenot17"));
}
if (a.getCloseTime() != null)
{
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true));
putTimePropertiesInState(state, a.getCloseTime(), NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM);
}
else
{
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(false));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR));
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN));
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, state.getAttribute(NEW_ASSIGNMENT_DUEAMPM));
}
state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection());
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(a.getContent().getTypeOfSubmission()));
state.setAttribute(NEW_ASSIGNMENT_CATEGORY, getAssignmentCategoryAsInt(a));
int typeOfGrade = a.getContent().getTypeOfGrade();
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(typeOfGrade));
if (typeOfGrade == 3)
{
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay());
}
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions());
ResourceProperties properties = a.getProperties();
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty(
ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty(
ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge()));
state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
state.setAttribute(ATTACHMENTS, a.getContent().getAttachments());
// submission notification option
if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null)
{
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
}
// release grade notification option
if (properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null)
{
state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE));
}
// group setting
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
state.setAttribute(NEW_ASSIGNMENT_RANGE, "site");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups");
}
// put the resubmission option into state
assignment_resubmission_option_into_state(a, null, state);
// set whether we use the review service or not
state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, Boolean.valueOf(a.getContent().getAllowReviewService()).toString());
//set whether students can view the review service results
state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, Boolean.valueOf(a.getContent().getAllowStudentViewReport()).toString());
state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups());
// get all supplement item info into state
setAssignmentSupplementItemInState(state, a);
}
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot6"));
}
} // doEdit_Assignment
/**
* put all assignment supplement item info into state
* @param state
* @param a
*/
private void setAssignmentSupplementItemInState(SessionState state, Assignment a) {
String assignmentId = a.getId();
// model answer
AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(assignmentId);
if (mAnswer != null)
{
if (state.getAttribute(MODELANSWER_TEXT) == null)
{
state.setAttribute(MODELANSWER_TEXT, mAnswer.getText());
}
if (state.getAttribute(MODELANSWER_SHOWTO) == null)
{
state.setAttribute(MODELANSWER_SHOWTO, String.valueOf(mAnswer.getShowTo()));
}
if (state.getAttribute(MODELANSWER) == null)
{
state.setAttribute(MODELANSWER, Boolean.TRUE);
}
}
// get attachments for model answer object
putSupplementItemAttachmentInfoIntoState(state, mAnswer, MODELANSWER_ATTACHMENTS);
// private notes
AssignmentNoteItem mNote = m_assignmentSupplementItemService.getNoteItem(assignmentId);
if (mNote != null)
{
if (state.getAttribute(NOTE) == null)
{
state.setAttribute(NOTE, Boolean.TRUE);
}
if (state.getAttribute(NOTE_TEXT) == null)
{
state.setAttribute(NOTE_TEXT, mNote.getNote());
}
if (state.getAttribute(NOTE_SHAREWITH) == null)
{
state.setAttribute(NOTE_SHAREWITH, String.valueOf(mNote.getShareWith()));
}
}
// all purpose item
AssignmentAllPurposeItem aItem = m_assignmentSupplementItemService.getAllPurposeItem(assignmentId);
if (aItem != null)
{
if (state.getAttribute(ALLPURPOSE) == null)
{
state.setAttribute(ALLPURPOSE, Boolean.TRUE);
}
if (state.getAttribute(ALLPURPOSE_TITLE) == null)
{
state.setAttribute(ALLPURPOSE_TITLE, aItem.getTitle());
}
if (state.getAttribute(ALLPURPOSE_TEXT) == null)
{
state.setAttribute(ALLPURPOSE_TEXT, aItem.getText());
}
if (state.getAttribute(ALLPURPOSE_HIDE) == null)
{
state.setAttribute(ALLPURPOSE_HIDE, Boolean.valueOf(aItem.getHide()));
}
if (state.getAttribute(ALLPURPOSE_SHOW_FROM) == null)
{
state.setAttribute(ALLPURPOSE_SHOW_FROM, aItem.getReleaseDate() != null);
}
if (state.getAttribute(ALLPURPOSE_SHOW_TO) == null)
{
state.setAttribute(ALLPURPOSE_SHOW_TO, aItem.getRetractDate() != null);
}
if (state.getAttribute(ALLPURPOSE_ACCESS) == null)
{
Set<AssignmentAllPurposeItemAccess> aSet = aItem.getAccessSet();
List<String> aList = new Vector<String>();
for(Iterator<AssignmentAllPurposeItemAccess> aIterator = aSet.iterator(); aIterator.hasNext();)
{
AssignmentAllPurposeItemAccess access = aIterator.next();
aList.add(access.getAccess());
}
state.setAttribute(ALLPURPOSE_ACCESS, aList);
}
// get attachments for model answer object
putSupplementItemAttachmentInfoIntoState(state, aItem, ALLPURPOSE_ATTACHMENTS);
}
// get the AllPurposeItem and AllPurposeReleaseTime/AllPurposeRetractTime
//default to assignment open time
Time releaseTime = a.getOpenTime();
// default to assignment close time
Time retractTime = a.getCloseTime();
if (aItem != null)
{
Date releaseDate = aItem.getReleaseDate();
if (releaseDate != null)
{
// overwrite if there is a release date
releaseTime = TimeService.newTime(releaseDate.getTime());
}
Date retractDate = aItem.getRetractDate();
if (retractDate != null)
{
// overwriteif there is a retract date
retractTime = TimeService.newTime(retractDate.getTime());
}
}
putTimePropertiesInState(state, releaseTime, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, ALLPURPOSE_RELEASE_AMPM);
putTimePropertiesInState(state, retractTime, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, ALLPURPOSE_RETRACT_AMPM);
}
/**
* Action is to show the delete assigment confirmation screen
*/
public void doDelete_confirm_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String[] assignmentIds = params.getStrings("selectedAssignments");
if (assignmentIds != null)
{
Vector ids = new Vector();
for (int i = 0; i < assignmentIds.length; i++)
{
String id = (String) assignmentIds[i];
if (!AssignmentService.allowRemoveAssignment(id))
{
addAlert(state, rb.getFormattedMessage("youarenot_removeAssignment", new Object[]{id}));
}
ids.add(id);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// can remove all the selected assignments
state.setAttribute(DELETE_ASSIGNMENT_IDS, ids);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT);
}
}
else
{
addAlert(state, rb.getString("youmust6"));
}
} // doDelete_confirm_Assignment
/**
* Action is to delete the confirmed assignments
*/
public void doDelete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the delete assignment ids
Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < ids.size(); i++)
{
String assignmentId = (String) ids.get(i);
AssignmentEdit aEdit = editAssignment(assignmentId, "doDelete_assignment", state, false);
if (aEdit != null)
{
if (state.getAttribute(STATE_MESSAGE) == null)
{
ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit();
String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (state.getAttribute(STATE_MESSAGE) == null)
{
String title = aEdit.getTitle();
// remove related event if there is one
removeCalendarEvent(state, aEdit, pEdit, title);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// remove related announcement if there is one
removeAnnouncement(state, pEdit);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// we use to check "assignment.delete.cascade.submission" setting. But the implementation now is always remove submission objects when the assignment is removed.
// delete assignment and its submissions altogether
deleteAssignmentObjects(state, aEdit, true);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// remove from Gradebook
integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null, -1);
}
}
}
}
}
}
} // for
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
// reset paging information after the assignment been deleted
resetPaging(state);
}
} // doDelete_Assignment
/**
* private function to remove assignment related announcement
* @param state
* @param pEdit
*/
private void removeAnnouncement(SessionState state,
ResourcePropertiesEdit pEdit) {
AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL);
if (channel != null)
{
String openDateAnnounced = StringUtil.trimToNull(pEdit.getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED));
String openDateAnnouncementId = StringUtil.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(this + ":removeAnnouncement " + e.getMessage());
}
}
}
}
/**
* private method to remove assignment and related objects
* @param state
* @param aEdit
* @param removeSubmissions Whether or not to remove the submission objects
*/
private void deleteAssignmentObjects(SessionState state, AssignmentEdit aEdit, boolean removeSubmissions) {
if (removeSubmissions)
{
// if this is non-electronic submission, remove all the submissions
List submissions = AssignmentService.getSubmissions(aEdit);
if (submissions != null)
{
for (Iterator sIterator=submissions.iterator(); sIterator.hasNext();)
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
AssignmentSubmissionEdit sEdit = editSubmission((s.getReference()), "deleteAssignmentObjects", state);
try
{
AssignmentService.removeSubmission(sEdit);
}
catch (Exception eee)
{
addAlert(state, rb.getFormattedMessage("youarenot_removeSubmission", new Object[]{s.getReference()}));
M_log.warn(this + ":deleteAssignmentObjects " + eee.getMessage() + " " + s.getReference());
}
}
}
}
AssignmentContent aContent = aEdit.getContent();
if (aContent != null)
{
try
{
// remove the assignment content
AssignmentContentEdit acEdit = editAssignmentContent(aContent.getReference(), "deleteAssignmentObjects", state, false);
if (acEdit != null)
AssignmentService.removeAssignmentContent(acEdit);
}
catch (Exception ee)
{
addAlert(state, rb.getString("youarenot11_c") + " " + aEdit.getContentReference() + ". ");
M_log.warn(this + ":deleteAssignmentObjects " + ee.getMessage());
}
}
try
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
if (taggingManager.isTaggable()) {
for (TaggingProvider provider : taggingManager
.getProviders()) {
provider.removeTags(assignmentActivityProducer
.getActivity(aEdit));
}
}
AssignmentService.removeAssignment(aEdit);
}
catch (PermissionException ee)
{
addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". ");
M_log.warn(this + ":deleteAssignmentObjects " + ee.getMessage());
}
}
private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title)
{
String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString()))
{
// remove the associated calendar event
Calendar c = (Calendar) state.getAttribute(CALENDAR);
if (c != null)
{
// already has calendar object
// get the old event
CalendarEvent e = null;
boolean found = false;
String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
if (oldEventId != null)
{
try
{
e = c.getEvent(oldEventId);
found = true;
}
catch (IdUnusedException ee)
{
// no action needed for this condition
M_log.warn(this + ":removeCalendarEvent " + ee.getMessage());
}
catch (PermissionException ee)
{
M_log.warn(this + ":removeCalendarEvent " + ee.getMessage());
}
}
else
{
TimeBreakdown b = aEdit.getDueTime().breakdownLocal();
// TODO: check- this was new Time(year...), not local! -ggolden
Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0);
Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999);
try
{
Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator();
while ((!found) && (events.hasNext()))
{
e = (CalendarEvent) events.next();
if (((String) e.getDisplayName()).indexOf(rb.getString("gen.assig") + " " + title) != -1)
{
found = true;
}
}
}
catch (PermissionException pException)
{
addAlert(state, rb.getFormattedMessage("cannot_getEvents", new Object[]{c.getReference()}));
}
}
// remove the founded old event
if (found)
{
// found the old event delete it
try
{
c.removeEvent(c.getEditEvent(e.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(this + ":removeCalendarEvent " + rb.getFormattedMessage("cannotrem", new Object[]{title}));
}
catch (InUseException ee)
{
M_log.warn(this + ":removeCalendarEvent " + rb.getString("somelsis_calendar"));
}
catch (IdUnusedException ee)
{
M_log.warn(this + ":removeCalendarEvent " + rb.getFormattedMessage("cannotfin6", new Object[]{e.getId()}));
}
}
}
}
}
/**
* Action is to delete the assignment and also the related AssignmentSubmission
*/
public void doDeep_delete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the delete assignment ids
Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < ids.size(); i++)
{
String currentId = (String) ids.get(i);
AssignmentEdit a = editAssignment(currentId, "doDeep_delete_assignment", state, false);
if (a != null)
{
try
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
if (taggingManager.isTaggable()) {
for (TaggingProvider provider : taggingManager
.getProviders()) {
provider.removeTags(assignmentActivityProducer
.getActivity(a));
}
}
AssignmentService.removeAssignment(a);
}
catch (PermissionException e)
{
addAlert(state, rb.getFormattedMessage("youarenot_editAssignment", new Object[]{a.getTitle()}));
M_log.warn(this + ":doDeep_delete_assignment " + e.getMessage());
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
} // doDeep_delete_Assignment
/**
* Action is to show the duplicate assignment screen
*/
public void doDuplicate_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the view, so start with first page again.
resetPaging(state);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
ParameterParser params = data.getParameters();
String assignmentId = StringUtil.trimToNull(params.getString("assignmentId"));
if (assignmentId != null)
{
try
{
AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId);
// clean the duplicate's property
ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit();
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED);
aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID);
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
aPropertiesEdit.removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
AssignmentService.commitEdit(aEdit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot5"));
M_log.warn(this + ":doDuplicate_assignment " + e.getMessage());
}
catch (IdInvalidException e)
{
addAlert(state, rb.getFormattedMessage("theassiid_isnotval", new Object[]{assignmentId}));
M_log.warn(this + ":doDuplicate_assignment " + e.getMessage());
}
catch (IdUnusedException e)
{
addAlert(state, rb.getFormattedMessage("theassiid_hasnotbee", new Object[]{assignmentId}));
M_log.warn(this + ":doDuplicate_assignment " + e.getMessage());
}
catch (Exception e)
{
M_log.warn(this + ":doDuplicate_assignment " + e.getMessage());
}
}
} // doDuplicate_Assignment
/**
* Action is to show the grade submission screen
*/
public void doGrade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the submission context
resetViewSubmission(state);
ParameterParser params = data.getParameters();
String assignmentId = params.getString("assignmentId");
String submissionId = params.getString("submissionId");
// put submission information into state
putSubmissionInfoIntoState(state, assignmentId, submissionId);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false));
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
// assignment read event
m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submissionId, false));
}
} // doGrade_submission
/**
* put all the submission information into state variables
* @param state
* @param assignmentId
* @param submissionId
*/
private void putSubmissionInfoIntoState(SessionState state, String assignmentId, String submissionId)
{
// reset grading submission variables
resetGradeSubmission(state);
// reset the grade assignment id and submission id
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, assignmentId);
state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId);
// allow resubmit number
String allowResubmitNumber = "0";
Assignment a = getAssignment(assignmentId, "putSubmissionInfoIntoState", state);
if (a != null)
{
AssignmentSubmission s = getSubmission(submissionId, "putSubmissionInfoIntoState", state);
if (s != null)
{
if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0))
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText());
}
else
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText());
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment());
List v = EntityManager.newReferenceList();
Iterator attachments = s.getFeedbackAttachments().iterator();
while (attachments.hasNext())
{
v.add(attachments.next());
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT,v);
state.setAttribute(ATTACHMENTS, v);
state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade());
// put the resubmission info into state
assignment_resubmission_option_into_state(a, s, state);
}
}
}
/**
* Action is to release all the grades of the submission
*/
public void doRelease_grades(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = params.getString("assignmentId");
// get the assignment
Assignment a = getAssignment(assignmentId, "doRelease_grades", state);
if (a != null)
{
String aReference = a.getReference();
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
while (submissions.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getGraded())
{
String sRef = s.getReference();
AssignmentSubmissionEdit sEdit = editSubmission(sRef, "doRelease_grades", state);
if (sEdit != null)
{
String grade = s.getGrade();
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES))
.booleanValue() : false;
if (withGrade)
{
// for the assignment tool with grade option, a valide grade is needed
if (grade != null && !"".equals(grade))
{
sEdit.setGradeReleased(true);
}
}
else
{
// for the assignment tool without grade option, no grade is needed
sEdit.setGradeReleased(true);
}
// also set the return status
sEdit.setReturned(true);
sEdit.setTimeReturned(TimeService.newTime());
sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue());
AssignmentService.commitEdit(sEdit);
}
}
} // while
// add grades into Gradebook
String integrateWithGradebook = a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// integrate with Gradebook
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update", -1);
}
}
} // doRelease_grades
/**
* Action is to show the assignment in grading page
*/
public void doExpand_grade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true));
} // doExpand_grade_assignment
/**
* Action is to hide the assignment in grading page
*/
public void doCollapse_grade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false));
} // doCollapse_grade_assignment
/**
* Action is to show the submissions in grading page
*/
public void doExpand_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(true));
} // doExpand_grade_submission
/**
* Action is to hide the submissions in grading page
*/
public void doCollapse_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(false));
} // doCollapse_grade_submission
/**
* Action is to show the grade assignment
*/
public void doGrade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// clean state attribute
state.removeAttribute(USER_SUBMISSIONS);
state.removeAttribute(SHOW_ALLOW_RESUBMISSION);
String assignmentId = params.getString("assignmentId");
state.setAttribute(EXPORT_ASSIGNMENT_REF, assignmentId);
Assignment a = getAssignment(assignmentId, "doGrade_assignment", state);
if (a != null)
{
state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false));
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(true));
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
// initialize the resubmission params
assignment_resubmission_option_into_state(a, null, state);
// we are changing the view, so start with first page again.
resetPaging(state);
}
} // doGrade_assignment
/**
* Action is to show the View Students assignment screen
*/
public void doView_students_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT);
} // doView_students_Assignment
/**
* Action is to show the student submissions
*/
public void doShow_student_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
ParameterParser params = data.getParameters();
String id = params.getString("studentId");
// add the student id into the table
t.add(id);
state.setAttribute(STUDENT_LIST_SHOW_TABLE, t);
} // doShow_student_submission
/**
* Action is to hide the student submissions
*/
public void doHide_student_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
ParameterParser params = data.getParameters();
String id = params.getString("studentId");
// remove the student id from the table
t.remove(id);
state.setAttribute(STUDENT_LIST_SHOW_TABLE, t);
} // doHide_student_submission
/**
* Action is to show the graded assignment submission
*/
public void doView_grade(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId"));
// whether the user can access the Submission object
if (getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID), "doView_grade", state ) != null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE);
}
} // doView_grade
/**
* Action is to show the graded assignment submission while keeping specific information private
*/
public void doView_grade_private(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId"));
// whether the user can access the Submission object
if (getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID), "doView_grade_private", state ) != null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE_PRIVATE);
}
} // doView_grade_private
/**
* Action is to show the student submissions
*/
public void doReport_submissions(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS);
state.setAttribute(SORTED_BY, SORTED_SUBMISSION_BY_LASTNAME);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doReport_submissions
/**
*
*
*/
public void doAssignment_form(RunData data)
{
ParameterParser params = data.getParameters();
//Added by Branden Visser: Grab the submission id from the query string
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String actualGradeSubmissionId = (String) params.getString("submissionId");
Log.debug("chef", "doAssignment_form(): actualGradeSubmissionId = " + actualGradeSubmissionId);
String option = (String) params.getString("option");
if (option != null)
{
if ("post".equals(option))
{
// post assignment
doPost_assignment(data);
}
else if ("save".equals(option))
{
// save assignment
doSave_assignment(data);
}
else if ("reorder".equals(option))
{
// reorder assignments
doReorder_assignment(data);
}
else if ("preview".equals(option))
{
// preview assignment
doPreview_assignment(data);
}
else if ("cancel".equals(option))
{
// cancel creating assignment
doCancel_new_assignment(data);
}
else if ("canceledit".equals(option))
{
// cancel editing assignment
doCancel_edit_assignment(data);
}
else if ("attach".equals(option))
{
// attachments
doAttachmentsFrom(data, null);
}
else if ("modelAnswerAttach".equals(option))
{
doAttachmentsFrom(data, "modelAnswer");
}
else if ("allPurposeAttach".equals(option))
{
doAttachmentsFrom(data, "allPurpose");
}
else if ("view".equals(option))
{
// view
doView(data);
}
else if ("permissions".equals(option))
{
// permissions
doPermissions(data);
}
else if ("returngrade".equals(option))
{
//Added by Branden Visser - Check that the state is consistent
if (checkSubmissionStateConsistency(state, actualGradeSubmissionId)) {
// return grading
doReturn_grade_submission(data);
}
}
else if ("savegrade".equals(option))
{
//Added by Branden Visser - Check that the state is consistent
if (checkSubmissionStateConsistency(state, actualGradeSubmissionId)) {
// save grading
doSave_grade_submission(data);
}
}
else if ("previewgrade".equals(option))
{
//Added by Branden Visser - Check that the state is consistent
if (checkSubmissionStateConsistency(state, actualGradeSubmissionId)) {
// preview grading
doPreview_grade_submission(data);
}
}
else if ("cancelgrade".equals(option))
{
// cancel grading
doCancel_grade_submission(data);
}
else if ("cancelreorder".equals(option))
{
// cancel reordering
doCancel_reorder(data);
}
else if ("sortbygrouptitle".equals(option))
{
// read input data
setNewAssignmentParameters(data, true);
// sort by group title
doSortbygrouptitle(data);
}
else if ("sortbygroupdescription".equals(option))
{
// read input data
setNewAssignmentParameters(data, true);
// sort group by description
doSortbygroupdescription(data);
}
else if ("hide_instruction".equals(option))
{
// hide the assignment instruction
doHide_submission_assignment_instruction(data);
}
else if ("show_instruction".equals(option))
{
// show the assignment instruction
doShow_submission_assignment_instruction(data);
}
else if ("sortbygroupdescription".equals(option))
{
// show the assignment instruction
doShow_submission_assignment_instruction(data);
}
else if ("revise".equals(option) || "done".equals(option))
{
// back from the preview mode
doDone_preview_new_assignment(data);
}
else if ("prevsubmission".equals(option))
{
// save and navigate to previous submission
doPrev_back_next_submission(data, "prev");
}
else if ("nextsubmission".equals(option))
{
// save and navigate to previous submission
doPrev_back_next_submission(data, "next");
}
else if ("cancelgradesubmission".equals(option))
{
// back to the list view
doPrev_back_next_submission(data, "back");
}
else if ("reorderNavigation".equals(option))
{
// save and do reorder
doReorder(data);
}
}
}
// added by Branden Visser - Check that the state is consistent
boolean checkSubmissionStateConsistency(SessionState state, String actualGradeSubmissionId) {
String stateGradeSubmissionId = (String)state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
Log.debug("chef", "doAssignment_form(): stateGradeSubmissionId = " + stateGradeSubmissionId);
boolean is_good = stateGradeSubmissionId.equals(actualGradeSubmissionId);
if (!is_good) {
Log.warn("chef", "doAssignment_form(): State is inconsistent! Aborting grade save.");
addAlert(state, rb.getString("grading.alert.multiTab"));
}
return is_good;
}
/**
* Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked
*/
public void doAttachmentsFrom(RunData data, String from)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
doAttachments(data);
// use the real attachment list
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (from != null && "modelAnswer".equals(from))
{
state.setAttribute(ATTACHMENTS_FOR, MODELANSWER_ATTACHMENTS);
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(MODELANSWER_ATTACHMENTS));
state.setAttribute(MODELANSWER, Boolean.TRUE);
}
else if (from != null && "allPurpose".equals(from))
{
state.setAttribute(ATTACHMENTS_FOR, ALLPURPOSE_ATTACHMENTS);
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ALLPURPOSE_ATTACHMENTS));
state.setAttribute(ALLPURPOSE, Boolean.TRUE);
}
}
}
/**
* put supplement item attachment info into state
* @param state
* @param item
* @param attachmentsKind
*/
private void putSupplementItemAttachmentInfoIntoState(SessionState state, AssignmentSupplementItemWithAttachment item, String attachmentsKind)
{
List refs = new Vector();
if (item != null)
{
// get reference list
Set<AssignmentSupplementItemAttachment> aSet = item.getAttachmentSet();
if (aSet != null && aSet.size() > 0)
{
for(Iterator<AssignmentSupplementItemAttachment> aIterator = aSet.iterator(); aIterator.hasNext();)
{
AssignmentSupplementItemAttachment att = aIterator.next();
// add reference
refs.add(EntityManager.newReference(att.getAttachmentId()));
}
state.setAttribute(attachmentsKind, refs);
}
}
}
/**
* put supplement item attachment state attribute value into context
* @param state
* @param context
* @param attachmentsKind
*/
private void putSupplementItemAttachmentStateIntoContext(SessionState state, Context context, String attachmentsKind)
{
List refs = new Vector();
String attachmentsFor = (String) state.getAttribute(ATTACHMENTS_FOR);
if (attachmentsFor != null && attachmentsFor.equals(attachmentsKind))
{
ToolSession session = SessionManager.getCurrentToolSession();
if (session.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null &&
session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null)
{
refs = (List)session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
// set the correct state variable
state.setAttribute(attachmentsKind, refs);
}
session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
state.removeAttribute(ATTACHMENTS_FOR);
}
// show attachments content
if (state.getAttribute(attachmentsKind) != null)
{
context.put(attachmentsKind, state.getAttribute(attachmentsKind));
}
// this is to keep the proper node div open
context.put("attachments_for", attachmentsKind);
}
/**
* Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked
*/
public void doAttachments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String mode = (String) state.getAttribute(STATE_MODE);
if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode))
{
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT),
checkForFormattingErrors);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null)
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true");
}
// need also to upload local file if any
doAttachUpload(data, false);
// TODO: file picker to save in dropbox? -ggolden
// User[] users = { UserDirectoryService.getCurrentUser() };
// state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users);
}
else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode))
{
setNewAssignmentParameters(data, false);
}
else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode))
{
readGradeForm(data, state, "read");
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.filepicker");
state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig"));
state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr"));
// use the real attachment list
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ATTACHMENTS));
}
}
/**
* read grade information form and see if any grading information has been changed
* @param data
* @param state
* @param gradeOption
* @return
*/
public boolean readGradeForm(RunData data, SessionState state, String gradeOption)
{
// whether user has changed anything from previous grading information
boolean hasChange = false;
ParameterParser params = data.getParameters();
String sId = params.getString("submissionId");
// security check for allowing grading submission or not
if (AssignmentService.allowGradeSubmission(sId))
{
int typeOfGrade = -1;
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()
: false;
boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors
String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT),
checkForFormattingErrors);
// comment value changed?
hasChange = !hasChange ? valueDiffFromStateAttribute(state, feedbackComment, GRADE_SUBMISSION_FEEDBACK_COMMENT):hasChange;
if (feedbackComment != null)
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment);
}
String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT));
// feedbackText value changed?
hasChange = !hasChange ? valueDiffFromStateAttribute(state, feedbackText, GRADE_SUBMISSION_FEEDBACK_TEXT):hasChange;
if (feedbackText != null)
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText);
}
// any change inside attachment list?
if (!hasChange)
{
List stateAttachments = state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT) == null?null:((List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT)).isEmpty()?null:(List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
List inputAttachments = state.getAttribute(ATTACHMENTS) == null?null:((List) state.getAttribute(ATTACHMENTS)).isEmpty()?null:(List) state.getAttribute(ATTACHMENTS);
if (stateAttachments == null && inputAttachments != null
|| stateAttachments != null && inputAttachments == null
|| stateAttachments != null && inputAttachments != null && !(stateAttachments.containsAll(inputAttachments) && inputAttachments.containsAll(stateAttachments)))
{
hasChange = true;
}
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS));
String g = StringUtil.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE));
AssignmentSubmission submission = getSubmission(sId, "readGradeForm", state);
if (submission != null)
{
Assignment a = submission.getAssignment();
typeOfGrade = a.getContent().getTypeOfGrade();
if (withGrade)
{
// any change in grade. Do not check for ungraded assignment type
hasChange = (!hasChange && typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) ? (typeOfGrade == Assignment.SCORE_GRADE_TYPE?valueDiffFromStateAttribute(state, scalePointGrade(state, g), GRADE_SUBMISSION_GRADE):valueDiffFromStateAttribute(state, g, GRADE_SUBMISSION_GRADE)):hasChange;
if (g != null)
{
state.setAttribute(GRADE_SUBMISSION_GRADE, g);
}
else
{
state.removeAttribute(GRADE_SUBMISSION_GRADE);
}
// for points grading, one have to enter number as the points
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
// do grade validation only for Assignment with Grade tool
if (typeOfGrade == Assignment.SCORE_GRADE_TYPE)
{
if ((grade != null))
{
// the preview grade process might already scaled up the grade by 10
if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION))
{
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))}));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
M_log.warn(this + ":readGradeForm " + e.getMessage());
}
}
state.setAttribute(GRADE_SUBMISSION_GRADE, grade);
}
}
}
// if ungraded and grade type is not "ungraded" type
if ((grade == null || "ungraded".equals(grade)) && (typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) && "release".equals(gradeOption))
{
addAlert(state, rb.getString("plespethe2"));
}
}
// allow resubmit number and due time
if (params.getString("allowResToggle") != null && params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// read in allowResubmit params
readAllowResubmitParams(params, state, submission);
}
else
{
resetAllowResubmitParams(state);
}
// record whether the resubmission options has been changed or not
hasChange = hasChange || change_resubmit_option(state, submission);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
grade = (typeOfGrade == Assignment.SCORE_GRADE_TYPE)?scalePointGrade(state, grade):grade;
state.setAttribute(GRADE_SUBMISSION_GRADE, grade);
}
}
else
{
// generate alert
addAlert(state, rb.getFormattedMessage("not_allowed_to_grade_submission", new Object[]{sId}));
}
return hasChange;
}
/**
* whether the current input value is different from existing session state value
* @param state
* @param value
* @param stateAttribute
* @return
*/
private boolean valueDiffFromStateAttribute(SessionState state, String value, String stateAttribute)
{
boolean rv = false;
value = StringUtil.trimToNull(value);
String stateAttributeValue = state.getAttribute(stateAttribute) == null?null:StringUtil.trimToNull((String) state.getAttribute(stateAttribute));
if (stateAttributeValue == null && value != null
|| stateAttributeValue != null && value == null
|| stateAttributeValue != null && value != null && !stateAttributeValue.equals(value))
{
rv = true;
}
return rv;
}
/**
* read in the resubmit parameters into state variables
* @param params
* @param state
*/
protected void readAllowResubmitParams(ParameterParser params, SessionState state, Entity entity)
{
String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (allowResubmitNumberString != null && Integer.parseInt(allowResubmitNumberString) != 0)
{
int closeMonth = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, Integer.valueOf(closeMonth));
int closeDay = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, Integer.valueOf(closeDay));
int closeYear = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, Integer.valueOf(closeYear));
int closeHour = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, Integer.valueOf(closeHour));
int closeMin = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, Integer.valueOf(closeMin));
String closeAMPM = params.getString(ALLOW_RESUBMIT_CLOSEAMPM);
state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, closeAMPM);
if (("PM".equals(closeAMPM)) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && ("AM".equals(closeAMPM)))
{
closeHour = 0;
}
Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
// no need to show alert if the resubmission setting has not changed
if (entity == null || change_resubmit_option(state, entity))
{
// validate date
if (closeTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) == null)
{
state.setAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE, Boolean.TRUE);
}
else
{
// clean the attribute after user confirm
state.removeAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE);
}
if (state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) != null)
{
addAlert(state, rb.getString("acesubdea5"));
}
if (!Validator.checkDate(closeDay, closeMonth, closeYear))
{
addAlert(state, rb.getFormattedMessage("date.invalid", new Object[]{rb.getString("date.resubmission.closedate")}));
}
}
}
else
{
// reset the state attributes
resetAllowResubmitParams(state);
}
}
protected void resetAllowResubmitParams(SessionState state)
{
state.removeAttribute(ALLOW_RESUBMIT_CLOSEMONTH);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEDAY);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEYEAR);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEHOUR);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEMIN);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEAMPM);
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
/**
* Populate the state object, if needed - override to do something!
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data)
{
super.initState(state, portlet, data);
if (m_contentHostingService == null)
{
m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
}
if (m_assignmentSupplementItemService == null)
{
m_assignmentSupplementItemService = (AssignmentSupplementItemService) ComponentManager.get("org.sakaiproject.assignment.api.model.AssignmentSupplementItemService");
}
if (m_eventTrackingService == null)
{
m_eventTrackingService = (EventTrackingService) ComponentManager.get("org.sakaiproject.event.api.EventTrackingService");
}
if (m_notificationService == null)
{
m_notificationService = (NotificationService) ComponentManager.get("org.sakaiproject.event.api.NotificationService");
}
String siteId = ToolManager.getCurrentPlacement().getContext();
// show the list of assignment view first
if (state.getAttribute(STATE_SELECTED_VIEW) == null)
{
state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS);
}
if (state.getAttribute(STATE_USER) == null)
{
state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser());
}
/** The content type image lookup service in the State. */
ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
if (iService == null)
{
iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance();
state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService);
} // if
/** The calendar tool */
if (state.getAttribute(CALENDAR_TOOL_EXIST) == null)
{
if (!siteHasTool(siteId, "sakai.schedule"))
{
state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.FALSE);
state.removeAttribute(CALENDAR);
}
else
{
state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE);
if (state.getAttribute(CALENDAR) == null )
{
state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE);
CalendarService cService = org.sakaiproject.calendar.cover.CalendarService.getInstance();
state.setAttribute(STATE_CALENDAR_SERVICE, cService);
String calendarId = ServerConfigurationService.getString("calendar", null);
if (calendarId == null)
{
calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER);
try
{
state.setAttribute(CALENDAR, cService.getCalendar(calendarId));
}
catch (IdUnusedException e)
{
state.removeAttribute(CALENDAR);
M_log.info(this + ":initState No calendar found for site " + siteId + " " + e.getMessage());
}
catch (PermissionException e)
{
state.removeAttribute(CALENDAR);
M_log.info(this + ":initState No permission to get the calender. " + e.getMessage());
}
catch (Exception ex)
{
state.removeAttribute(CALENDAR);
M_log.info(this + ":initState Assignment : Action : init state : calendar exception : " + ex.getMessage());
}
}
}
}
}
/** The Announcement tool */
if (state.getAttribute(ANNOUNCEMENT_TOOL_EXIST) == null)
{
if (!siteHasTool(siteId, "sakai.announcements"))
{
state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.FALSE);
state.removeAttribute(ANNOUNCEMENT_CHANNEL);
}
else
{
state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.TRUE);
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) == null )
{
/** The announcement service in the State. */
AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE);
if (aService == null)
{
aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance();
state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService);
String channelId = ServerConfigurationService.getString("channel", null);
if (channelId == null)
{
channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER);
try
{
state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId));
}
catch (IdUnusedException e)
{
M_log.warn(this + ":initState No announcement channel found. " + e.getMessage());
state.removeAttribute(ANNOUNCEMENT_CHANNEL);
}
catch (PermissionException e)
{
M_log.warn(this + ":initState No permission to annoucement channel. " + e.getMessage());
}
catch (Exception ex)
{
M_log.warn(this + ":initState Assignment : Action : init state : calendar exception : " + ex.getMessage());
}
}
}
}
}
} // if
if (state.getAttribute(STATE_CONTEXT_STRING) == null)
{
state.setAttribute(STATE_CONTEXT_STRING, siteId);
} // if context string is null
if (state.getAttribute(SORTED_BY) == null)
{
setDefaultSort(state);
}
if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null)
{
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME);
}
if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null)
{
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString());
}
if (state.getAttribute(SORTED_SUBMISSION_BY) == null)
{
state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME);
}
if (state.getAttribute(SORTED_SUBMISSION_ASC) == null)
{
state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString());
}
if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null)
{
state.setAttribute(STUDENT_LIST_SHOW_TABLE, new HashSet());
}
if (state.getAttribute(ATTACHMENTS_MODIFIED) == null)
{
state.setAttribute(ATTACHMENTS_MODIFIED, Boolean.valueOf(false));
}
// SECTION MOD
if (state.getAttribute(STATE_SECTION_STRING) == null)
{
state.setAttribute(STATE_SECTION_STRING, "001");
}
// // setup the observer to notify the Main panel
// if (state.getAttribute(STATE_OBSERVER) == null)
// {
// // the delivery location for this tool
// String deliveryId = clientWindowId(state, portlet.getID());
//
// // the html element to update on delivery
// String elementId = mainPanelUpdateId(portlet.getID());
//
// // the event resource reference pattern to watch for
// String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), "");
//
// state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern));
// }
if (state.getAttribute(STATE_MODE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null)
{
state.setAttribute(STATE_TOP_PAGE_MESSAGE, Integer.valueOf(0));
}
if (state.getAttribute(WITH_GRADES) == null)
{
PortletConfig config = portlet.getPortletConfig();
String withGrades = StringUtil.trimToNull(config.getInitParameter("withGrades"));
if (withGrades == null)
{
withGrades = Boolean.FALSE.toString();
}
state.setAttribute(WITH_GRADES, Boolean.valueOf(withGrades));
}
// whether to display the number of submission/ungraded submission column
// default to show
if (state.getAttribute(SHOW_NUMBER_SUBMISSION_COLUMN) == null)
{
PortletConfig config = portlet.getPortletConfig();
String value = StringUtil.trimToNull(config.getInitParameter(SHOW_NUMBER_SUBMISSION_COLUMN));
if (value == null)
{
value = Boolean.TRUE.toString();
}
state.setAttribute(SHOW_NUMBER_SUBMISSION_COLUMN, Boolean.valueOf(value));
}
if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM) == null)
{
state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM, Integer.valueOf(2002));
}
if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO) == null)
{
state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO, Integer.valueOf(2012));
}
} // initState
/**
* whether the site has the specified tool
* @param siteId
* @return
*/
private boolean siteHasTool(String siteId, String toolId) {
boolean rv = false;
try
{
Site s = SiteService.getSite(siteId);
if (s.getToolForCommonId(toolId) != null)
{
rv = true;
}
}
catch (Exception e)
{
M_log.warn(this + "siteHasTool" + e.getMessage() + siteId);
}
return rv;
}
/**
* reset the attributes for view submission
*/
private void resetViewSubmission(SessionState state)
{
state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
state.removeAttribute(VIEW_SUBMISSION_TEXT);
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false");
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
} // resetViewSubmission
/**
* initialize assignment attributes
* @param state
*/
private void initializeAssignment(SessionState state)
{
// put the input value into the state attributes
state.setAttribute(NEW_ASSIGNMENT_TITLE, "");
// get current time
Time t = TimeService.newTime();
TimeBreakdown tB = t.breakdownLocal();
int month = tB.getMonth();
int day = tB.getDay();
int year = tB.getYear();
// set the open time to be 12:00 PM
state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, Integer.valueOf(month));
state.setAttribute(NEW_ASSIGNMENT_OPENDAY, Integer.valueOf(day));
state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, Integer.valueOf(year));
state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, Integer.valueOf(12));
state.setAttribute(NEW_ASSIGNMENT_OPENMIN, Integer.valueOf(0));
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM");
// set the all purpose item release time
state.setAttribute(ALLPURPOSE_RELEASE_MONTH, Integer.valueOf(month));
state.setAttribute(ALLPURPOSE_RELEASE_DAY, Integer.valueOf(day));
state.setAttribute(ALLPURPOSE_RELEASE_YEAR, Integer.valueOf(year));
state.setAttribute(ALLPURPOSE_RELEASE_HOUR, Integer.valueOf(12));
state.setAttribute(ALLPURPOSE_RELEASE_MIN, Integer.valueOf(0));
state.setAttribute(ALLPURPOSE_RELEASE_AMPM, "PM");
// due date is shifted forward by 7 days
t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000);
tB = t.breakdownLocal();
month = tB.getMonth();
day = tB.getDay();
year = tB.getYear();
// set the due time to be 5:00pm
state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, Integer.valueOf(month));
state.setAttribute(NEW_ASSIGNMENT_DUEDAY, Integer.valueOf(day));
state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, Integer.valueOf(year));
state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, Integer.valueOf(5));
state.setAttribute(NEW_ASSIGNMENT_DUEMIN, Integer.valueOf(0));
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM");
// set the resubmit time to be the same as due time
state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, Integer.valueOf(month));
state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, Integer.valueOf(day));
state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, Integer.valueOf(year));
state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, Integer.valueOf(5));
state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, Integer.valueOf(0));
state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, "PM");
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, Integer.valueOf(1));
// enable the close date by default
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true));
// set the close time to be 5:00 pm, same as the due time by default
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, Integer.valueOf(month));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, Integer.valueOf(day));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, Integer.valueOf(year));
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, Integer.valueOf(5));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, Integer.valueOf(0));
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM");
// set the all purpose retract time
state.setAttribute(ALLPURPOSE_RETRACT_MONTH, Integer.valueOf(month));
state.setAttribute(ALLPURPOSE_RETRACT_DAY, Integer.valueOf(day));
state.setAttribute(ALLPURPOSE_RETRACT_YEAR, Integer.valueOf(year));
state.setAttribute(ALLPURPOSE_RETRACT_HOUR, Integer.valueOf(5));
state.setAttribute(ALLPURPOSE_RETRACT_MIN, Integer.valueOf(0));
state.setAttribute(ALLPURPOSE_RETRACT_AMPM, "PM");
state.setAttribute(NEW_ASSIGNMENT_SECTION, "001");
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION));
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(Assignment.UNGRADED_GRADE_TYPE));
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, "");
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, "");
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString());
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString());
// make the honor pledge not include as the default
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (Integer.valueOf(Assignment.HONOR_PLEDGE_NONE)).toString());
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList());
state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE);
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
state.removeAttribute(NEW_ASSIGNMENT_RANGE);
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
// remove the edit assignment id if any
state.removeAttribute(EDIT_ASSIGNMENT_ID);
// remove the resubmit number
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// remove the supplement attributes
state.removeAttribute(MODELANSWER);
state.removeAttribute(MODELANSWER_TEXT);
state.removeAttribute(MODELANSWER_SHOWTO);
state.removeAttribute(MODELANSWER_ATTACHMENTS);
state.removeAttribute(NOTE);
state.removeAttribute(NOTE_TEXT);
state.removeAttribute(NOTE_SHAREWITH);
state.removeAttribute(ALLPURPOSE);
state.removeAttribute(ALLPURPOSE_TITLE);
state.removeAttribute(ALLPURPOSE_TEXT);
state.removeAttribute(ALLPURPOSE_HIDE);
state.removeAttribute(ALLPURPOSE_SHOW_FROM);
state.removeAttribute(ALLPURPOSE_SHOW_TO);
state.removeAttribute(ALLPURPOSE_RELEASE_DATE);
state.removeAttribute(ALLPURPOSE_RETRACT_DATE);
state.removeAttribute(ALLPURPOSE_ACCESS);
state.removeAttribute(ALLPURPOSE_ATTACHMENTS);
} // resetNewAssignment
/**
* reset the attributes for assignment
*/
private void resetAssignment(SessionState state)
{
state.removeAttribute(NEW_ASSIGNMENT_TITLE);
state.removeAttribute(NEW_ASSIGNMENT_OPENMONTH);
state.removeAttribute(NEW_ASSIGNMENT_OPENDAY);
state.removeAttribute(NEW_ASSIGNMENT_OPENYEAR);
state.removeAttribute(NEW_ASSIGNMENT_OPENHOUR);
state.removeAttribute(NEW_ASSIGNMENT_OPENMIN);
state.removeAttribute(NEW_ASSIGNMENT_OPENAMPM);
state.removeAttribute(ALLPURPOSE_RELEASE_MONTH);
state.removeAttribute(ALLPURPOSE_RELEASE_DAY);
state.removeAttribute(ALLPURPOSE_RELEASE_YEAR);
state.removeAttribute(ALLPURPOSE_RELEASE_HOUR);
state.removeAttribute(ALLPURPOSE_RELEASE_MIN);
state.removeAttribute(ALLPURPOSE_RELEASE_AMPM);
state.removeAttribute(NEW_ASSIGNMENT_DUEMONTH);
state.removeAttribute(NEW_ASSIGNMENT_DUEDAY);
state.removeAttribute(NEW_ASSIGNMENT_DUEYEAR);
state.removeAttribute(NEW_ASSIGNMENT_DUEHOUR);
state.removeAttribute(NEW_ASSIGNMENT_DUEMIN);
state.removeAttribute(NEW_ASSIGNMENT_DUEAMPM);
state.removeAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEMONTH);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEDAY);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEYEAR);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEHOUR);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEMIN);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEAMPM);
// set the all purpose retract time
state.removeAttribute(ALLPURPOSE_RETRACT_MONTH);
state.removeAttribute(ALLPURPOSE_RETRACT_DAY);
state.removeAttribute(ALLPURPOSE_RETRACT_YEAR);
state.removeAttribute(ALLPURPOSE_RETRACT_HOUR);
state.removeAttribute(ALLPURPOSE_RETRACT_MIN);
state.removeAttribute(ALLPURPOSE_RETRACT_AMPM);
state.removeAttribute(NEW_ASSIGNMENT_SECTION);
state.removeAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE);
state.removeAttribute(NEW_ASSIGNMENT_GRADE_TYPE);
state.removeAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION);
state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
state.removeAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
state.removeAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
state.removeAttribute(NEW_ASSIGNMENT_ATTACHMENT);
state.removeAttribute(NEW_ASSIGNMENT_FOCUS);
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
state.removeAttribute(NEW_ASSIGNMENT_RANGE);
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
// remove the edit assignment id if any
state.removeAttribute(EDIT_ASSIGNMENT_ID);
// remove the resubmit number
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// remove the supplement attributes
state.removeAttribute(MODELANSWER);
state.removeAttribute(MODELANSWER_TEXT);
state.removeAttribute(MODELANSWER_SHOWTO);
state.removeAttribute(MODELANSWER_ATTACHMENTS);
state.removeAttribute(NOTE);
state.removeAttribute(NOTE_TEXT);
state.removeAttribute(NOTE_SHAREWITH);
state.removeAttribute(ALLPURPOSE);
state.removeAttribute(ALLPURPOSE_TITLE);
state.removeAttribute(ALLPURPOSE_TEXT);
state.removeAttribute(ALLPURPOSE_HIDE);
state.removeAttribute(ALLPURPOSE_SHOW_FROM);
state.removeAttribute(ALLPURPOSE_SHOW_TO);
state.removeAttribute(ALLPURPOSE_RELEASE_DATE);
state.removeAttribute(ALLPURPOSE_RETRACT_DATE);
state.removeAttribute(ALLPURPOSE_ACCESS);
state.removeAttribute(ALLPURPOSE_ATTACHMENTS);
// remove content-review setting
state.removeAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
} // resetNewAssignment
/**
* construct a Hashtable using integer as the key and three character string of the month as the value
*/
private Hashtable monthTable()
{
Hashtable n = new Hashtable();
n.put(Integer.valueOf(1), rb.getString("jan"));
n.put(Integer.valueOf(2), rb.getString("feb"));
n.put(Integer.valueOf(3), rb.getString("mar"));
n.put(Integer.valueOf(4), rb.getString("apr"));
n.put(Integer.valueOf(5), rb.getString("may"));
n.put(Integer.valueOf(6), rb.getString("jun"));
n.put(Integer.valueOf(7), rb.getString("jul"));
n.put(Integer.valueOf(8), rb.getString("aug"));
n.put(Integer.valueOf(9), rb.getString("sep"));
n.put(Integer.valueOf(10), rb.getString("oct"));
n.put(Integer.valueOf(11), rb.getString("nov"));
n.put(Integer.valueOf(12), rb.getString("dec"));
return n;
} // monthTable
/**
* construct a Hashtable using the integer as the key and grade type String as the value
*/
private Hashtable gradeTypeTable()
{
Hashtable n = new Hashtable();
n.put(Integer.valueOf(2), rb.getString("letter"));
n.put(Integer.valueOf(3), rb.getString("points"));
n.put(Integer.valueOf(4), rb.getString("pass"));
n.put(Integer.valueOf(5), rb.getString("check"));
n.put(Integer.valueOf(1), rb.getString("ungra"));
return n;
} // gradeTypeTable
/**
* construct a Hashtable using the integer as the key and submission type String as the value
*/
private Hashtable submissionTypeTable()
{
Hashtable n = new Hashtable();
n.put(Integer.valueOf(1), rb.getString("inlin"));
n.put(Integer.valueOf(2), rb.getString("attaonly"));
n.put(Integer.valueOf(3), rb.getString("inlinatt"));
n.put(Integer.valueOf(4), rb.getString("nonelec"));
n.put(Integer.valueOf(5), rb.getString("singleatt"));
return n;
} // submissionTypeTable
/**
* Add the list of categories from the gradebook tool
* construct a Hashtable using the integer as the key and category String as the value
* @return
*/
private Hashtable<Long, String> categoryTable()
{
boolean gradebookExists = isGradebookDefined();
Hashtable<Long, String> catTable = new Hashtable<Long, String>();
if (gradebookExists) {
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
List<CategoryDefinition> categoryDefinitions = g.getCategoryDefinitions(gradebookUid);
catTable.put(Long.valueOf(-1), rb.getString("grading.unassigned"));
for (CategoryDefinition category: categoryDefinitions) {
catTable.put(category.getId(), category.getName());
}
}
return catTable;
} // categoryTable
/**
* Sort based on the given property
*/
public void doSort(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
setupSort(data, data.getParameters().getString("criteria"));
}
/**
* setup sorting parameters
*
* @param criteria
* String for sortedBy
*/
private void setupSort(RunData data, String criteria)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_BY)))
{
state.setAttribute(SORTED_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
} // doSort
/**
* Do sort by group title
*/
public void doSortbygrouptitle(RunData data)
{
setupSort(data, SORTED_BY_GROUP_TITLE);
} // doSortbygrouptitle
/**
* Do sort by group description
*/
public void doSortbygroupdescription(RunData data)
{
setupSort(data, SORTED_BY_GROUP_DESCRIPTION);
} // doSortbygroupdescription
/**
* Sort submission based on the given property
*/
public void doSort_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
// get the ParameterParser from RunData
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY)))
{
state.setAttribute(SORTED_SUBMISSION_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_SUBMISSION_ASC, asc);
}
else
{
// current sorting sequence
state.setAttribute(SORTED_SUBMISSION_BY, criteria);
asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_SUBMISSION_ASC, asc);
}
} // doSort_submission
/**
* Sort submission based on the given property in instructor grade view
*/
public void doSort_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
// get the ParameterParser from RunData
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY)))
{
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria);
//for content review default is desc
if (criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
asc = Boolean.FALSE.toString();
else
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc);
}
else
{
// current sorting sequence
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria);
asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc);
}
} // doSort_grade_submission
public void doSort_tags(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
String providerId = params.getString(PROVIDER_ID);
String savedText = params.getString("savedText");
state.setAttribute(VIEW_SUBMISSION_TEXT, savedText);
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
for (DecoratedTaggingProvider dtp : providers) {
if (dtp.getProvider().getId().equals(providerId)) {
Sort sort = dtp.getSort();
if (sort.getSort().equals(criteria)) {
sort.setAscending(sort.isAscending() ? false : true);
} else {
sort.setSort(criteria);
sort.setAscending(true);
}
break;
}
}
}
public void doPage_tags(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String page = params.getString("page");
String pageSize = params.getString("pageSize");
String providerId = params.getString(PROVIDER_ID);
String savedText = params.getString("savedText");
state.setAttribute(VIEW_SUBMISSION_TEXT, savedText);
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
for (DecoratedTaggingProvider dtp : providers) {
if (dtp.getProvider().getId().equals(providerId)) {
Pager pager = dtp.getPager();
pager.setPageSize(Integer.valueOf(pageSize));
if (Pager.FIRST.equals(page)) {
pager.setFirstItem(0);
} else if (Pager.PREVIOUS.equals(page)) {
pager.setFirstItem(pager.getFirstItem()
- pager.getPageSize());
} else if (Pager.NEXT.equals(page)) {
pager.setFirstItem(pager.getFirstItem()
+ pager.getPageSize());
} else if (Pager.LAST.equals(page)) {
pager.setFirstItem((pager.getTotalItems() / pager
.getPageSize())
* pager.getPageSize());
}
break;
}
}
}
/**
* the UserSubmission clas
*/
public class UserSubmission
{
/**
* the User object
*/
User m_user = null;
/**
* the AssignmentSubmission object
*/
AssignmentSubmission m_submission = null;
public UserSubmission(User u, AssignmentSubmission s)
{
m_user = u;
m_submission = s;
}
/**
* Returns the AssignmentSubmission object
*/
public AssignmentSubmission getSubmission()
{
return m_submission;
}
/**
* Returns the User object
*/
public User getUser()
{
return m_user;
}
}
/**
* the AssignmentComparator clas
*/
private class AssignmentComparator implements Comparator
{
Collator collator = Collator.getInstance();
/**
* the SessionState object
*/
SessionState m_state = null;
/**
* the criteria
*/
String m_criteria = null;
/**
* the criteria
*/
String m_asc = null;
/**
* the user
*/
User m_user = null;
/**
* constructor
*
* @param state
* The state object
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
*/
public AssignmentComparator(SessionState state, String criteria, String asc)
{
m_state = state;
m_criteria = criteria;
m_asc = asc;
} // constructor
/**
* constructor
*
* @param state
* The state object
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
* @param user
* The user object
*/
public AssignmentComparator(SessionState state, String criteria, String asc, User user)
{
m_state = state;
m_criteria = criteria;
m_asc = asc;
m_user = user;
} // constructor
/**
* caculate the range string for an assignment
*/
private String getAssignmentRange(Assignment a)
{
String rv = "";
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
// site assignment
rv = rb.getString("range.allgroups");
}
else
{
try
{
// get current site
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
for (Iterator k = a.getGroups().iterator(); k.hasNext();)
{
// announcement by group
rv = rv.concat(site.getGroup((String) k.next()).getTitle());
}
}
catch (Exception ignore)
{
M_log.warn(this + ":getAssignmentRange" + ignore.getMessage());
}
}
return rv;
} // getAssignmentRange
/**
* 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;
if (m_criteria == null)
{
m_criteria = SORTED_BY_DEFAULT;
}
/** *********** for sorting assignments ****************** */
if (m_criteria.equals(SORTED_BY_DEFAULT))
{
int s1 = ((Assignment) o1).getPosition_order();
int s2 = ((Assignment) o2).getPosition_order();
if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate
{
// 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.equals(t2))
{
t1 = ((Assignment) o1).getTimeCreated();
t2 = ((Assignment) o2).getTimeCreated();
}
else if (t1.before(t2))
{
result = 1;
}
else
{
result = -1;
}
}
}
else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list
{
result = 1;
}
else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom
{
result = -1;
}
else // 2 legitimate postion orders
{
result = (s1 < s2) ? -1 : 1;
}
}
if (m_criteria.equals(SORTED_BY_TITLE))
{
// sorted by the assignment title
String s1 = ((Assignment) o1).getTitle();
String s2 = ((Assignment) o2).getTitle();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_SECTION))
{
// sorted by the assignment section
String s1 = ((Assignment) o1).getSection();
String s2 = ((Assignment) o2).getSection();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_DUEDATE))
{
// 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 (m_criteria.equals(SORTED_BY_OPENDATE))
{
// sorted by the assignment open
Time t1 = ((Assignment) o1).getOpenTime();
Time t2 = ((Assignment) o2).getOpenTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS))
{
result = compareString(((Assignment) o1).getStatus(), ((Assignment) o2).getStatus());
}
else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS))
{
// sort by numbers of submissions
// initialize
int subNum1 = 0;
int subNum2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted()) subNum1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted()) subNum2++;
}
result = (subNum1 > subNum2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED))
{
// sort by numbers of ungraded submissions
// initialize
int ungraded1 = 0;
int ungraded2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++;
}
result = (ungraded1 > ungraded2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_GRADE) || m_criteria.equals(SORTED_BY_SUBMISSION_STATUS))
{
AssignmentSubmission submission1 = getSubmission(((Assignment) o1).getId(), m_user, "compare", null);
String grade1 = " ";
if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased())
{
grade1 = submission1.getGrade();
}
AssignmentSubmission submission2 = getSubmission(((Assignment) o2).getId(), m_user, "compare", null);
String grade2 = " ";
if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased())
{
grade2 = submission2.getGrade();
}
result = compareString(grade1, grade2);
}
else if (m_criteria.equals(SORTED_BY_MAX_GRADE))
{
String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1);
String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
M_log.warn(this + ":AssignmentComparator compare" + e.getMessage());
// otherwise do an alpha-compare
result = compareString(maxGrade1, maxGrade2);
}
}
// group related sorting
else if (m_criteria.equals(SORTED_BY_FOR))
{
// sorted by the public view attribute
String factor1 = getAssignmentRange((Assignment) o1);
String factor2 = getAssignmentRange((Assignment) o2);
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_TITLE))
{
// sorted by the group title
String factor1 = ((Group) o1).getTitle();
String factor2 = ((Group) o2).getTitle();
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION))
{
// sorted by the group description
String factor1 = ((Group) o1).getDescription();
String factor2 = ((Group) o2).getDescription();
if (factor1 == null)
{
factor1 = "";
}
if (factor2 == null)
{
factor2 = "";
}
result = compareString(factor1, factor2);
}
/** ***************** for sorting submissions in instructor grade assignment view ************* */
else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
{
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null )
{
result = 1;
}
else
{
int score1 = u1.getSubmission().getReviewScore();
int score2 = u2.getSubmission().getReviewScore();
result = (Integer.valueOf(score1)).intValue() > (Integer.valueOf(score2)).intValue() ? 1 : -1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
String lName1 = u1.getUser().getSortName();
String lName2 = u2.getUser().getSortName();
result = compareString(lName1, lName2);
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null || s1.getTimeSubmitted() == null)
{
result = -1;
}
else if (s2 == null || s2.getTimeSubmitted() == null)
{
result = 1;
}
else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted()))
{
result = -1;
}
else
{
result = 1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
String status1 = "";
String status2 = "";
if (u1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
if (s1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
status1 = s1.getStatus();
}
}
if (u2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s2 = u2.getSubmission();
if (s2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
status2 = s2.getStatus();
}
}
result = compareString(status1, status2);
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
//sort by submission grade
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
String grade1 = s1.getGrade();
String grade2 = s2.getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((s1.getAssignment().getContent().getTypeOfGrade() == 3)
&& ((s2.getAssignment().getContent().getTypeOfGrade() == 3)))
{
if ("".equals(grade1))
{
result = -1;
}
else if ("".equals(grade2))
{
result = 1;
}
else
{
result = compareDouble(grade1, grade2);
}
}
else
{
result = compareString(grade1, grade2);
}
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
// sort by submission released
String released1 = (Boolean.valueOf(s1.getGradeReleased())).toString();
String released2 = (Boolean.valueOf(s2.getGradeReleased())).toString();
result = compareString(released1, released2);
}
}
}
/****** for other sort on submissions **/
else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
User[] u1 = ((AssignmentSubmission) o1).getSubmitters();
User[] u2 = ((AssignmentSubmission) o2).getSubmitters();
if (u1 == null || u1.length == 0 || u2 == null || u2.length ==0)
{
return 1;
}
else
{
String submitters1 = "";
String submitters2 = "";
for (int j = 0; j < u1.length; j++)
{
if (u1[j] != null && u1[j].getSortName() != null)
{
if (j > 0)
{
submitters1 = submitters1.concat("; ");
}
submitters1 = submitters1.concat("" + u1[j].getSortName());
}
}
for (int j = 0; j < u2.length; j++)
{
if (u2[j] != null && u2[j].getSortName() != null)
{
if (j > 0)
{
submitters2 = submitters2.concat("; ");
}
submitters2 = submitters2.concat(u2[j].getSortName());
}
}
result = compareString(submitters1, submitters2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted();
Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS))
{
// sort by submission status
result = compareString(((AssignmentSubmission) o1).getStatus(), ((AssignmentSubmission) o2).getStatus());
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if ("".equals(grade1))
{
result = -1;
}
else if ("".equals(grade2))
{
result = 1;
}
else
{
result = compareDouble(grade1, grade2);
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if ("".equals(grade1))
{
result = -1;
}
else if ("".equals(grade2))
{
result = 1;
}
else
{
result = compareDouble(grade1, grade2);
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE))
{
Assignment a1 = ((AssignmentSubmission) o1).getAssignment();
Assignment a2 = ((AssignmentSubmission) o2).getAssignment();
String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1);
String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
M_log.warn(this + ":AssignmentComparator compare" + e.getMessage());
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED))
{
// sort by submission released
String released1 = (Boolean.valueOf(((AssignmentSubmission) o1).getGradeReleased())).toString();
String released2 = (Boolean.valueOf(((AssignmentSubmission) o2).getGradeReleased())).toString();
result = compareString(released1, released2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT))
{
// sort by submission's assignment
String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle();
String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle();
result = compareString(title1, title2);
}
/*************** sort user by sort name ***************/
else if (m_criteria.equals(SORTED_USER_BY_SORTNAME))
{
// sort by user's sort name
String name1 = ((User) o1).getSortName();
String name2 = ((User) o2).getSortName();
result = compareString(name1, name2);
}
// sort ascending or descending
if (!Boolean.valueOf(m_asc))
{
result = -result;
}
return result;
}
/**
* Compare two strings as double values. Deal with the case when either of the strings cannot be parsed as double value.
* @param grade1
* @param grade2
* @return
*/
private int compareDouble(String grade1, String grade2) {
int result;
try
{
result = (Double.valueOf(grade1)).doubleValue() > (Double.valueOf(grade2)).doubleValue() ? 1 : -1;
}
catch (Exception formatException)
{
// in case either grade1 or grade2 cannot be parsed as Double
result = compareString(grade1, grade2);
M_log.warn(this + ":AssignmentComparator compareDouble " + formatException.getMessage());
}
return result;
} // compareDouble
private int compareString(String s1, String s2)
{
int result;
if (s1 == null && s2 == null) {
result = 0;
} else if (s2 == null) {
result = 1;
} else if (s1 == null) {
result = -1;
} else {
result = collator.compare(s1.toLowerCase(), s2.toLowerCase());
}
return result;
}
/**
* get assignment maximun grade available based on the assignment grade type
*
* @param gradeType
* The int value of grade type
* @param a
* The assignment object
* @return The max grade String
*/
private String maxGrade(int gradeType, Assignment a)
{
String maxGrade = "";
if (gradeType == -1)
{
// Grade type not set
maxGrade = rb.getString("granotset");
}
else if (gradeType == 1)
{
// Ungraded grade type
maxGrade = rb.getString("gen.nograd");
}
else if (gradeType == 2)
{
// Letter grade type
maxGrade = "A";
}
else if (gradeType == 3)
{
// Score based grade type
maxGrade = Integer.toString(a.getContent().getMaxGradePoint());
}
else if (gradeType == 4)
{
// Pass/fail grade type
maxGrade = rb.getString("pass");
}
else if (gradeType == 5)
{
// Grade type that only requires a check
maxGrade = rb.getString("check");
}
return maxGrade;
} // maxGrade
} // DiscussionComparator
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
// we are changing the view, so start with first page again.
resetPaging(state);
// clear search form
doSearch_clear(data, null);
if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String siteRef = SiteService.siteReference(contextString);
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " "
+ SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "asn.");
// ... pass the resource loader object
ResourceLoader pRb = new ResourceLoader("permissions");
HashMap<String, String> pRbValues = new HashMap<String, String>();
for (Iterator iKeys = pRb.keySet().iterator();iKeys.hasNext();)
{
String key = (String) iKeys.next();
pRbValues.put(key, (String) pRb.get(key));
}
state.setAttribute("permissionDescriptions", pRbValues);
// disable auto-updates while leaving the list view
justDelivered(state);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
// switching back to assignment list view
state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS);
doList_assignments(data);
}
} // doPermissions
/**
* transforms the Iterator to Vector
*/
private Vector iterator_to_vector(Iterator l)
{
Vector v = new Vector();
while (l.hasNext())
{
v.add(l.next());
}
return v;
} // iterator_to_vector
/**
* Implement this to return alist of all the resources that there are to page. Sort them as appropriate.
*/
protected List readResourcesPage(SessionState state, int first, int last)
{
List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS);
PagingPosition page = new PagingPosition(first, last);
page.validate(returnResources.size());
returnResources = returnResources.subList(page.getFirst() - 1, page.getLast());
return returnResources;
} // readAllResources
/*
* (non-Javadoc)
*
* @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState)
*/
protected int sizeResources(SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// all the resources for paging
List returnResources = new Vector();
boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString);
if (MODE_LIST_ASSIGNMENTS.equals(mode))
{
String view = "";
if (state.getAttribute(STATE_SELECTED_VIEW) != null)
{
view = (String) state.getAttribute(STATE_SELECTED_VIEW);
}
if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS))
{
// read all Assignments
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW)
|| (!allowAddAssignment && AssignmentService.allowAddSubmission((String) state
.getAttribute(STATE_CONTEXT_STRING))))
{
// in the student list view of assignments
Iterator assignments = AssignmentService
.getAssignmentsForContext(contextString);
Time currentTime = TimeService.newTime();
while (assignments.hasNext())
{
Assignment a = (Assignment) assignments.next();
String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if (deleted == null || "".equals(deleted))
{
// show not deleted assignments
Time openTime = a.getOpenTime();
if (openTime != null && currentTime.after(openTime) && !a.getDraft())
{
returnResources.add(a);
}
}
else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
&& getSubmission(a.getReference(), (User) state.getAttribute(STATE_USER), "sizeResources", state) != null)
{
// and those deleted but not non-electronic assignments but the user has made submissions to them
returnResources.add(a);
}
}
}
else
{
// read all Assignments
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
state.setAttribute(HAS_MULTIPLE_ASSIGNMENTS, Boolean.valueOf(returnResources.size() > 1));
}
else if (MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode))
{
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode))
{
Vector submissions = new Vector();
Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext(contextString));
if (assignments.size() > 0)
{
// users = AssignmentService.allowAddSubmissionUsers (((Assignment)assignments.get(0)).getReference ());
}
try
{
// get the site object first
Site site = SiteService.getSite(contextString);
for (int j = 0; j < assignments.size(); j++)
{
Assignment a = (Assignment) assignments.get(j);
//get the list of users which are allowed to grade this assignment
List allowGradeAssignmentUsers = AssignmentService.allowGradeAssignmentUsers(a.getReference());
String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if ((deleted == null || "".equals(deleted)) && (!a.getDraft()) && AssignmentService.allowGradeSubmission(a.getReference()))
{
try
{
List assignmentSubmissions = AssignmentService.getSubmissions(a);
for (int k = 0; k < assignmentSubmissions.size(); k++)
{
AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k);
if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s
.getTimeReturned())))))
{
// has been subitted or has been returned and not work on it yet
User[] submitters = s.getSubmitters();
if (submitters != null && submitters.length > 0 && !allowGradeAssignmentUsers.contains(submitters[0]))
{
// find whether the submitter is still an active member of the site
Member member = site.getMember(submitters[0].getId());
if(member != null && member.isActive()) {
// only include the active student submission
submissions.add(s);
}
}
} // if-else
}
}
catch (Exception e)
{
M_log.warn(this + ":sizeResources " + e.getMessage());
}
}
}
}
catch (IdUnusedException idUnusedException)
{
M_log.warn(this + ":sizeResources " + idUnusedException.getMessage() + " site id=" + contextString);
}
returnResources = submissions;
}
else if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode))
{
// range
Collection groups = new Vector();
String aRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
Assignment a = getAssignment(aRef, "sizeResources", state);
if (a != null)
{
// all submissions
List submissions = AssignmentService.getSubmissions(a);
// now are we view all sections/groups or just specific one?
initViewSubmissionListOption(state);
String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION);
if (allOrOneGroup.equals(rb.getString("gen.viewallgroupssections")))
{
if (AssignmentService.allowAllGroups(contextString))
{
// site range
try {
groups.add(SiteService.getSite(contextString));
} catch (IdUnusedException e) {
addAlert(state, rb.getFormattedMessage("cannotfin_site", new Object[]{contextString}));
M_log.warn(this + ":sizeResources " + mode + " " + e.getMessage() + " " + contextString);
}
}
else
{
// get all groups user can grade
groups = AssignmentService.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(this + "sizeResources " + e.getMessage() + " groupId=" + allOrOneGroup);
}
}
// all users that can submit
List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
HashSet userIdSet = new HashSet();
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
if (!userIdSet.contains(userId))
{
try
{
User u = UserDirectoryService.getUser(userId);
if (u != null)
{
boolean found = false;
for (int i = 0; !found && i<submissions.size();i++)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.get(i);
if (s.getSubmitterIds().contains(userId))
{
returnResources.add(new UserSubmission(u, s));
found = true;
}
}
// add those users who haven't made any submissions and with submission rights
if (!found && allowAddSubmissionUsers.contains(u))
{
// construct fake submissions for grading purpose if the user has right for grading
if (AssignmentService.allowGradeSubmission(a.getReference()))
{
// temporarily allow the user to read and write from assignments (asn.revise permission)
enableSecurityAdvisor();
AssignmentSubmissionEdit s = AssignmentService.addSubmission(contextString, a.getId(), userId);
s.setSubmitted(true);
s.setAssignment(a);
// set the resubmission properties
setResubmissionProperties(a, s);
AssignmentService.commitEdit(s);
// update the UserSubmission list by adding newly created Submission object
AssignmentSubmission sub = getSubmission(s.getReference(), "sizeResources", state);
returnResources.add(new UserSubmission(u, sub));
// clear the permission
disableSecurityAdvisor();
}
}
}
}
catch (Exception e)
{
M_log.warn(this + ":sizeResources " + e.getMessage() + " userId = " + userId);
}
// add userId into set to prevent showing user multiple times
userIdSet.add(userId);
}
}
}
catch (Exception eee)
{
M_log.warn(this + ":sizeResources " + eee.getMessage() + " authGroupId=" + authzGroupRef);
}
}
}
}
}
// sort them all
String ascending = "true";
String sort = "";
ascending = (String) state.getAttribute(SORTED_ASC);
sort = (String) state.getAttribute(SORTED_BY);
if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode) && (sort == null || !sort.startsWith("sorted_grade_submission_by")))
{
ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC);
sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY);
}
else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode) && (sort == null || sort.startsWith("sorted_submission_by")))
{
ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC);
sort = (String) state.getAttribute(SORTED_SUBMISSION_BY);
}
else
{
ascending = (String) state.getAttribute(SORTED_ASC);
sort = (String) state.getAttribute(SORTED_BY);
}
if ((returnResources.size() > 1) && !MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(mode))
{
try
{
Collections.sort(returnResources, new AssignmentComparator(state, sort, ascending));
}
catch (Exception e)
{
// log exception during sorting for helping debugging
M_log.warn(this + ":sizeResources mode=" + mode + " sort=" + sort + " ascending=" + ascending + " " + e.getStackTrace());
}
}
// record the total item number
state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources);
return returnResources.size();
}
public void doView(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
// we are changing the view, so start with first page again.
resetPaging(state);
// clear search form
doSearch_clear(data, null);
String viewMode = data.getParameters().getString("view");
state.setAttribute(STATE_SELECTED_VIEW, viewMode);
if (MODE_LIST_ASSIGNMENTS.equals(viewMode))
{
doList_assignments(data);
}
else if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(viewMode))
{
doView_students_assignment(data);
}
else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(viewMode))
{
doReport_submissions(data);
}
else if (MODE_STUDENT_VIEW.equals(viewMode))
{
doView_student(data);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
}
} // doView
/**
* put those variables related to 2ndToolbar into context
*/
private void add2ndToolbarFields(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
context.put("totalPageNumber", Integer.valueOf(totalPageNumber(state)));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
context.put("selectedView", state.getAttribute(STATE_MODE));
} // add2ndToolbarFields
/**
* valid grade for point based type
* returns a double value in a string from the localized input
*/
private String validPointGrade(SessionState state, String grade)
{
if (grade != null && !"".equals(grade))
{
if (grade.startsWith("-"))
{
// check for negative sign
addAlert(state, rb.getString("plesuse3"));
}
else
{
// 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);
}
DecimalFormat dcFormat = (DecimalFormat) nbFormat;
String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + "";
// only the right decimal separator is allowed and no other grouping separator
if ((",".equals(decSeparator) && grade.indexOf(".") != -1) ||
(".".equals(decSeparator) && grade.indexOf(",") != -1) ||
grade.indexOf(" ") != -1) {
addAlert(state, rb.getString("plesuse1"));
return grade;
}
// parse grade from localized number format
try {
Double dblGrade = new Double (nbFormat.parse(grade).doubleValue());
grade = dblGrade.toString();
int index = grade.indexOf(".");
if (index != -1)
{
// when there is decimal points inside the grade, scale the number by 10
// but only one decimal place is supported
// for example, change 100.0 to 1000
if (!grade.equals("."))
{
if (grade.length() > index + 2)
{
// if there are more than one decimal point
addAlert(state, rb.getString("plesuse2"));
}
else
{
// decimal points is the only allowed character inside grade
// replace it with '1', and try to parse the new String into int
String gradeString = (grade.endsWith(".")) ? grade.substring(0, index).concat("0") : grade.substring(0,
index).concat(grade.substring(index + 1));
try
{
Integer.parseInt(gradeString);
}
catch (NumberFormatException e)
{
M_log.warn(this + ":validPointGrade " + e.getMessage());
alertInvalidPoint(state, gradeString);
}
}
}
else
{
// grade is "."
addAlert(state, rb.getString("plesuse1"));
}
}
else
{
// There is no decimal point; should be int number
String gradeString = grade + "0";
try
{
Integer.parseInt(gradeString);
}
catch (NumberFormatException e)
{
M_log.warn(this + ":validPointGrade " + e.getMessage());
alertInvalidPoint(state, gradeString);
}
}
}
catch (ParseException e) {
// grade does not meet the number format and could not be parsed
addAlert(state, rb.getString("plesuse1"));
}
}
}
return grade;
} // validPointGrade
/**
* valid grade for point based type
*/
private void validLetterGrade(SessionState state, String grade)
{
String VALID_CHARS_FOR_LETTER_GRADE = " ABCDEFGHIJKLMNOPQRSTUVWXYZ+-";
boolean invalid = false;
if (grade != null)
{
grade = grade.toUpperCase();
for (int i = 0; i < grade.length() && !invalid; i++)
{
char c = grade.charAt(i);
if (VALID_CHARS_FOR_LETTER_GRADE.indexOf(c) == -1)
{
invalid = true;
}
}
if (invalid)
{
addAlert(state, rb.getString("plesuse0"));
}
}
}
private void alertInvalidPoint(SessionState state, String grade)
{
String VALID_CHARS_FOR_INT = "-01234567890";
boolean invalid = false;
// case 1: contains invalid char for int
for (int i = 0; i < grade.length() && !invalid; i++)
{
char c = grade.charAt(i);
if (VALID_CHARS_FOR_INT.indexOf(c) == -1)
{
invalid = true;
}
}
if (invalid)
{
addAlert(state, rb.getString("plesuse1"));
}
else
{
int maxInt = Integer.MAX_VALUE / 10;
int maxDec = Integer.MAX_VALUE - maxInt * 10;
// case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10
addAlert(state, rb.getFormattedMessage("plesuse4", new Object[]{grade.substring(0, grade.length()-1) + "." + grade.substring(grade.length()-1), maxInt + "." + maxDec}));
}
}
/**
* display grade properly
*/
private String displayGrade(SessionState state, String grade)
{
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (grade != null && (grade.length() >= 1))
{
// 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);
// check if grade uses a comma as separator because of number format and change to a point
// remove group separator
DecimalFormat dcformat = (DecimalFormat) nbFormat;
String decSeparator = dcformat.getDecimalFormatSymbols().getDecimalSeparator() + "";
if (",".equals(decSeparator) && grade.indexOf(decSeparator) != -1) {
grade = grade.replace(",", ".");
}
if (grade.indexOf(".") != -1)
{
if (grade.startsWith("."))
{
grade = "0".concat(grade);
}
else if (grade.endsWith("."))
{
grade = grade.concat("0");
}
}
else
{
try
{
Integer.parseInt(grade);
grade = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1);
}
catch (NumberFormatException e)
{
// alert
alertInvalidPoint(state, grade);
M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage());
}
}
try {
// show grade in localized number format
Double dblGrade = new Double(grade);
grade = nbFormat.format(dblGrade);
}
catch (Exception e) {
// alert
alertInvalidPoint(state, grade);
M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage());
}
}
else
{
grade = "";
}
}
return grade;
} // displayGrade
/**
* scale the point value by 10 if there is a valid point grade
*/
private String scalePointGrade(SessionState state, String point)
{
point = validPointGrade(state, point);
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (point != null && (point.length() >= 1))
{
// when there is decimal points inside the grade, scale the number by 10
// but only one decimal place is supported
// for example, change 100.0 to 1000
int index = point.indexOf(".");
if (index != -1)
{
if (index == 0)
{
// if the point is the first char, add a 0 for the integer part
point = "0".concat(point.substring(1));
}
else if (index < point.length() - 1)
{
// use scale integer for gradePoint
point = point.substring(0, index) + point.substring(index + 1);
}
else
{
// decimal point is the last char
point = point.substring(0, index) + "0";
}
}
else
{
// if there is no decimal place, scale up the integer by 10
point = point + "0";
}
// filter out the "zero grade"
if ("00".equals(point))
{
point = "0";
}
}
}
if (StringUtil.trimToNull(point) != null)
{
try
{
point = Integer.valueOf(point).toString();
}
catch (Exception e)
{
M_log.warn(this + " scalePointGrade: cannot parse " + point + " into integer. " + e.getMessage());
}
}
return point;
} // scalePointGrade
/**
* Processes formatted text that is coming back from the browser (from the formatted text editing widget).
*
* @param state
* Used to pass in any user-visible alerts or errors when processing the text
* @param strFromBrowser
* The string from the browser
* @param checkForFormattingErrors
* Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors.
* @return The formatted text
*/
private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors)
{
StringBuilder alertMsg = new StringBuilder();
try
{
boolean replaceWhitespaceTags = true;
String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors,
replaceWhitespaceTags);
if (alertMsg.length() > 0) addAlert(state, alertMsg.toString());
return text;
}
catch (Exception e)
{
M_log.warn(this + ":processFormattedTextFromBrowser " + e.getMessage());
return strFromBrowser;
}
}
/**
* Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced.
*/
private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser)
{
if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser;
StringBuilder buf = new StringBuilder(strFromBrowser);
int pos = -1;
int numopentags = 0;
while ((pos = buf.indexOf("{{")) != -1)
{
buf.replace(pos, pos + "{{".length(), "<ins>");
numopentags++;
}
while ((pos = buf.indexOf("}}")) != -1)
{
buf.replace(pos, pos + "}}".length(), "</ins>");
numopentags--;
}
while (numopentags > 0)
{
buf.append("</ins>");
numopentags--;
}
boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors
buf = new StringBuilder(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors));
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();
}
/**
* Called to deal with old Chef-style assignment feedback annotation, {{like this}}.
*
* @param value
* A formatted text string that may contain {{}} style markup
* @return HTML ready to for display on a browser
*/
public static String escapeAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
value = fixAssignmentFeedback(value);
StringBuilder buf = new StringBuilder(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());
}
/**
* Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget)
*/
public static String escapeAssignmentFeedbackTextarea(String value)
{
if (value == null || value.length() == 0) return value;
value = fixAssignmentFeedback(value);
return FormattedText.escapeHtmlFormattedTextarea(value);
}
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
private static String fixAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuilder buf = new StringBuilder(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
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
public static String showPrevFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuilder buf = new StringBuilder(value);
int pos = -1;
// <br/> -> \n
while ((pos = buf.indexOf("\n")) != -1)
{
buf.replace(pos, pos + "\n".length(), "<br />");
}
return buf.toString();
} // showPrevFeedback
private boolean alertGlobalNavigation(SessionState state, RunData data)
{
String mode = (String) state.getAttribute(STATE_MODE);
ParameterParser params = data.getParameters();
if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode) || MODE_STUDENT_PREVIEW_SUBMISSION.equals(mode)
|| MODE_STUDENT_VIEW_GRADE.equals(mode) || MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode)
|| MODE_INSTRUCTOR_DELETE_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode)
|| MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION.equals(mode)|| MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode)
|| MODE_INSTRUCTOR_VIEW_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode))
{
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null)
{
addAlert(state, rb.getString("alert.globalNavi"));
state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE);
if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode))
{
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT),
checkForFormattingErrors);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null)
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true");
}
state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt"));
// TODO: file picker to save in dropbox? -ggolden
// User[] users = { UserDirectoryService.getCurrentUser() };
// state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users);
}
else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode))
{
setNewAssignmentParameters(data, false);
}
else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode))
{
readGradeForm(data, state, "read");
}
return true;
}
}
return false;
} // alertGlobalNavigation
/**
* Dispatch function inside add submission page
*/
public void doRead_add_submission_form(RunData data)
{
String option = data.getParameters().getString("option");
if ("cancel".equals(option))
{
// cancel
doCancel_show_submission(data);
}
else if ("preview".equals(option))
{
// preview
doPreview_submission(data);
}
else if ("save".equals(option))
{
// save draft
doSave_submission(data);
}
else if ("post".equals(option))
{
// post
doPost_submission(data);
}
else if ("revise".equals(option))
{
// done preview
doDone_preview_submission(data);
}
else if ("attach".equals(option))
{
// attach
ToolSession toolSession = SessionManager.getCurrentToolSession();
String userId = SessionManager.getCurrentSessionUserId();
String siteId = SiteService.getUserSiteId(userId);
String collectionId = m_contentHostingService.getSiteCollection(siteId);
toolSession.setAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID, collectionId);
doAttachments(data);
}
else if ("removeAttachment".equals(option))
{
// remove selected attachment
doRemove_attachment(data);
}
}
public void doRemove_attachment(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String removeAttachmentId = params.getString("currentAttachment");
List attachments = state.getAttribute(ATTACHMENTS) == null?null:((List) state.getAttribute(ATTACHMENTS)).isEmpty()?null:(List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
Reference found = null;
for(Object attachment : attachments)
{
if (((Reference) attachment).getId().equals(removeAttachmentId))
{
found = (Reference) attachment;
break;
}
}
if (found != null)
{
attachments.remove(found);
// refresh state variable
state.setAttribute(ATTACHMENTS, attachments);
}
}
}
/**
* Set default score for all ungraded non electronic submissions
* @param data
*/
public void doSet_defaultNotGradedNonElectronicScore(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String grade = StringUtil.trimToNull(params.getString("defaultGrade"));
if (grade == null)
{
addAlert(state, rb.getString("plespethe2"));
}
String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
// record the default grade setting for no-submission
AssignmentEdit aEdit = editAssignment(assignmentId, "doSet_defaultNotGradedNonElectronicScore", state, false);
if (aEdit != null)
{
aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade);
AssignmentService.commitEdit(aEdit);
}
Assignment a = getAssignment(assignmentId, "doSet_defaultNotGradedNonElectronicScore", state);
if (a != null && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
//for point-based grades
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))}));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
M_log.warn(this + ":setDefaultNotGradedNonElectronicScore " + e.getMessage());
alertInvalidPoint(state, grade);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade = scalePointGrade(state, grade);
}
}
if (grade != null && state.getAttribute(STATE_MESSAGE) == null)
{
// get the user list
List submissions = AssignmentService.getSubmissions(a);
for (int i = 0; i<submissions.size(); i++)
{
// get the submission object
AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i);
if (submission.getSubmitted() && !submission.getGraded())
{
String sRef = submission.getReference();
// update the grades for those existing non-submissions
AssignmentSubmissionEdit sEdit = editSubmission(sRef, "doSet_defaultNotGradedNonElectronicScore", state);
if (sEdit != null)
{
sEdit.setGrade(grade);
sEdit.setGraded(true);
AssignmentService.commitEdit(sEdit);
}
}
}
}
}
/**
*
*/
public void doSet_defaultNoSubmissionScore(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String grade = StringUtil.trimToNull(params.getString("defaultGrade"));
if (grade == null)
{
addAlert(state, rb.getString("plespethe2"));
}
String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
// record the default grade setting for no-submission
AssignmentEdit aEdit = editAssignment(assignmentId, "doSet_defaultNoSubmissionScore", state, false);
if (aEdit != null)
{
aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade);
AssignmentService.commitEdit(aEdit);
}
Assignment a = getAssignment(assignmentId, "doSet_defaultNoSubmissionScore", state);
if (a != null && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
//for point-based grades
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))}));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
M_log.warn(this + ":setDefaultNoSubmissionScore " + e.getMessage());
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade = scalePointGrade(state, grade);
}
}
if (grade != null && state.getAttribute(STATE_MESSAGE) == null)
{
// get the submission list
List submissions = AssignmentService.getSubmissions(a);
for (int i = 0; i<submissions.size(); i++)
{
// get the submission object
AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i);
if (StringUtil.trimToNull(submission.getGrade()) == null)
{
// update the grades for those existing non-submissions
AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "doSet_defaultNoSubmissionScore", state);
if (sEdit != null)
{
sEdit.setGrade(grade);
sEdit.setSubmitted(true);
sEdit.setGraded(true);
AssignmentService.commitEdit(sEdit);
}
}
else if (StringUtil.trimToNull(submission.getGrade()) != null && !submission.getGraded())
{
// correct the grade status if there is a grade but the graded is false
AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "doSet_defaultNoSubmissionScore", state);
if (sEdit != null)
{
sEdit.setGraded(true);
AssignmentService.commitEdit(sEdit);
}
}
}
}
}
/**
*
* @return
*/
public void doDownload_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String flow = params.getString("flow");
if ("upload".equals(flow))
{
// upload
doUpload_all(data);
}
else if ("download".equals(flow))
{
// upload
doDownload_all(data);
}
else if ("cancel".equals(flow))
{
// cancel
doCancel_download_upload_all(data);
}
}
public void doDownload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
}
public void doUpload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String contextString = ToolManager.getCurrentPlacement().getContext();
String toolTitle = ToolManager.getTool(ASSIGNMENT_TOOL_ID).getTitle();
String aReference = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
String associateGradebookAssignment = null;
List<String> choices = params.getStrings("choices") != null?new ArrayList(Arrays.asList(params.getStrings("choices"))):null;
if (choices == null || choices.size() == 0)
{
// has to choose one upload feature
addAlert(state, rb.getString("uploadall.alert.choose.element"));
}
else
{
boolean hasSubmissionText = false;
boolean hasSubmissionAttachment = false;
boolean hasGradeFile = false;
boolean hasFeedbackText = false;
boolean hasComment = false;
boolean hasFeedbackAttachment = false;
boolean releaseGrades = false;
// check against the content elements selection
if (choices.contains("studentSubmissionText"))
{
// should contain student submission text information
hasSubmissionText = true;
}
if (choices.contains("studentSubmissionAttachment"))
{
// should contain student submission attachment information
hasSubmissionAttachment = true;
}
if (choices.contains("gradeFile"))
{
// should contain grade file
hasGradeFile = true;
}
if (choices.contains("feedbackTexts"))
{
// inline text
hasFeedbackText = true;
}
if (choices.contains("feedbackComments"))
{
// comments.txt should be available
hasComment = true;
}
if (choices.contains("feedbackAttachments"))
{
// feedback attachment
hasFeedbackAttachment = true;
}
if (params.getString("release") != null)
{
// comments.xml should be available
releaseGrades = params.getBoolean("release");
}
state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT, Boolean.valueOf(hasSubmissionText));
state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT, Boolean.valueOf(hasSubmissionAttachment));
state.setAttribute(UPLOAD_ALL_HAS_GRADEFILE, Boolean.valueOf(hasGradeFile));
state.setAttribute(UPLOAD_ALL_HAS_COMMENTS, Boolean.valueOf(hasComment));
state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT, Boolean.valueOf(hasFeedbackText));
state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT, Boolean.valueOf(hasFeedbackAttachment));
state.setAttribute(UPLOAD_ALL_RELEASE_GRADES, Boolean.valueOf(releaseGrades));
// constructor the hashtable for all submission objects
Hashtable submissionTable = new Hashtable();
List submissions = null;
Assignment assignment = getAssignment(aReference, "doUpload_all", state);
if (assignment != null)
{
associateGradebookAssignment = StringUtil.trimToNull(assignment.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
submissions = AssignmentService.getSubmissions(assignment);
if (submissions != null)
{
Iterator sIterator = submissions.iterator();
while (sIterator.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
User[] users = s.getSubmitters();
if (users != null && users.length > 0 && users[0] != null)
{
submissionTable.put(users[0].getEid(), new UploadGradeWrapper(s.getGrade(), s.getSubmittedText(), s.getFeedbackComment(), hasSubmissionAttachment?new Vector():s.getSubmittedAttachments(), hasFeedbackAttachment?new Vector():s.getFeedbackAttachments(), (s.getSubmitted() && s.getTimeSubmitted() != null)?s.getTimeSubmitted().toString():"", s.getFeedbackText()));
}
}
}
}
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = params.getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1");
int max_bytes = 1024 * 1024;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
M_log.warn(this + ":doUpload_all_upload " + e.getMessage());
}
if(fileFromUpload == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded"));
}
else
{
String contentType = fileFromUpload.getContentType();
if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0
|| (!"application/zip".equals(contentType) && !"application/x-zip-compressed".equals(contentType)))
{
// no file
addAlert(state, rb.getString("uploadall.alert.zipFile"));
}
else
{
InputStream fileContentStream = fileFromUpload.getInputStream();
int contentLength = data.getRequest().getContentLength();
if(contentLength >= max_bytes)
{
addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded"));
}
else if(fileContentStream != null)
{
// a flag value for checking whether the zip file is of proper format:
// should have a grades.csv file if there is no user folders
boolean zipHasGradeFile = false;
// and if have any folder structures, those folders should be named after at least one site user (zip file could contain user names who is no longer inside the site)
boolean zipHasFolder = false;
boolean zipHasFolderValidUserId = false;
FileOutputStream tmpFileOut = null;
try
{
File f = File.createTempFile(String.valueOf(System.currentTimeMillis()),"");
tmpFileOut = new FileOutputStream(f);
writeToStream(fileContentStream, tmpFileOut);
tmpFileOut.flush();
tmpFileOut.close();
ZipFile zipFile = new ZipFile(f, "UTF-8");
Enumeration<ZipEntry> zipEntries = zipFile.getEntries();
ZipEntry entry;
while (zipEntries.hasMoreElements())
{
entry = zipEntries.nextElement();
String entryName = entry.getName();
if (!entry.isDirectory() && entryName.indexOf("/.") == -1)
{
if (entryName.endsWith("grades.csv"))
{
// at least the zip file has a grade.csv
zipHasGradeFile = true;
if (hasGradeFile)
{
// read grades.cvs from zip
String result = StringUtil.trimToZero(readIntoString(zipFile.getInputStream(entry)));
String[] lines=null;
if (result.indexOf("\r\n") != -1)
lines = result.split("\r\n");
else if (result.indexOf("\r") != -1)
lines = result.split("\r");
else if (result.indexOf("\n") != -1)
lines = result.split("\n");
if (lines != null )
{
for (int i = 3; i<lines.length; i++)
{
// escape the first three header lines
String[] items = lines[i].split(",");
if (items.length > 4)
{
// has grade information
try
{
User u = UserDirectoryService.getUserByEid(items[1]/*user eid*/);
if (u != null)
{
UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(u.getEid());
if (w != null)
{
String itemString = items[4];
int gradeType = assignment.getContent().getTypeOfGrade();
if (gradeType == Assignment.SCORE_GRADE_TYPE)
{
validPointGrade(state, itemString);
}
else
{
validLetterGrade(state, itemString);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE?scalePointGrade(state, itemString):itemString);
submissionTable.put(u.getEid(), w);
}
}
}
}
catch (Exception e )
{
M_log.warn(this + ":doUpload_all_upload " + e.getMessage());
}
}
}
}
}
}
else
{
// get user eid part
String userEid = "";
if (entryName.indexOf("/") != -1)
{
// there is folder structure inside zip
if (!zipHasFolder) zipHasFolder = true;
// remove the part of zip name
userEid = entryName.substring(entryName.indexOf("/")+1);
// get out the user name part
if (userEid.indexOf("/") != -1)
{
userEid = userEid.substring(0, userEid.indexOf("/"));
}
// get the eid part
if (userEid.indexOf("(") != -1)
{
userEid = userEid.substring(userEid.indexOf("(")+1, userEid.indexOf(")"));
}
userEid=StringUtil.trimToNull(userEid);
}
if (submissionTable.containsKey(userEid))
{
if (!zipHasFolderValidUserId) zipHasFolderValidUserId = true;
if (hasComment && entryName.indexOf("comments") != -1)
{
// read the comments file
String comment = getBodyTextFromZipHtml(zipFile.getInputStream(entry));
if (comment != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
r.setComment(comment);
submissionTable.put(userEid, r);
}
}
if (hasFeedbackText && entryName.indexOf("feedbackText") != -1)
{
// upload the feedback text
String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry));
if (text != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
r.setFeedbackText(text);
submissionTable.put(userEid, r);
}
}
if (hasSubmissionText && entryName.indexOf("_submissionText") != -1)
{
// upload the student submission text
String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry));
if (text != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
r.setText(text);
submissionTable.put(userEid, r);
}
}
if (hasSubmissionAttachment)
{
// upload the submission attachment
String submissionFolder = "/" + rb.getString("download.submission.attachment") + "/";
if ( entryName.indexOf(submissionFolder) != -1)
{
// clear the submission attachment first
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
submissionTable.put(userEid, r);
submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "submission");
}
}
if (hasFeedbackAttachment)
{
// upload the feedback attachment
String submissionFolder = "/" + rb.getString("download.feedback.attachment") + "/";
if ( entryName.indexOf(submissionFolder) != -1)
{
// clear the feedback attachment first
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
submissionTable.put(userEid, r);
submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "feedback");
}
}
// if this is a timestamp file
if (entryName.indexOf("timestamp") != -1)
{
byte[] timeStamp = readIntoBytes(zipFile.getInputStream(entry), entryName, entry.getSize());
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
r.setSubmissionTimestamp(new String(timeStamp));
submissionTable.put(userEid, r);
}
}
}
}
}
}
catch (IOException e)
{
// uploaded file is not a valid archive
addAlert(state, rb.getString("uploadall.alert.zipFile"));
M_log.warn(this + ":doUpload_all_upload " + e.getMessage());
}
finally
{
if (tmpFileOut != null) {
try {
tmpFileOut.close();
} catch (IOException e) {
M_log.warn(this + "doUpload_all: Error closing temp file output stream: " + e.toString());
}
}
if (fileContentStream != null) {
try {
fileContentStream.close();
} catch (IOException e) {
M_log.warn(this + "doUpload_all: Error closing file upload stream: " + e.toString());
}
}
}
if ((!zipHasGradeFile && !zipHasFolder) // generate error when there is no grade file and no folder structure
|| (zipHasFolder && !zipHasFolderValidUserId)) // generate error when there is folder structure but not matching one user id
{
// alert if the zip is of wrong format
addAlert(state, rb.getString("uploadall.alert.wrongZipFormat"));
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// update related submissions
if (assignment != null && submissions != null)
{
Iterator sIterator = submissions.iterator();
while (sIterator.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
User[] users = s.getSubmitters();
if (users != null && users.length > 0 && users[0] != null)
{
String uName = users[0].getEid();
if (submissionTable.containsKey(uName))
{
// update the AssignmetnSubmission record
AssignmentSubmissionEdit sEdit = editSubmission(s.getReference(), "doUpload_all", state);
if (sEdit != null)
{
UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(uName);
// the submission text
if (hasSubmissionText)
{
sEdit.setSubmittedText(w.getText());
}
// the feedback text
if (hasFeedbackText)
{
sEdit.setFeedbackText(w.getFeedbackText());
}
// the submission attachment
if (hasSubmissionAttachment)
{
// update the submission attachments with newly added ones from zip file
List submittedAttachments = sEdit.getSubmittedAttachments();
for (Iterator attachments = w.getSubmissionAttachments().iterator(); attachments.hasNext();)
{
Reference a = (Reference) attachments.next();
if (!submittedAttachments.contains(a))
{
sEdit.addSubmittedAttachment(a);
}
}
}
// the feedback attachment
if (hasFeedbackAttachment)
{
List feedbackAttachments = sEdit.getFeedbackAttachments();
for (Iterator attachments = w.getFeedbackAttachments().iterator(); attachments.hasNext();)
{
// update the feedback attachments with newly added ones from zip file
Reference a = (Reference) attachments.next();
if (!feedbackAttachments.contains(a))
{
sEdit.addFeedbackAttachment(a);
}
}
}
// the feedback comment
if (hasComment)
{
sEdit.setFeedbackComment(w.getComment());
}
// the grade file
if (hasGradeFile)
{
// set grade
String grade = StringUtil.trimToNull(w.getGrade());
sEdit.setGrade(grade);
if (grade != null && !grade.equals(rb.getString("gen.nograd")) && !"ungraded".equals(grade))
sEdit.setGraded(true);
}
// release or not
if (sEdit.getGraded())
{
sEdit.setGradeReleased(releaseGrades);
sEdit.setReturned(releaseGrades);
}
else
{
sEdit.setGradeReleased(false);
sEdit.setReturned(false);
}
if (releaseGrades && sEdit.getGraded())
{
sEdit.setTimeReturned(TimeService.newTime());
}
// if the current submission lacks timestamp while the timestamp exists inside the zip file
if (StringUtil.trimToNull(w.getSubmissionTimeStamp()) != null && sEdit.getTimeSubmitted() == null)
{
sEdit.setTimeSubmitted(TimeService.newTimeGmt(w.getSubmissionTimeStamp()));
sEdit.setSubmitted(true);
}
// for further information
boolean graded = sEdit.getGraded();
String sReference = sEdit.getReference();
// commit
AssignmentService.commitEdit(sEdit);
if (releaseGrades && graded)
{
// update grade in gradebook
if (associateGradebookAssignment != null)
{
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update", -1);
}
}
}
}
}
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// go back to the list of submissions view
cleanUploadAllContext(state);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
}
}
/**
* This is to get the submission or feedback attachment from the upload zip file into the submission object
* @param state
* @param submissionTable
* @param zin
* @param entry
* @param entryName
* @param userEid
* @param submissionOrFeedback
*/
private Hashtable uploadZipAttachments(SessionState state, Hashtable submissionTable, InputStream zin, ZipEntry entry, String entryName, String userEid, String submissionOrFeedback) {
// upload all the files as instructor attachments to the submission for grading purpose
String fName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length());
ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
try
{
// get file extension for detecting content type
// ignore those hidden files
String extension = "";
if(!fName.contains(".") || (fName.contains(".") && fName.indexOf(".") != 0))
{
// add the file as attachment
ResourceProperties properties = m_contentHostingService.newResourceProperties();
properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fName);
String[] parts = fName.split("\\.");
if(parts.length > 1)
{
extension = parts[parts.length - 1];
}
try {
String contentType = ((ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)).getContentType(extension);
ContentResourceEdit attachment = m_contentHostingService.addAttachmentResource(fName);
attachment.setContent(zin);
attachment.setContentType(contentType);
attachment.getPropertiesEdit().addAll(properties);
m_contentHostingService.commitResource(attachment);
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
List attachments = "submission".equals(submissionOrFeedback)?r.getSubmissionAttachments():r.getFeedbackAttachments();
attachments.add(EntityManager.newReference(attachment.getReference()));
if ("submission".equals(submissionOrFeedback))
{
r.setSubmissionAttachments(attachments);
}
else
{
r.setFeedbackAttachments(attachments);
}
submissionTable.put(userEid, r);
}
catch (Exception e)
{
M_log.warn(this + ":doUploadZipAttachments problem commit resource " + e.getMessage());
}
}
}
catch (Exception ee)
{
M_log.warn(this + ":doUploadZipAttachments " + ee.getMessage());
}
return submissionTable;
}
private String getBodyTextFromZipHtml(InputStream zin)
{
String rv = "";
try
{
rv = StringUtil.trimToNull(readIntoString(zin));
}
catch (IOException e)
{
M_log.warn(this + ":getBodyTextFromZipHtml " + e.getMessage());
}
if (rv != null)
{
int start = rv.indexOf("<body>");
int end = rv.indexOf("</body>");
if (start != -1 && end != -1)
{
// get the text in between
rv = rv.substring(start+6, end);
}
}
return rv;
}
private byte[] readIntoBytes(InputStream zin, String fName, long length) throws IOException {
byte[] buffer = new byte[4096];
File f = File.createTempFile("asgnup", "tmp");
FileOutputStream fout = new FileOutputStream(f);
try {
int len;
while ((len = zin.read(buffer)) > 0)
{
fout.write(buffer, 0, len);
}
zin.close();
} finally {
try
{
fout.close(); // The file channel needs to be closed before the deletion.
}
catch (IOException ioException)
{
M_log.warn(this + "readIntoBytes: problem closing FileOutputStream " + ioException.getMessage());
}
}
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
byte[] data = null;
try {
data = new byte[(int)(fc.size())]; // fc.size returns the size of the file which backs the channel
ByteBuffer bb = ByteBuffer.wrap(data);
fc.read(bb);
} finally {
try
{
fc.close(); // The file channel needs to be closed before the deletion.
}
catch (IOException ioException)
{
M_log.warn(this + "readIntoBytes: problem closing FileChannel " + ioException.getMessage());
}
try
{
fis.close(); // The file inputstream needs to be closed before the deletion.
}
catch (IOException ioException)
{
M_log.warn(this + "readIntoBytes: problem closing FileInputStream " + ioException.getMessage());
}
}
//remove the file
f.delete();
return data;
}
private String readIntoString(InputStream zin) throws IOException
{
StringBuilder buffer = new StringBuilder();
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
try
{
size = zin.read(data, 0, data.length);
if (size > 0)
{
buffer.append(new String(data, 0, size));
}
else
{
break;
}
}
catch (IOException e)
{
M_log.warn(this + ":readIntoString " + e.getMessage());
}
}
return buffer.toString();
}
/**
*
* @return
*/
public void doCancel_download_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
cleanUploadAllContext(state);
}
/**
* clean the state variabled used by upload all process
*/
private void cleanUploadAllContext(SessionState state)
{
state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT);
state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT);
state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT);
state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT);
state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE);
state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS);
state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES);
}
/**
* Action is to preparing to go to the download all file
*/
public void doPrep_download_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DOWNLOAD_ALL);
} // doPrep_download_all
/**
* Action is to preparing to go to the upload files
*/
public void doPrep_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_UPLOAD_ALL);
} // doPrep_upload_all
/**
* the UploadGradeWrapper class to be used for the "upload all" feature
*/
public class UploadGradeWrapper
{
/**
* the grade
*/
String m_grade = null;
/**
* the text
*/
String m_text = null;
/**
* the submission attachment list
*/
List m_submissionAttachments = EntityManager.newReferenceList();
/**
* the comment
*/
String m_comment = "";
/**
* the timestamp
*/
String m_timeStamp="";
/**
* the feedback text
*/
String m_feedbackText="";
/**
* the feedback attachment list
*/
List m_feedbackAttachments = EntityManager.newReferenceList();
public UploadGradeWrapper(String grade, String text, String comment, List submissionAttachments, List feedbackAttachments, String timeStamp, String feedbackText)
{
m_grade = grade;
m_text = text;
m_comment = comment;
m_submissionAttachments = submissionAttachments;
m_feedbackAttachments = feedbackAttachments;
m_feedbackText = feedbackText;
m_timeStamp = timeStamp;
}
/**
* Returns grade string
*/
public String getGrade()
{
return m_grade;
}
/**
* Returns the text
*/
public String getText()
{
return m_text;
}
/**
* Returns the comment string
*/
public String getComment()
{
return m_comment;
}
/**
* Returns the submission attachment list
*/
public List getSubmissionAttachments()
{
return m_submissionAttachments;
}
/**
* Returns the feedback attachment list
*/
public List getFeedbackAttachments()
{
return m_feedbackAttachments;
}
/**
* submission timestamp
* @return
*/
public String getSubmissionTimeStamp()
{
return m_timeStamp;
}
/**
* feedback text/incline comment
* @return
*/
public String getFeedbackText()
{
return m_feedbackText;
}
/**
* set the grade string
*/
public void setGrade(String grade)
{
m_grade = grade;
}
/**
* set the text
*/
public void setText(String text)
{
m_text = text;
}
/**
* set the comment string
*/
public void setComment(String comment)
{
m_comment = comment;
}
/**
* set the submission attachment list
*/
public void setSubmissionAttachments(List attachments)
{
m_submissionAttachments = attachments;
}
/**
* set the attachment list
*/
public void setFeedbackAttachments(List attachments)
{
m_feedbackAttachments = attachments;
}
/**
* set the submission timestamp
*/
public void setSubmissionTimestamp(String timeStamp)
{
m_timeStamp = timeStamp;
}
/**
* set the feedback text
*/
public void setFeedbackText(String feedbackText)
{
m_feedbackText = feedbackText;
}
}
private List<DecoratedTaggingProvider> initDecoratedProviders() {
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>();
for (TaggingProvider provider : taggingManager.getProviders())
{
providers.add(new DecoratedTaggingProvider(provider));
}
return providers;
}
private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
if (providers == null)
{
providers = initDecoratedProviders();
state.setAttribute(mode + PROVIDER_LIST, providers);
}
context.put("providers", providers);
return providers;
}
private void addActivity(Context context, Assignment assignment)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
context.put("activity", assignmentActivityProducer
.getActivity(assignment));
String placement = ToolManager.getCurrentPlacement().getId();
context.put("iframeId", Validator.escapeJavascript("Main" + placement));
}
private void addItem(Context context, AssignmentSubmission submission, String userId)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
context.put("item", assignmentActivityProducer
.getItem(submission, userId));
}
private ContentReviewService contentReviewService;
public String getReportURL(Long score) {
getContentReviewService();
return contentReviewService.getIconUrlforScore(score);
}
private void getContentReviewService() {
if (contentReviewService == null)
{
contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName());
}
}
/******************* model answer *********/
/**
* add model answer input into state variables
*/
public void doModel_answer(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String text = StringUtil.trimToNull(params.get("modelanswer_text"));
if (text == null)
{
// no text entered for model answer
addAlert(state, rb.getString("modelAnswer.show_to_student.alert.noText"));
}
int showTo = params.getInt("modelanswer_showto");
if (showTo == 0)
{
// no show to criteria specifided for model answer
addAlert(state, rb.getString("modelAnswer.show_to_student.alert.noShowTo"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER, Boolean.TRUE);
state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER_TEXT, text);
state.setAttribute(NEW_ASSIGNMENT_MODEL_SHOW_TO_STUDENT, showTo);
//state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER_ATTACHMENT);
}
}
private void assignment_resubmission_option_into_context(Context context, SessionState state)
{
context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null ? (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) : null;
String allowResubmitTimeString = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME) != null ? (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME) : null;
// the resubmit number
if (allowResubmitNumber != null && !"0".equals(allowResubmitNumber))
{
context.put("value_allowResubmitNumber", Integer.valueOf(allowResubmitNumber));
context.put("resubmitNumber", "-1".equals(allowResubmitNumber) ? rb.getString("allow.resubmit.number.unlimited"): allowResubmitNumber);
// put allow resubmit time information into context
putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
// resubmit close time
Time resubmitCloseTime = null;
if (allowResubmitTimeString != null)
{
resubmitCloseTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString));
}
// put into context
if (resubmitCloseTime != null)
{
context.put("resubmitCloseTime", resubmitCloseTime.toStringLocalFull());
}
}
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
}
private void assignment_resubmission_option_into_state(Assignment a, AssignmentSubmission s, SessionState state)
{
String allowResubmitNumber = null;
String allowResubmitTimeString = null;
if (s != null)
{
// if submission is present, get the resubmission values from submission object first
ResourceProperties sProperties = s.getProperties();
allowResubmitNumber = sProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
allowResubmitTimeString = sProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
else if (a != null)
{
// otherwise, if assignment is present, get the resubmission values from assignment object next
ResourceProperties aProperties = a.getProperties();
allowResubmitNumber = aProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
allowResubmitTimeString = aProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
if (StringUtil.trimToNull(allowResubmitNumber) != null)
{
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber);
}
else
{
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
if (allowResubmitTimeString == null)
{
// default setting
allowResubmitTimeString = String.valueOf(a.getCloseTime().getTime());
}
Time allowResubmitTime = null;
if (allowResubmitTimeString != null)
{
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, allowResubmitTimeString);
// get time object
allowResubmitTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString));
}
else
{
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
if (allowResubmitTime != null)
{
// set up related state variables
putTimePropertiesInState(state, allowResubmitTime, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
}
}
/**
* save the resubmit option for selected users
* @param data
*/
public void doSave_resubmission_option(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// read in user input into state variable
if (StringUtil.trimToNull(params.getString("allowResToggle")) != null)
{
if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// read in allowResubmit params
readAllowResubmitParams(params, state, null);
}
}
else
{
resetAllowResubmitParams(state);
}
String[] userIds = params.getStrings("selectedAllowResubmit");
if (userIds == null || userIds.length == 0)
{
addAlert(state, rb.getString("allowResubmission.nouser"));
}
else
{
for (int i = 0; i < userIds.length; i++)
{
String userId = userIds[i];
try
{
User u = UserDirectoryService.getUser(userId);
String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
AssignmentSubmission submission = getSubmission(assignmentRef, u, "doSave_resubmission_option", state);
if (submission != null)
{
AssignmentSubmissionEdit submissionEdit = editSubmission(submission.getReference(), "doSave_resubmission_option", state);
if (submissionEdit != null)
{
// get resubmit number
ResourcePropertiesEdit pEdit = submissionEdit.getPropertiesEdit();
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null)
{
// get resubmit time
Time closeTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
}
else
{
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
// save
AssignmentService.commitEdit(submissionEdit);
}
}
}
catch (Exception userException)
{
M_log.warn(this + ":doSave_resubmission_option error getting user with id " + userId + " " + userException.getMessage());
}
}
}
// make sure the options are exposed in UI
state.setAttribute(SHOW_ALLOW_RESUBMISSION, Boolean.TRUE);
}
/**
* upload local file for attachment
* @param data
* @param singleFileUpload
*/
public void doAttachUpload(RunData data, boolean singleFileUpload)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ToolSession toolSession = SessionManager.getCurrentToolSession();
ParameterParser params = data.getParameters ();
String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1");
long max_bytes = 1024L * 1024L;
try
{
max_bytes = Long.parseLong(max_file_size_mb) * 1024L * 1024L;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024L * 1024L;
}
int submissionFileCount = 0;
String submissionFileCountString = params.getString("submissionFileCount");
if (params.getString("submissionFileCount") != null)
{
try
{
submissionFileCount = Integer.valueOf(params.getString("submissionFileCount"));
}
catch (NumberFormatException e)
{
M_log.warn(this + ".doAttachUpload: NumberFormatException " + params.getString("submissionFileCount"));
}
}
// construct the state variable for attachment list
List attachments = state.getAttribute(ATTACHMENTS) != null? (List) state.getAttribute(ATTACHMENTS) : EntityManager.newReferenceList();
for (int i = 0; i<submissionFileCount; i++)
{
FileItem fileitem = null;
try
{
fileitem = params.getFileItem("upload" + i);
}
catch(Exception e)
{
}
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_file_size_mb }));
//addAlert(state, hrb.getString("size") + " " + max_file_size_mb + "MB " + hrb.getString("exceeded2"));
}
else if (singleFileUpload && (fileitem.getFileName() == null || fileitem.getFileName().length() == 0))
{
// only if in the single file upload case, need to warn user to upload a local file
addAlert(state, rb.getString("choosefile7"));
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
InputStream fileContentStream = fileitem.getInputStream();
int contentLength = data.getRequest().getContentLength();
String contentType = fileitem.getContentType();
if(contentLength >= max_bytes)
{
addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_file_size_mb }));
// addAlert(state, hrb.getString("size") + " " + max_file_size_mb + "MB " + hrb.getString("exceeded2"));
}
else if(fileContentStream != null)
{
// we just want the file name part - strip off any drive and path stuff
String name = Validator.getFileName(filename);
String resourceId = Validator.escapeResourceName(name);
// make a set of properties to add for the new resource
ResourcePropertiesEdit props = m_contentHostingService.newResourceProperties();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
props.addProperty(ResourceProperties.PROP_DESCRIPTION, filename);
// make an attachment resource for this URL
try
{
String siteId = ToolManager.getCurrentPlacement().getContext();
// add attachment
enableSecurityAdvisor();
ContentResource attachment = m_contentHostingService.addAttachmentResource(resourceId, siteId, "Assignments", contentType, fileContentStream, props);
disableSecurityAdvisor();
try
{
Reference ref = EntityManager.newReference(m_contentHostingService.getReference(attachment.getId()));
attachments.add(ref);
}
catch(Exception ee)
{
M_log.warn(this + "doAttachUpload cannot find reference for " + attachment.getId() + ee.getMessage());
}
state.setAttribute(ATTACHMENTS, attachments);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(RuntimeException e)
{
if(m_contentHostingService.ID_LENGTH_EXCEPTION.equals(e.getMessage()))
{
// couldn't we just truncate the resource-id instead of rejecting the upload?
addAlert(state, rb.getFormattedMessage("alert.toolong", new String[]{name}));
}
else
{
M_log.debug(this + ".doAttachupload ***** Runtime Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
}
catch(Exception ignore)
{
// other exceptions should be caught earlier
M_log.debug(this + ".doAttachupload ***** Unknown Exception ***** " + ignore.getMessage());
}
}
else
{
addAlert(state, rb.getString("choosefile7"));
}
}
}
} // doAttachupload
/**
* Simply take as much as possible out of 'in', and write it to 'out'. Don't
* close the streams, just transfer the data.
*
* @param in
* The data provider
* @param out
* The data output
* @throws IOException
* Thrown if there is an IOException transfering the data
*/
private void writeToStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[INPUT_BUFFER_SIZE];
try {
while (in.read(buffer) > 0) {
out.write(buffer);
}
} catch (IOException e) {
throw e;
}
}
/**
* remove recent added security advisor
*/
protected void disableSecurityAdvisor()
{
// remove recent added security advisor
SecurityService.popAdvisor();
}
/**
* Establish a security advisor to allow the "embedded" azg work to occur
* with no need for additional security permissions.
*/
protected void enableSecurityAdvisor()
{
// put in a security advisor so we can create citationAdmin site without need
// of further permissions
SecurityService.pushAdvisor(new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
return SecurityAdvice.ALLOWED;
}
});
}
/**
* Categories are represented as Integers. Right now this feature only will
* be active for new assignments, so we'll just always return 0 for the
* unassigned category. In the future we may (or not) want to update this
* to return categories for existing gradebook items.
* @param assignment
* @return
*/
private int getAssignmentCategoryAsInt(Assignment assignment) {
int categoryAsInt;
categoryAsInt = 0; // zero for unassigned
return categoryAsInt;
}
}
| assignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.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.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.assignment.tool;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.Collator;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import java.util.GregorianCalendar;
import java.nio.channels.*;
import java.nio.*;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.announcement.api.AnnouncementChannel;
import org.sakaiproject.announcement.api.AnnouncementMessage;
import org.sakaiproject.announcement.api.AnnouncementMessageEdit;
import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit;
import org.sakaiproject.announcement.api.AnnouncementService;
import org.sakaiproject.assignment.api.Assignment;
import org.sakaiproject.assignment.api.AssignmentConstants;
import org.sakaiproject.assignment.api.AssignmentContent;
import org.sakaiproject.assignment.api.AssignmentContentEdit;
import org.sakaiproject.assignment.api.AssignmentEdit;
import org.sakaiproject.assignment.api.AssignmentSubmission;
import org.sakaiproject.assignment.api.AssignmentSubmissionEdit;
import org.sakaiproject.assignment.api.model.AssignmentAllPurposeItemAccess;
import org.sakaiproject.assignment.api.model.AssignmentModelAnswerItem;
import org.sakaiproject.assignment.api.model.AssignmentNoteItem;
import org.sakaiproject.assignment.api.model.AssignmentAllPurposeItem;
import org.sakaiproject.assignment.api.model.AssignmentSupplementItemAttachment;
import org.sakaiproject.assignment.api.model.AssignmentSupplementItemService;
import org.sakaiproject.assignment.api.model.AssignmentSupplementItemWithAttachment;
import org.sakaiproject.assignment.cover.AssignmentService;
import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer;
import org.sakaiproject.taggable.api.TaggingHelperInfo;
import org.sakaiproject.taggable.api.TaggingManager;
import org.sakaiproject.taggable.api.TaggingProvider;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarEventEdit;
import org.sakaiproject.calendar.api.CalendarService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.ContentTypeImageService;
import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.content.api.ResourceTypeRegistry;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException;
import org.sakaiproject.service.gradebook.shared.CategoryDefinition;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService;
import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException;
import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException;
import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.RequestFilter;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SortedIterator;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.thread_local.cover.ThreadLocalManager;
import org.sakaiproject.contentreview.service.ContentReviewService;
/**
* <p>
* AssignmentAction is the action class for the assignment tool.
* </p>
*/
public class AssignmentAction extends PagedResourceActionII
{
private static ResourceLoader rb = new ResourceLoader("assignment");
/** Our logger. */
private static Log M_log = LogFactory.getLog(AssignmentAction.class);
private static final String ASSIGNMENT_TOOL_ID = "sakai.assignment.grades";
private static final Boolean allowReviewService = ServerConfigurationService.getBoolean("assignment.useContentReview", false);
/** Is the review service available? */
private static final String ALLOW_REVIEW_SERVICE = "allow_review_service";
private static final String NEW_ASSIGNMENT_USE_REVIEW_SERVICE = "new_assignment_use_review_service";
private static final String NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW = "new_assignment_allow_student_view";
/** The attachments */
private static final String ATTACHMENTS = "Assignment.attachments";
private static final String ATTACHMENTS_FOR = "Assignment.attachments_for";
/** The content type image lookup service in the State. */
private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service";
/** The calendar service in the State. */
private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service";
/** The announcement service in the State. */
private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service";
/** The calendar object */
private static final String CALENDAR = "calendar";
/** The calendar tool */
private static final String CALENDAR_TOOL_EXIST = "calendar_tool_exisit";
/** The announcement tool */
private static final String ANNOUNCEMENT_TOOL_EXIST = "announcement_tool_exist";
/** The announcement channel */
private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel";
/** The state mode */
private static final String STATE_MODE = "Assignment.mode";
/** The context string */
private static final String STATE_CONTEXT_STRING = "Assignment.context_string";
/** The user */
private static final String STATE_USER = "Assignment.user";
// SECTION MOD
/** Used to keep track of the section info not currently being used. */
private static final String STATE_SECTION_STRING = "Assignment.section_string";
/** **************************** sort assignment ********************** */
/** state sort * */
private static final String SORTED_BY = "Assignment.sorted_by";
/** state sort ascendingly * */
private static final String SORTED_ASC = "Assignment.sorted_asc";
/** default sorting */
private static final String SORTED_BY_DEFAULT = "default";
/** sort by assignment title */
private static final String SORTED_BY_TITLE = "title";
/** sort by assignment section */
private static final String SORTED_BY_SECTION = "section";
/** sort by assignment due date */
private static final String SORTED_BY_DUEDATE = "duedate";
/** sort by assignment open date */
private static final String SORTED_BY_OPENDATE = "opendate";
/** sort by assignment status */
private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status";
/** sort by assignment submission status */
private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status";
/** sort by assignment number of submissions */
private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions";
/** sort by assignment number of ungraded submissions */
private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded";
/** sort by assignment submission grade */
private static final String SORTED_BY_GRADE = "grade";
/** sort by assignment maximun grade available */
private static final String SORTED_BY_MAX_GRADE = "max_grade";
/** sort by assignment range */
private static final String SORTED_BY_FOR = "for";
/** sort by group title */
private static final String SORTED_BY_GROUP_TITLE = "group_title";
/** sort by group description */
private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description";
/** *************************** sort submission in instructor grade view *********************** */
/** state sort submission* */
private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by";
/** state sort submission ascendingly * */
private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc";
/** state sort submission by submitters last name * */
private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname";
/** state sort submission by submit time * */
private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time";
/** state sort submission by submission status * */
private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status";
/** state sort submission by submission grade * */
private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade";
/** state sort submission by submission released * */
private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released";
/** state sort submissuib by content review score **/
private static final String SORTED_GRADE_SUBMISSION_CONTENTREVIEW = "sorted_grade_submission_by_contentreview";
/** *************************** sort submission *********************** */
/** state sort submission* */
private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by";
/** state sort submission ascendingly * */
private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc";
/** state sort submission by submitters last name * */
private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname";
/** state sort submission by submit time * */
private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time";
/** state sort submission by submission grade * */
private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade";
/** state sort submission by submission status * */
private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status";
/** state sort submission by submission released * */
private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released";
/** state sort submission by assignment title */
private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment";
/** state sort submission by max grade */
private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade";
/*********************** Sort by user sort name *****************************************/
private static final String SORTED_USER_BY_SORTNAME = "sorted_user_by_sortname";
/** ******************** student's view assignment submission ****************************** */
/** the assignment object been viewing * */
private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference";
/** the submission text to the assignment * */
private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text";
/** the submission answer to Honor Pledge * */
private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes";
/** ***************** student's preview of submission *************************** */
/** the assignment id * */
private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference";
/** the submission text * */
private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text";
/** the submission honor pledge answer * */
private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes";
/** the submission attachments * */
private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments";
/** the flag indicate whether the to show the student view or not */
private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag";
/** the flag indicate whether the to show the assignment info or not */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag";
/** the assignment id */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id";
/** the assignment content id */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id";
/** ************** view assignment ***************************************** */
/** the hide assignment flag in the view assignment page * */
private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag";
/** the hide student view flag in the view assignment page * */
private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag";
/** ******************* instructor's view assignment ***************************** */
private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id";
/** ******************* instructor's edit assignment ***************************** */
private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id";
/** ******************* instructor's delete assignment ids ***************************** */
private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids";
/** ******************* flags controls the grade assignment page layout ******************* */
private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag";
private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag";
private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade";
/** ******************* instructor's grade submission ***************************** */
private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id";
private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id";
private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment";
private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text";
private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment";
private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade";
private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag";
private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit";
private static final String GRADE_SUBMISSION_DONE = "grade_submission_done";
/** ******************* instructor's export assignment ***************************** */
private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref";
/**
* Is review service enabled?
*/
private static final String ENABLE_REVIEW_SERVICE = "enable_review_service";
private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id";
/** ****************** instructor's new assignment ****************************** */
private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title";
// assignment order for default view
private static final String NEW_ASSIGNMENT_ORDER = "new_assignment_order";
// open date
private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth";
private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday";
private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear";
private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour";
private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin";
private static final String NEW_ASSIGNMENT_OPENAMPM = "new_assignment_openampm";
// due date
private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth";
private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday";
private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear";
private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour";
private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin";
private static final String NEW_ASSIGNMENT_DUEAMPM = "new_assignment_dueampm";
private static final String NEW_ASSIGNMENT_PAST_DUE_DATE = "new_assignment_past_due_date";
// close date
private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate";
private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth";
private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday";
private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear";
private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour";
private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin";
private static final String NEW_ASSIGNMENT_CLOSEAMPM = "new_assignment_closeampm";
private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment";
private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section";
private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type";
private static final String NEW_ASSIGNMENT_CATEGORY = "new_assignment_category";
private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type";
private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points";
private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions";
private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled";
private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced";
private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge";
private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus";
private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty";
private static final String NEW_ASSIGNMENT_ADD_TO_GRADEBOOK = "new_assignment_add_to_gradebook";
private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range";
private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups";
private static final String NEW_ASSIGNMENT_PAST_CLOSE_DATE = "new_assignment_past_close_date";
/*************************** assignment model answer attributes *************************/
private static final String NEW_ASSIGNMENT_MODEL_ANSWER = "new_assignment_model_answer";
private static final String NEW_ASSIGNMENT_MODEL_ANSWER_TEXT = "new_assignment_model_answer_text";
private static final String NEW_ASSIGNMENT_MODEL_SHOW_TO_STUDENT = "new_assignment_model_answer_show_to_student";
private static final String NEW_ASSIGNMENT_MODEL_ANSWER_ATTACHMENT = "new_assignment_model_answer_attachment";
/**************************** assignment year range *************************/
private static final String NEW_ASSIGNMENT_YEAR_RANGE_FROM = "new_assignment_year_range_from";
private static final String NEW_ASSIGNMENT_YEAR_RANGE_TO = "new_assignment_year_range_to";
// submission level of resubmit due time
private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth";
private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay";
private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear";
private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour";
private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin";
private static final String ALLOW_RESUBMIT_CLOSEAMPM = "allow_resubmit_closeAMPM";
private static final String ATTACHMENTS_MODIFIED = "attachments_modified";
/** **************************** instructor's view student submission ***************** */
// the show/hide table based on member id
private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE";
/** **************************** student view grade submission id *********** */
private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id";
// alert for grade exceeds max grade setting
private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert";
/** **************************** modes *************************** */
/** The list view of assignments */
private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template
/** The student view of an assignment submission */
private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission";
/** The student view of an assignment submission confirmation */
private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation";
/** The student preview of an assignment submission */
private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission";
/** The student view of graded submission */
private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade";
/** The student view of graded submission */
private static final String MODE_STUDENT_VIEW_GRADE_PRIVATE = "Assignment.mode_student_view_grade_private";
/** The student view of assignments */
private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment";
/** The instructor view of creating a new assignment or editing an existing one */
private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment";
/** The instructor view to reorder assignments */
private static final String MODE_INSTRUCTOR_REORDER_ASSIGNMENT = "reorder";
/** The instructor view to delete an assignment */
private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment";
/** The instructor view to grade an assignment */
private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment";
/** The instructor view to grade a submission */
private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission";
/** The instructor view of preview grading a submission */
private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission";
/** The instructor preview of one assignment */
private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments";
/** The instructor view of one assignment */
private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments";
/** The instructor view to list students of an assignment */
private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template
/** The instructor view of assignment submission report */
private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template
/** The instructor view of download all file */
private static final String MODE_INSTRUCTOR_DOWNLOAD_ALL = "downloadAll";
/** The instructor view of uploading all from archive file */
private static final String MODE_INSTRUCTOR_UPLOAD_ALL = "uploadAll";
/** The student view of assignment submission report */
private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template
/** ************************* vm names ************************** */
/** The list view of assignments */
private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments";
/** The student view of assignment */
private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment";
/** The student view of showing an assignment submission */
private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission";
/** The student view of an assignment submission confirmation */
private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation";
/** The student preview an assignment submission */
private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission";
/** The student view of graded submission */
private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade";
/** The instructor view to create a new assignment or edit an existing one */
private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment";
/** The instructor view to reorder the default assignments */
private static final String TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT = "_instructor_reorder_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission";
/** The instructor preview to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission";
/** The instructor view to grade the assignment */
private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions";
/** The instructor preview of assignment */
private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment";
/** The instructor view of assignment */
private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions";
/** The instructor view to assignment submission report */
private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions";
/** The instructor view to upload all information from archive file */
private static final String TEMPLATE_INSTRUCTOR_UPLOAD_ALL = "_instructor_uploadAll";
/** The opening mark comment */
private static final String COMMENT_OPEN = "{{";
/** The closing mark for comment */
private static final String COMMENT_CLOSE = "}}";
/** The selected view */
private static final String STATE_SELECTED_VIEW = "state_selected_view";
/** The configuration choice of with grading option or not */
private static final String WITH_GRADES = "with_grades";
/** The configuration choice of showing or hiding the number of submissions column */
private static final String SHOW_NUMBER_SUBMISSION_COLUMN = "showNumSubmissionColumn";
/** The alert flag when doing global navigation from improper mode */
private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation";
/** The total list item before paging */
private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items";
/** is current user allowed to grade assignment? */
private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission";
/** property for previous feedback attachments **/
private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments";
/** the user and submission list for list of submissions page */
private static final String USER_SUBMISSIONS = "user_submissions";
/** ************************* Taggable constants ************************** */
/** identifier of tagging provider that will provide the appropriate helper */
private static final String PROVIDER_ID = "providerId";
/** Reference to an activity */
private static final String ACTIVITY_REF = "activityRef";
/** Reference to an item */
private static final String ITEM_REF = "itemRef";
/** session attribute for list of decorated tagging providers */
private static final String PROVIDER_LIST = "providerList";
// whether the choice of emails instructor submission notification is available in the installation
private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications";
// default for whether or how the instructor receive submission notification emails, none(default)|each|digest
private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default";
// name for release grade notification
private static final String ASSIGNMENT_RELEASEGRADE_NOTIFICATION = "assignment.releasegrade.notification";
/****************************** Upload all screen ***************************/
private static final String UPLOAD_ALL_HAS_SUBMISSION_TEXT = "upload_all_has_submission_text";
private static final String UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT = "upload_all_has_submission_attachment";
private static final String UPLOAD_ALL_HAS_GRADEFILE = "upload_all_has_gradefile";
private static final String UPLOAD_ALL_HAS_COMMENTS= "upload_all_has_comments";
private static final String UPLOAD_ALL_HAS_FEEDBACK_TEXT= "upload_all_has_feedback_text";
private static final String UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT = "upload_all_has_feedback_attachment";
private static final String UPLOAD_ALL_RELEASE_GRADES = "upload_all_release_grades";
// this is to track whether the site has multiple assignment, hence if true, show the reorder link
private static final String HAS_MULTIPLE_ASSIGNMENTS = "has_multiple_assignments";
// view all or grouped submission list
private static final String VIEW_SUBMISSION_LIST_OPTION = "view_submission_list_option";
private ContentHostingService m_contentHostingService = null;
private EventTrackingService m_eventTrackingService = null;
private NotificationService m_notificationService = null;
/********************** Supplement item ************************/
private AssignmentSupplementItemService m_assignmentSupplementItemService = null;
/******** Model Answer ************/
private static final String MODELANSWER = "modelAnswer";
private static final String MODELANSWER_TEXT = "modelAnswer.text";
private static final String MODELANSWER_SHOWTO = "modelAnswer.showTo";
private static final String MODELANSWER_ATTACHMENTS = "modelanswer_attachments";
private static final String MODELANSWER_TO_DELETE = "modelanswer.toDelete";
/******** Note ***********/
private static final String NOTE = "note";
private static final String NOTE_TEXT = "note.text";
private static final String NOTE_SHAREWITH = "note.shareWith";
private static final String NOTE_TO_DELETE = "note.toDelete";
/******** AllPurpose *******/
private static final String ALLPURPOSE = "allPurpose";
private static final String ALLPURPOSE_TITLE = "allPurpose.title";
private static final String ALLPURPOSE_TEXT = "allPurpose.text";
private static final String ALLPURPOSE_HIDE = "allPurpose.hide";
private static final String ALLPURPOSE_SHOW_FROM = "allPurpose.show.from";
private static final String ALLPURPOSE_SHOW_TO = "allPurpose.show.to";
private static final String ALLPURPOSE_RELEASE_DATE = "allPurpose.releaseDate";
private static final String ALLPURPOSE_RETRACT_DATE= "allPurpose.retractDate";
private static final String ALLPURPOSE_ACCESS = "allPurpose.access";
private static final String ALLPURPOSE_ATTACHMENTS = "allPurpose_attachments";
private static final String ALLPURPOSE_RELEASE_YEAR = "allPurpose.releaseYear";
private static final String ALLPURPOSE_RELEASE_MONTH = "allPurpose.releaseMonth";
private static final String ALLPURPOSE_RELEASE_DAY = "allPurpose.releaseDay";
private static final String ALLPURPOSE_RELEASE_HOUR = "allPurpose.releaseHour";
private static final String ALLPURPOSE_RELEASE_MIN = "allPurpose.releaseMin";
private static final String ALLPURPOSE_RELEASE_AMPM = "allPurpose.releaseAMPM";
private static final String ALLPURPOSE_RETRACT_YEAR = "allPurpose.retractYear";
private static final String ALLPURPOSE_RETRACT_MONTH = "allPurpose.retractMonth";
private static final String ALLPURPOSE_RETRACT_DAY = "allPurpose.retractDay";
private static final String ALLPURPOSE_RETRACT_HOUR = "allPurpose.retractHour";
private static final String ALLPURPOSE_RETRACT_MIN = "allPurpose.retractMin";
private static final String ALLPURPOSE_RETRACT_AMPM = "allPurpose.retractAMPM";
private static final String ALLPURPOSE_TO_DELETE = "allPurpose.toDelete";
private static final String SHOW_ALLOW_RESUBMISSION = "show_allow_resubmission";
private static final int INPUT_BUFFER_SIZE = 102400;
/**
* central place for dispatching the build routines based on the state name
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
String template = null;
context.put("tlang", rb);
context.put("dateFormat", getDateFormatString());
context.put("cheffeedbackhelper", this);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// allow add assignment?
boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString);
context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment));
Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION);
// allow update site?
context.put("allowUpdateSite", Boolean
.valueOf(SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))));
// allow all.groups?
boolean allowAllGroups = AssignmentService.allowAllGroups(contextString);
context.put("allowAllGroups", Boolean.valueOf(allowAllGroups));
//Is the review service allowed?
Site s = null;
try {
s = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (IdUnusedException iue) {
M_log.warn(this + ":buildMainPanelContext: Site not found!" + iue.getMessage());
}
// Check whether content review service is enabled, present and enabled for this site
getContentReviewService();
context.put("allowReviewService", allowReviewService && contentReviewService != null && contentReviewService.isSiteAcceptable(s));
if (allowReviewService && contentReviewService != null && contentReviewService.isSiteAcceptable(s)) {
//put the review service stings in context
String reviewServiceName = contentReviewService.getServiceName();
String reviewServiceTitle = rb.getFormattedMessage("review.title", new Object[]{reviewServiceName});
String reviewServiceUse = rb.getFormattedMessage("review.use", new Object[]{reviewServiceName});
context.put("reviewServiceName", reviewServiceTitle);
context.put("reviewServiceUse", reviewServiceUse);
}
// grading option
context.put("withGrade", state.getAttribute(WITH_GRADES));
// the grade type table
context.put("gradeTypeTable", gradeTypeTable());
String mode = (String) state.getAttribute(STATE_MODE);
if (!MODE_LIST_ASSIGNMENTS.equals(mode))
{
// allow grade assignment?
if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null)
{
state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE);
}
context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION));
}
if (MODE_LIST_ASSIGNMENTS.equals(mode))
{
// build the context for the student assignment view
template = build_list_assignments_context(portlet, context, data, state);
}
else if (MODE_STUDENT_VIEW_ASSIGNMENT.equals(mode))
{
// the student view of assignment
template = build_student_view_assignment_context(portlet, context, data, state);
}
else if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for showing one assignment submission
template = build_student_view_submission_context(portlet, context, data, state);
}
else if (MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION.equals(mode))
{
// build the context for showing one assignment submission confirmation
template = build_student_view_submission_confirmation_context(portlet, context, data, state);
}
else if (MODE_STUDENT_PREVIEW_SUBMISSION.equals(mode))
{
// build the context for showing one assignment submission
template = build_student_preview_submission_context(portlet, context, data, state);
}
else if (MODE_STUDENT_VIEW_GRADE.equals(mode) || MODE_STUDENT_VIEW_GRADE_PRIVATE.equals(mode))
{
// disable auto-updates while leaving the list view
justDelivered(state);
if(MODE_STUDENT_VIEW_GRADE_PRIVATE.equals(mode)){
context.put("privateView", true);
}
// build the context for showing one graded submission
template = build_student_view_grade_context(portlet, context, data, state);
}
else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode))
{
// allow add assignment?
boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString);
context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment));
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's create new assignment view
template = build_instructor_new_edit_assignment_context(portlet, context, data, state);
}
else if (MODE_INSTRUCTOR_DELETE_ASSIGNMENT.equals(mode))
{
if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null)
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's delete assignment
template = build_instructor_delete_assignment_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode))
{
if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's grade assignment
template = build_instructor_grade_assignment_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode))
{
if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's grade submission
template = build_instructor_grade_submission_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's preview grade submission
template = build_instructor_preview_grade_submission_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode))
{
// build the context for preview one assignment
template = build_instructor_preview_assignment_context(portlet, context, data, state);
}
else if (MODE_INSTRUCTOR_VIEW_ASSIGNMENT.equals(mode))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for view one assignment
template = build_instructor_view_assignment_context(portlet, context, data, state);
}
else if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's create new assignment view
template = build_instructor_view_students_assignment_context(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of report submissions
template = build_instructor_report_submissions(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_DOWNLOAD_ALL.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of uploading all info from archive file
template = build_instructor_download_upload_all(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_UPLOAD_ALL.equals(mode))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of uploading all info from archive file
template = build_instructor_download_upload_all(portlet, context, data, state);
}
}
else if (MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's create new assignment view
template = build_instructor_reorder_assignment_context(portlet, context, data, state);
}
if (template == null)
{
// default to student list view
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
template = build_list_assignments_context(portlet, context, data, state);
}
// this is a check for seeing if there are any assignments. The check is used to see if we display a Reorder link in the vm files
if (state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS) != null)
{
context.put("assignmentscheck", state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS));
}
return template;
} // buildNormalContext
/**
* local function for getting assignment object
* @param assignmentId
* @param callingFunctionName
* @param state
* @return
*/
private Assignment getAssignment(String assignmentId, String callingFunctionName, SessionState state)
{
Assignment rv = null;
try
{
rv = AssignmentService.getAssignment(assignmentId);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentId}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("youarenot_viewAssignment", new Object[]{assignmentId}));
}
return rv;
}
/**
* local function for getting assignment submission object
* @param submissionId
* @param callingFunctionName
* @param state
* @return
*/
private AssignmentSubmission getSubmission(String submissionId, String callingFunctionName, SessionState state)
{
AssignmentSubmission rv = null;
try
{
rv = AssignmentService.getSubmission(submissionId);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("cannotfin_submission", new Object[]{submissionId}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission", new Object[]{submissionId}));
}
return rv;
}
/**
* local function for editing assignment submission object
* @param submissionId
* @param callingFunctionName
* @param state
* @return
*/
private AssignmentSubmissionEdit editSubmission(String submissionId, String callingFunctionName, SessionState state)
{
AssignmentSubmissionEdit rv = null;
try
{
rv = AssignmentService.editSubmission(submissionId);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("cannotfin_submission", new Object[]{submissionId}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("youarenot_editSubmission", new Object[]{submissionId}));
}
catch (InUseException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId);
addAlert(state, rb.getFormattedMessage("somelsis_submission", new Object[]{submissionId}));
}
return rv;
}
/**
* local function for editing assignment object
* @param assignmentId
* @param callingFunctionName
* @param state
* @param allowToAdd
* @return
*/
private AssignmentEdit editAssignment(String assignmentId, String callingFunctionName, SessionState state, boolean allowAdd)
{
AssignmentEdit rv = null;
if (assignmentId.length() == 0 && allowAdd)
{
// create a new assignment
try
{
rv = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot_addAssignment"));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage());
}
}
else
{
try
{
rv = AssignmentService.editAssignment(assignmentId);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentId}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("youarenot_editAssignment", new Object[]{assignmentId}));
}
catch (InUseException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId);
addAlert(state, rb.getFormattedMessage("somelsis_assignment", new Object[]{assignmentId}));
}
} // if-else
return rv;
}
/**
* local function for getting assignment submission object
* @param submissionId
* @param callingFunctionName
* @param state
* @return
*/
private AssignmentSubmission getSubmission(String assignmentRef, User user, String callingFunctionName, SessionState state)
{
AssignmentSubmission rv = null;
try
{
rv = AssignmentService.getSubmission(assignmentRef, user);
}
catch (IdUnusedException e)
{
M_log.warn(this + ":build_student_view_submission " + e.getMessage() + " " + assignmentRef + " " + user.getId());
if (state != null)
addAlert(state, rb.getFormattedMessage("cannotfin_submission_1", new Object[]{assignmentRef, user.getId()}));
}
catch (PermissionException e)
{
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentRef + " " + user.getId());
if (state != null)
addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission_1", new Object[]{assignmentRef, user.getId()}));
}
return rv;
}
/**
* build the student view of showing an assignment submission
*/
protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("context", contextString);
User user = (User) state.getAttribute(STATE_USER);
String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
AssignmentSubmission s = null;
Assignment assignment = getAssignment(currentAssignmentReference, "build_student_view_submission_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit(contextString, assignment)));
if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
context.put("nonElectronicType", Boolean.TRUE);
}
s = getSubmission(assignment.getReference(), user, "build_student_view_submission_context", state);
if (s != null)
{
context.put("submission", s);
ResourceProperties p = s.getProperties();
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null)
{
context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT));
}
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null)
{
context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT));
}
if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null)
{
context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p));
}
// put the resubmit information into context
assignment_resubmission_option_into_context(context, state);
}
// can the student view model answer or not
canViewAssignmentIntoContext(context, assignment, s);
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
// name value pairs for the vm
context.put("name_submission_text", VIEW_SUBMISSION_TEXT);
context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT));
context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES);
context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES));
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("currentTime", TimeService.newTime());
boolean allowSubmit = AssignmentService.allowAddSubmission((String) state.getAttribute(STATE_CONTEXT_STRING));
if (!allowSubmit)
{
addAlert(state, rb.getString("not_allowed_to_submit"));
}
context.put("allowSubmit", Boolean.valueOf(allowSubmit));
// put supplement item into context
supplementItemIntoContext(state, context, assignment, s);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_SUBMISSION;
} // build_student_view_submission_context
/**
* build the student view of showing an assignment submission confirmation
*/
protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("context", contextString);
// get user information
User user = (User) state.getAttribute(STATE_USER);
context.put("user_name", user.getDisplayName());
context.put("user_id", user.getDisplayId());
if (StringUtil.trimToNull(user.getEmail()) != null)
context.put("user_email", user.getEmail());
// get site information
try
{
// get current site
Site site = SiteService.getSite(contextString);
context.put("site_title", site.getTitle());
}
catch (Exception ignore)
{
M_log.warn(this + ":buildStudentViewSubmission " + ignore.getMessage() + " siteId= " + contextString);
}
// get assignment and submission information
String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment currentAssignment = getAssignment(currentAssignmentReference, "build_student_view_submission_confirmation_context", state);
if (currentAssignment != null)
{
context.put("assignment_title", currentAssignment.getTitle());
// differenciate submission type
int submissionType = currentAssignment.getContent().getTypeOfSubmission();
if (submissionType == Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION || submissionType == Assignment.SINGLE_ATTACHMENT_SUBMISSION)
{
context.put("attachmentSubmissionOnly", Boolean.TRUE);
}
else
{
context.put("attachmentSubmissionOnly", Boolean.FALSE);
}
if (submissionType == Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION)
{
context.put("textSubmissionOnly", Boolean.TRUE);
}
else
{
context.put("textSubmissionOnly", Boolean.FALSE);
}
AssignmentSubmission s = getSubmission(currentAssignmentReference, user, "build_student_view_submission_confirmation_context",state);
if (s != null)
{
context.put("submitted", Boolean.valueOf(s.getSubmitted()));
context.put("submission_id", s.getId());
if (s.getTimeSubmitted() != null)
{
context.put("submit_time", s.getTimeSubmitted().toStringLocalFull());
}
List attachments = s.getSubmittedAttachments();
if (attachments != null && attachments.size()>0)
{
context.put("submit_attachments", s.getSubmittedAttachments());
}
context.put("submit_text", StringUtil.trimToNull(s.getSubmittedText()));
context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true)));
}
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION;
} // build_student_view_submission_confirmation_context
/**
* build the student view of assignment
*/
protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("context", state.getAttribute(STATE_CONTEXT_STRING));
String aReference = (String) state.getAttribute(VIEW_ASSIGNMENT_ID);
User user = (User) state.getAttribute(STATE_USER);
AssignmentSubmission submission = null;
Assignment assignment = getAssignment(aReference, "build_student_view_assignment_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
// put creator information into context
putCreatorIntoContext(context, assignment);
submission = getSubmission(aReference, user, "build_student_view_assignment_context", state);
context.put("submission", submission);
// can the student view model answer or not
canViewAssignmentIntoContext(context, assignment, submission);
// put resubmit information into context
assignment_resubmission_option_into_context(context, state);
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("userDirectoryService", UserDirectoryService.getInstance());
// put supplement item into context
supplementItemIntoContext(state, context, assignment, submission);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT;
} // build_student_view_submission_context
/**
* build the student preview of showing an assignment submission
*/
protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
User user = (User) state.getAttribute(STATE_USER);
String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment assignment = getAssignment(aReference, "build_student_preview_submission_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
AssignmentSubmission submission = getSubmission(aReference, user, "build_student_preview_submission_context", state);
context.put("submission", submission);
context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit((String) state.getAttribute(STATE_CONTEXT_STRING), assignment)));
// can the student view model answer or not
canViewAssignmentIntoContext(context, assignment, submission);
// put the resubmit information into context
assignment_resubmission_option_into_context(context, state);
}
context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT));
context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES));
context.put("attachments", state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION;
} // build_student_preview_submission_context
private void canViewAssignmentIntoContext(Context context,
Assignment assignment, AssignmentSubmission submission) {
boolean canViewModelAnswer = m_assignmentSupplementItemService.canViewModelAnswer(assignment, submission);
context.put("allowViewModelAnswer", Boolean.valueOf(canViewModelAnswer));
if (canViewModelAnswer)
{
context.put("modelAnswer", m_assignmentSupplementItemService.getModelAnswer(assignment.getId()));
}
}
/**
* build the student view of showing a graded submission
*/
protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
Session session = SessionManager.getCurrentSession();
SecurityAdvisor contentAdvisor = (SecurityAdvisor)session.getAttribute("assignment.content.security.advisor");
String decoratedContentWrapper = (String)session.getAttribute("assignment.content.decoration.wrapper");
session.removeAttribute("assignment.content.decoration.wrapper");
String[] contentRefs = (String[])session.getAttribute("assignment.content.decoration.wrapper.refs");
session.removeAttribute("assignment.content.decoration.wrapper.refs");
if (contentAdvisor != null && contentRefs != null) {
SecurityService.pushAdvisor(contentAdvisor);
Map urlMap = new HashMap();
for (String refStr:contentRefs) {
Reference ref = EntityManager.newReference(refStr);
String url = ref.getUrl();
urlMap.put(url, url.replaceFirst("access/content", "access/" + decoratedContentWrapper + "/content"));
}
context.put("decoratedUrlMap", urlMap);
}
SecurityAdvisor asgnAdvisor = (SecurityAdvisor)session.getAttribute("assignment.security.advisor");
if (asgnAdvisor != null) {
SecurityService.pushAdvisor(asgnAdvisor);
session.removeAttribute("assignment.security.advisor");
}
AssignmentSubmission submission = null;
Assignment assignment = null;
String submissionId = (String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID);
submission = getSubmission(submissionId, "build_student_view_grade_context", state);
if (submission != null)
{
assignment = submission.getAssignment();
context.put("assignment", assignment);
if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
context.put("nonElectronicType", Boolean.TRUE);
}
context.put("submission", submission);
// can the student view model answer or not
canViewAssignmentIntoContext(context, assignment, submission);
SecurityService.popAdvisor();
//should be the asgnAdvisor that gets popped
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && submission != null)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
List<DecoratedTaggingProvider> providers = addProviders(context, state);
List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>();
for (DecoratedTaggingProvider provider : providers)
{
TaggingHelperInfo helper = provider.getProvider()
.getItemHelperInfo(
assignmentActivityProducer.getItem(
submission,
UserDirectoryService.getCurrentUser()
.getId()).getReference());
if (helper != null)
{
itemHelpers.add(helper);
}
}
addItem(context, submission, UserDirectoryService.getCurrentUser().getId());
addActivity(context, submission.getAssignment());
context.put("itemHelpers", itemHelpers);
context.put("taggable", Boolean.valueOf(true));
}
// put supplement item into context
supplementItemIntoContext(state, context, assignment, submission);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_GRADE;
} // build_student_view_grade_context
/**
* build the view of assignments list
*/
protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable())
{
context.put("producer", ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"));
context.put("providers", taggingManager.getProviders());
context.put("taggable", Boolean.valueOf(true));
}
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("contextString", contextString);
context.put("user", state.getAttribute(STATE_USER));
context.put("service", AssignmentService.getInstance());
context.put("TimeService", TimeService.getInstance());
context.put("LongObject", Long.valueOf(TimeService.newTime().getTime()));
context.put("currentTime", TimeService.newTime());
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
// clean sort criteria
if (SORTED_BY_GROUP_TITLE.equals(sortedBy) || SORTED_BY_GROUP_DESCRIPTION.equals(sortedBy))
{
sortedBy = SORTED_BY_DUEDATE;
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sortedBy);
state.setAttribute(SORTED_ASC, sortedAsc);
}
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
if (state.getAttribute(STATE_SELECTED_VIEW) != null)
{
context.put("view", state.getAttribute(STATE_SELECTED_VIEW));
}
List assignments = prepPage(state);
context.put("assignments", assignments.iterator());
// allow get assignment
context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString)));
// test whether user user can grade at least one assignment
// and update the state variable.
boolean allowGradeSubmission = false;
for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); )
{
if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference()))
{
allowGradeSubmission = true;
}
}
state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.valueOf(allowGradeSubmission));
context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION));
// allow remove assignment?
boolean allowRemoveAssignment = false;
for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); )
{
if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference()))
{
allowRemoveAssignment = true;
}
}
context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment));
add2ndToolbarFields(data, context);
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
justDelivered(state);
pagingInfoToContext(state, context);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite(contextString);
context.put("site", site);
// any group in the site?
Collection groups = site.getGroups();
context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE);
// add active user list
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString));
if (realm != null)
{
context.put("activeUserIds", realm.getUsers());
}
}
catch (Exception ignore)
{
M_log.warn(this + ":build_list_assignments_context " + ignore.getMessage());
M_log.warn(this + ignore.getMessage() + " siteId= " + contextString);
}
boolean allowSubmit = AssignmentService.allowAddSubmission(contextString);
context.put("allowSubmit", Boolean.valueOf(allowSubmit));
// related to resubmit settings
context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
// the type int for non-electronic submission
context.put("typeNonElectronic", Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION));
// show or hide the number of submission column
context.put(SHOW_NUMBER_SUBMISSION_COLUMN, state.getAttribute(SHOW_NUMBER_SUBMISSION_COLUMN));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_LIST_ASSIGNMENTS;
} // build_list_assignments_context
private HashSet<String> getSubmittersIdSet(List submissions)
{
HashSet<String> rv = new HashSet<String>();
for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext();)
{
List submitterIds = ((AssignmentSubmission) iSubmissions.next()).getSubmitterIds();
if (submitterIds != null && submitterIds.size() > 0)
{
rv.add((String) submitterIds.get(0));
}
}
return rv;
}
private HashSet<String> getAllowAddSubmissionUsersIdSet(List users)
{
HashSet<String> rv = new HashSet<String>();
for (Iterator iUsers=users.iterator(); iUsers.hasNext();)
{
rv.add(((User) iUsers.next()).getId());
}
return rv;
}
/**
* build the instructor view of creating a new assignment or editing an existing one
*/
protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
// is the assignment an new assignment
String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID);
if (assignmentId != null)
{
Assignment a = getAssignment(assignmentId, "build_instructor_new_edit_assignment_context", state);
if (a != null)
{
context.put("assignment", a);
}
}
// set up context variables
setAssignmentFormContext(state, context);
context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS));
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT;
} // build_instructor_new_assignment_context
protected void setAssignmentFormContext(SessionState state, Context context)
{
// put the names and values into vm file
context.put("name_UseReviewService", NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
context.put("name_AllowStudentView", NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW);
context.put("name_title", NEW_ASSIGNMENT_TITLE);
context.put("name_order", NEW_ASSIGNMENT_ORDER);
// set open time context variables
putTimePropertiesInContext(context, state, "Open", NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM);
// set due time context variables
putTimePropertiesInContext(context, state, "Due", NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM);
context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE);
// set close time context variables
putTimePropertiesInContext(context, state, "Close", NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM);
context.put("name_Section", NEW_ASSIGNMENT_SECTION);
context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE);
context.put("name_Category", NEW_ASSIGNMENT_CATEGORY);
context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE);
context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS);
context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION);
// do not show the choice when there is no Schedule tool yet
if (state.getAttribute(CALENDAR) != null)
context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
//don't show the choice when there is no Announcement tool yet
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null)
context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
// set the values
Assignment a = null;
String assignmentRef = (String) state.getAttribute(EDIT_ASSIGNMENT_ID);
if (assignmentRef != null)
{
a = getAssignment(assignmentRef, "setAssignmentFormContext", state);
}
// put the re-submission info into context
putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE));
context.put("value_position_order", state.getAttribute(NEW_ASSIGNMENT_ORDER));
context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE));
context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION));
context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE));
// information related to gradebook categories
putGradebookCategoryInfoIntoContext(state, context);
context.put("value_totalSubmissionTypes", Assignment.SUBMISSION_TYPES.length);
context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE));
// format to show one decimal place
String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
context.put("value_GradePoints", displayGrade(state, maxGrade));
context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION));
// Keep the use review service setting
context.put("value_UseReviewService", state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE));
context.put("value_AllowStudentView", state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW));
// don't show the choice when there is no Schedule tool yet
if (state.getAttribute(CALENDAR) != null)
context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
// don't show the choice when there is no Announcement tool yet
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null)
context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
if (s == null) s = "1";
context.put("value_CheckAddHonorPledge", s);
// put resubmission option into context
assignment_resubmission_option_into_context(context, state);
// get all available assignments from Gradebook tool except for those created fromcategoryTable
boolean gradebookExists = isGradebookDefined();
if (gradebookExists)
{
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
try
{
// get all assignments in Gradebook
List gradebookAssignments = g.getAssignments(gradebookUid);
List gradebookAssignmentsExceptSamigo = new Vector();
// filtering out those from Samigo
for (Iterator i=gradebookAssignments.iterator(); i.hasNext();)
{
org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next();
if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle()))
{
gradebookAssignmentsExceptSamigo.add(gAssignment);
}
}
context.put("gradebookAssignments", gradebookAssignmentsExceptSamigo);
if (StringUtil.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null)
{
state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
}
context.put("withGradebook", Boolean.TRUE);
// offer the gradebook integration choice only in the Assignments with Grading tool
boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue();
if (withGrade)
{
context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
}
context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO);
context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD);
context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE);
String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (associateGradebookAssignment != null)
{
context.put("associateGradebookAssignment", associateGradebookAssignment);
if (a != null)
{
context.put("noAddToGradebookChoice", Boolean.valueOf(associateGradebookAssignment.equals(a.getReference())));
}
}
}
catch (Exception e)
{
// not able to link to Gradebook
M_log.warn(this + "setAssignmentFormContext " + e.getMessage());
}
if (StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null)
{
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
}
}
context.put("monthTable", monthTable());
context.put("submissionTypeTable", submissionTypeTable());
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String range = StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_RANGE));
context.put("range", range != null?range:"site");
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
context.put("site", site);
}
catch (Exception ignore)
{
M_log.warn(this + ":setAssignmentFormContext " + ignore.getMessage());
}
if (AssignmentService.getAllowGroupAssignments())
{
Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString);
if (range == null)
{
if (AssignmentService.allowAddSiteAssignment(contextString))
{
// default to make site selection
context.put("range", "site");
}
else if (groupsAllowAddAssignment.size() > 0)
{
// to group otherwise
context.put("range", "groups");
}
}
// group list which user can add message to
if (groupsAllowAddAssignment.size() > 0)
{
String sort = (String) state.getAttribute(SORTED_BY);
String asc = (String) state.getAttribute(SORTED_ASC);
if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION)))
{
sort = SORTED_BY_GROUP_TITLE;
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sort);
state.setAttribute(SORTED_ASC, asc);
}
context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), new AssignmentComparator(state, sort, asc)));
context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS));
}
}
context.put("allowGroupAssignmentsInGradebook", Boolean.valueOf(AssignmentService.getAllowGroupAssignmentsInGradebook()));
// the notification email choices
// whether the choice of emails instructor submission notification is available in the installation
// system installation allowed assignment submission notification
boolean allowNotification = ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true);
if (allowNotification)
{
// whether current user can receive notification. If not, don't show the notification choices in the create/edit assignment page
allowNotification = AssignmentService.allowReceiveSubmissionNotification(contextString);
}
if (allowNotification)
{
context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS);
if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null)
{
// set the notification value using site default
// whether or how the instructor receive submission notification emails, none(default)|each|digest
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE));
}
context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
// the option values
context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE);
context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH);
context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST);
}
// release grade notification option
putReleaseGradeNotificationOptionIntoContext(state, context);
// the supplement information
// model answers
context.put("modelanswer", state.getAttribute(MODELANSWER) != null?Boolean.TRUE:Boolean.FALSE);
context.put("modelanswer_text", state.getAttribute(MODELANSWER_TEXT));
context.put("modelanswer_showto", state.getAttribute(MODELANSWER_SHOWTO));
// get attachment for model answer object
putSupplementItemAttachmentStateIntoContext(state, context, MODELANSWER_ATTACHMENTS);
// private notes
context.put("allowReadAssignmentNoteItem", m_assignmentSupplementItemService.canReadNoteItem(a, contextString));
context.put("allowEditAssignmentNoteItem", m_assignmentSupplementItemService.canEditNoteItem(a));
context.put("note", state.getAttribute(NOTE) != null?Boolean.TRUE:Boolean.FALSE);
context.put("note_text", state.getAttribute(NOTE_TEXT));
context.put("note_to", state.getAttribute(NOTE_SHAREWITH) != null?state.getAttribute(NOTE_SHAREWITH):String.valueOf(0));
// all purpose item
context.put("allPurpose", state.getAttribute(ALLPURPOSE) != null?Boolean.TRUE:Boolean.FALSE);
context.put("value_allPurposeTitle", state.getAttribute(ALLPURPOSE_TITLE));
context.put("value_allPurposeText", state.getAttribute(ALLPURPOSE_TEXT));
context.put("value_allPurposeHide", state.getAttribute(ALLPURPOSE_HIDE) != null?state.getAttribute(ALLPURPOSE_HIDE):Boolean.FALSE);
context.put("value_allPurposeShowFrom", state.getAttribute(ALLPURPOSE_SHOW_FROM) != null?state.getAttribute(ALLPURPOSE_SHOW_FROM):Boolean.FALSE);
context.put("value_allPurposeShowTo", state.getAttribute(ALLPURPOSE_SHOW_TO) != null?state.getAttribute(ALLPURPOSE_SHOW_TO):Boolean.FALSE);
context.put("value_allPurposeAccessList", state.getAttribute(ALLPURPOSE_ACCESS));
putTimePropertiesInContext(context, state, "allPurposeRelease", ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, ALLPURPOSE_RELEASE_AMPM);
putTimePropertiesInContext(context, state, "allPurposeRetract", ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, ALLPURPOSE_RETRACT_AMPM);
// get attachment for all purpose object
putSupplementItemAttachmentStateIntoContext(state, context, ALLPURPOSE_ATTACHMENTS);
// put role information into context
Hashtable<String, List> roleUsers = new Hashtable<String, List>();
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString));
Set<Role> roles = realm.getRoles();
for(Iterator iRoles = roles.iterator(); iRoles.hasNext();)
{
Role r = (Role) iRoles.next();
Set<String> users = realm.getUsersHasRole(r.getId());
if (users!=null && users.size() > 0)
{
List<User> usersList = new Vector();
for (Iterator<String> iUsers = users.iterator(); iUsers.hasNext();)
{
String userId = iUsers.next();
try
{
User u = UserDirectoryService.getUser(userId);
usersList.add(u);
}
catch (Exception e)
{
M_log.warn(this + ":setAssignmentFormContext cannot get user " + e.getMessage() + " user id=" + userId);
}
}
roleUsers.put(r.getId(), usersList);
}
}
context.put("roleUsers", roleUsers);
}
catch (Exception e)
{
M_log.warn(this + ":setAssignmentFormContext role cast problem " + e.getMessage() + " site =" + contextString);
}
} // setAssignmentFormContext
private void putGradebookCategoryInfoIntoContext(SessionState state,
Context context) {
Hashtable<Long, String> categoryTable = categoryTable();
if (categoryTable != null)
{
context.put("value_totalCategories", Integer.valueOf(categoryTable.size()));
// selected category
context.put("value_Category", state.getAttribute(NEW_ASSIGNMENT_CATEGORY));
Enumeration<Long> categories = categoryTable.keys();
List<Long> categoryList = new Vector<Long>();
while(categories.hasMoreElements())
{
categoryList.add(categories.nextElement());
}
Collections.sort(categoryList);
context.put("categoryKeys", categoryList);
context.put("categoryTable", categoryTable());
}
else
{
context.put("value_totalCategories", Integer.valueOf(0));
}
}
/**
* put the release grade notification options into context
* @param state
* @param context
*/
private void putReleaseGradeNotificationOptionIntoContext(SessionState state, Context context) {
if (state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) == null)
{
// set the notification value using site default to be none: no email will be sent to student when the grade is released
state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_NONE);
}
// input fields
context.put("name_assignment_releasegrade_notification", ASSIGNMENT_RELEASEGRADE_NOTIFICATION);
context.put("value_assignment_releasegrade_notification", state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE));
// the option values
context.put("value_assignment_releasegrade_notification_none", Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_NONE);
context.put("value_assignment_releasegrade_notification_each", Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_EACH);
}
/**
* build the instructor view of create a new assignment
*/
protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("time", TimeService.newTime());
context.put("user", UserDirectoryService.getCurrentUser());
context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE));
context.put("name_order", NEW_ASSIGNMENT_ORDER);
context.put("value_position_order", (String) state.getAttribute(NEW_ASSIGNMENT_ORDER));
Time openTime = getTimeFromState(state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM);
context.put("value_OpenDate", openTime);
// due time
Time dueTime = getTimeFromState(state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM);
context.put("value_DueDate", dueTime);
// close time
Time closeTime = TimeService.newTime();
Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE);
context.put("value_EnableCloseDate", enableCloseDate);
if ((enableCloseDate).booleanValue())
{
closeTime = getTimeFromState(state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM);
context.put("value_CloseDate", closeTime);
}
context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION));
context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE));
context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE));
String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
context.put("value_GradePoints", displayGrade(state, maxGrade));
context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION));
context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE));
// get all available assignments from Gradebook tool except for those created from
if (isGradebookDefined())
{
context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
// information related to gradebook categories
putGradebookCategoryInfoIntoContext(state, context);
}
context.put("monthTable", monthTable());
context.put("submissionTypeTable", submissionTypeTable());
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG));
context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG));
String assignmentId = StringUtil.trimToNull((String) state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID));
if (assignmentId != null)
{
// editing existing assignment
context.put("value_assignment_id", assignmentId);
Assignment a = getAssignment(assignmentId, "build_instructor_preview_assignment_context", state);
if (a != null)
{
context.put("isDraft", Boolean.valueOf(a.getDraft()));
}
}
else
{
// new assignment
context.put("isDraft", Boolean.TRUE);
}
context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID));
context.put("currentTime", TimeService.newTime());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT;
} // build_instructor_preview_assignment_context
/**
* build the instructor view to delete an assignment
*/
protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
Vector assignments = new Vector();
Vector assignmentIds = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
Hashtable<String, Integer> submissionCountTable = new Hashtable<String, Integer>();
for (int i = 0; i < assignmentIds.size(); i++)
{
String assignmentId = (String) assignmentIds.get(i);
Assignment a = getAssignment(assignmentId, "build_instructor_delete_assignment_context", state);
if (a != null)
{
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
int submittedCount = 0;
while (submissions.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getSubmitted() && s.getTimeSubmitted() != null)
{
submittedCount++;
}
}
if (submittedCount > 0)
{
// if there is submission to the assignment, show the alert
addAlert(state, rb.getFormattedMessage("areyousur_withSubmission", new Object[]{a.getTitle()}));
}
assignments.add(a);
submissionCountTable.put(a.getReference(), Integer.valueOf(submittedCount));
}
}
context.put("assignments", assignments);
context.put("confirmMessage", assignments.size() > 1 ? rb.getString("areyousur_multiple"):rb.getString("areyousur_single"));
context.put("currentTime", TimeService.newTime());
context.put("submissionCountTable", submissionCountTable);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT;
} // build_instructor_delete_assignment_context
/**
* build the instructor view to grade an submission
*/
protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String submissionId="";
int gradeType = -1;
// need to show the alert for grading drafts?
boolean addGradeDraftAlert = false;
// assignment
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
Assignment a = getAssignment(assignmentId, "build_instructor_grade_submission_context", state);
if (a != null)
{
context.put("assignment", a);
if (a.getContent() != null)
{
gradeType = a.getContent().getTypeOfGrade();
}
boolean allowToGrade=true;
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if (associateGradebookAssignment != null)
{
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
if (g != null && g.isGradebookDefined(gradebookUid))
{
if (!g.currentUserHasGradingPerm(gradebookUid))
{
context.put("notAllowedToGradeWarning", rb.getString("not_allowed_to_grade_in_gradebook"));
allowToGrade=false;
}
}
}
context.put("allowToGrade", Boolean.valueOf(allowToGrade));
}
// assignment submission
AssignmentSubmission s = getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_instructor_grade_submission_context", state);
if (s != null)
{
submissionId = s.getId();
context.put("submission", s);
// show alert if student is working on a draft
if (!s.getSubmitted() // not submitted
&& ((s.getSubmittedText() != null && s.getSubmittedText().length()> 0) // has some text
|| (s.getSubmittedAttachments() != null && s.getSubmittedAttachments().size() > 0))) // has some attachment
{
if (s.getCloseTime().after(TimeService.newTime()))
{
// not pass the close date yet
addGradeDraftAlert = true;
}
else
{
// passed the close date already
addGradeDraftAlert = false;
}
}
ResourceProperties p = s.getProperties();
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null)
{
context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT));
}
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null)
{
context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT));
}
if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null)
{
context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p));
}
// put the re-submission info into context
putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
assignment_resubmission_option_into_context(context, state);
}
context.put("user", state.getAttribute(STATE_USER));
context.put("submissionTypeTable", submissionTypeTable());
context.put("instructorAttachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
// names
context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID);
context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT);
context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT);
context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
context.put("name_grade", GRADE_SUBMISSION_GRADE);
context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// values
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT));
context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS));
// format to show one decimal place in grade
context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE))
: state.getAttribute(GRADE_SUBMISSION_GRADE));
context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG));
// is this a non-electronic submission type of assignment
context.put("nonElectronic", (a!=null && a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)?Boolean.TRUE:Boolean.FALSE);
if (addGradeDraftAlert)
{
addAlert(state, rb.getString("grading.alert.draft.beforeclosedate"));
}
context.put("alertGradeDraft", Boolean.valueOf(addGradeDraftAlert));
// for the navigation purpose
List<UserSubmission> userSubmissions = state.getAttribute(USER_SUBMISSIONS) != null ? (List<UserSubmission>) state.getAttribute(USER_SUBMISSIONS):null;
if (userSubmissions != null)
{
for (int i = 0; i < userSubmissions.size(); i++)
{
if (((UserSubmission) userSubmissions.get(i)).getSubmission().getId().equals(submissionId))
{
boolean goPT = false;
boolean goNT = false;
if ((i - 1) >= 0)
{
goPT = true;
}
if ((i + 1) < userSubmissions.size())
{
goNT = true;
}
context.put("goPTButton", Boolean.valueOf(goPT));
context.put("goNTButton", Boolean.valueOf(goNT));
if (i>0)
{
// retrieve the previous submission id
context.put("prevSubmissionId", ((UserSubmission) userSubmissions.get(i-1)).getSubmission().getReference());
}
if (i < userSubmissions.size() - 1)
{
// retrieve the next submission id
context.put("nextSubmissionId", ((UserSubmission) userSubmissions.get(i+1)).getSubmission().getReference());
}
}
}
}
// put supplement item into context
supplementItemIntoContext(state, context, a, null);
// put the grade confirmation message if applicable
if (state.getAttribute(GRADE_SUBMISSION_DONE) != null)
{
context.put("gradingDone", Boolean.TRUE);
state.removeAttribute(GRADE_SUBMISSION_DONE);
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION;
} // build_instructor_grade_submission_context
/**
* Checks whether the time is already past.
* If yes, return the time of three days from current time;
* Otherwise, return the original time
* @param originalTime
* @return
*/
private Time getProperFutureTime(Time originalTime) {
// check whether the time is past already.
// If yes, add three days to the current time
Time time = originalTime;
if (TimeService.newTime().after(time))
{
time = TimeService.newTime(TimeService.newTime().getTime() + 3*24*60*60*1000/*add three days*/);
}
return time;
}
/**
* Responding to the request of submission navigation
* @param rundata
* @param option
*/
public void doPrev_back_next_submission(RunData rundata, String option)
{
SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid());
// save the instructor input
boolean hasChange = readGradeForm(rundata, state, "save");
if (state.getAttribute(STATE_MESSAGE) == null && hasChange)
{
grade_submission_option(rundata, "save");
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if ("next".equals(option))
{
navigateToSubmission(rundata, "nextSubmissionId");
}
else if ("prev".equals(option))
{
navigateToSubmission(rundata, "prevSubmissionId");
}
else if ("back".equals(option))
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
}
}
} // doPrev_back_next_submission
private void navigateToSubmission(RunData rundata, String paramString) {
ParameterParser params = rundata.getParameters();
SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid());
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
String submissionId = StringUtil.trimToNull(params.getString(paramString));
if (submissionId != null)
{
// put submission information into state
putSubmissionInfoIntoState(state, assignmentId, submissionId);
}
}
/**
* Parse time value and put corresponding values into state
* @param context
* @param state
* @param a
* @param timeValue
* @param timeName
* @param month
* @param day
* @param year
* @param hour
* @param min
* @param ampm
*/
private void putTimePropertiesInState(SessionState state, Time timeValue,
String month, String day, String year, String hour, String min, String ampm) {
TimeBreakdown bTime = timeValue.breakdownLocal();
state.setAttribute(month, Integer.valueOf(bTime.getMonth()));
state.setAttribute(day, Integer.valueOf(bTime.getDay()));
state.setAttribute(year, Integer.valueOf(bTime.getYear()));
int bHour = bTime.getHour();
if (bHour >= 12)
{
state.setAttribute(ampm, "PM");
}
else
{
state.setAttribute(ampm, "AM");
}
if (bHour == 0)
{
// for midnight point, we mark it as 12AM
bHour = 12;
}
state.setAttribute(hour, Integer.valueOf((bHour > 12) ? bHour - 12 : bHour));
state.setAttribute(min, Integer.valueOf(bTime.getMin()));
}
/**
* put related time information into context variable
* @param context
* @param state
* @param timeName
* @param month
* @param day
* @param year
* @param hour
* @param min
* @param ampm
*/
private void putTimePropertiesInContext(Context context, SessionState state, String timeName,
String month, String day, String year, String hour, String min, String ampm) {
// get the submission level of close date setting
context.put("name_" + timeName + "Month", month);
context.put("name_" + timeName + "Day", day);
context.put("name_" + timeName + "Year", year);
context.put("name_" + timeName + "Hour", hour);
context.put("name_" + timeName + "Min", min);
context.put("name_" + timeName + "AMPM", ampm);
context.put("value_" + timeName + "Month", (Integer) state.getAttribute(month));
context.put("value_" + timeName + "Day", (Integer) state.getAttribute(day));
context.put("value_" + timeName + "Year", (Integer) state.getAttribute(year));
context.put("value_" + timeName + "AMPM", (String) state.getAttribute(ampm));
context.put("value_" + timeName + "Hour", (Integer) state.getAttribute(hour));
context.put("value_" + timeName + "Min", (Integer) state.getAttribute(min));
}
private List getPrevFeedbackAttachments(ResourceProperties p) {
String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS);
String[] attachmentsReferences = attachmentsString.split(",");
List prevFeedbackAttachments = EntityManager.newReferenceList();
for (int k =0; k < attachmentsReferences.length; k++)
{
prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k]));
}
return prevFeedbackAttachments;
}
/**
* build the instructor preview of grading submission
*/
protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
// assignment
int gradeType = -1;
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
Assignment a = getAssignment(assignmentId, "build_instructor_preview_grade_submission_context", state);
if (a != null)
{
context.put("assignment", a);
gradeType = a.getContent().getTypeOfGrade();
}
// submission
context.put("submission", getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_instructor_preview_grade_submission_context", state));
User user = (User) state.getAttribute(STATE_USER);
context.put("user", user);
context.put("submissionTypeTable", submissionTypeTable());
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
// filter the feedback text for the instructor comment and mark it as red
String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
context.put("feedback_text", feedbackText);
context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT));
// format to show one decimal place
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
if (gradeType == 3)
{
grade = displayGrade(state, grade);
}
context.put("grade", grade);
context.put("comment_open", COMMENT_OPEN);
context.put("comment_close", COMMENT_CLOSE);
context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
if (closeTimeString != null)
{
// close time for resubmit
Time time = TimeService.newTime(Long.parseLong(closeTimeString));
context.put("allowResubmitCloseTime", time.toStringLocalFull());
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION;
} // build_instructor_preview_grade_submission_context
/**
* build the instructor view to grade an assignment
*/
protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("user", state.getAttribute(STATE_USER));
// sorting related fields
context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY));
context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC));
context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME);
context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME);
context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS);
context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE);
context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED);
context.put("sort_submitReview", SORTED_GRADE_SUBMISSION_CONTENTREVIEW);
String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
Assignment assignment = getAssignment(assignmentRef, "build_instructor_grade_assignment_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId());
if (assignment.getContent() != null)
{
context.put("value_SubmissionType", Integer.valueOf(assignment.getContent().getTypeOfSubmission()));
}
// put creator information into context
putCreatorIntoContext(context, assignment);
// ever set the default grade for no-submissions
String defaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE);
if (defaultGrade != null)
{
context.put("defaultGrade", defaultGrade);
}
initViewSubmissionListOption(state);
String view = (String)state.getAttribute(VIEW_SUBMISSION_LIST_OPTION);
context.put("view", view);
// access point url for zip file download
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference(
contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)));
if (!view.equals(rb.getString("gen.viewallgroupssections")))
{
// append the group info to the end
accessPointUrl = accessPointUrl.concat(view);
}
context.put("accessPointUrl", accessPointUrl);
if (AssignmentService.getAllowGroupAssignments())
{
Collection groupsAllowGradeAssignment = AssignmentService.getGroupsAllowGradeAssignment((String) state.getAttribute(STATE_CONTEXT_STRING), assignment.getReference());
// group list which user can add message to
if (groupsAllowGradeAssignment.size() > 0)
{
String sort = (String) state.getAttribute(SORTED_BY);
String asc = (String) state.getAttribute(SORTED_ASC);
if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION)))
{
sort = SORTED_BY_GROUP_TITLE;
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sort);
state.setAttribute(SORTED_ASC, asc);
}
context.put("groups", new SortedIterator(groupsAllowGradeAssignment.iterator(), new AssignmentComparator(state, sort, asc)));
}
}
List<UserSubmission> userSubmissions = prepPage(state);
state.setAttribute(USER_SUBMISSIONS, userSubmissions);
context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS));
// whether to show the resubmission choice
if (state.getAttribute(SHOW_ALLOW_RESUBMISSION) != null)
{
context.put("showAllowResubmission", Boolean.TRUE);
}
// put the re-submission info into context
putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
assignment_resubmission_option_into_context(context, state);
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
context.put("producer", ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"));
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
context.put("submissionTypeTable", submissionTypeTable());
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG));
context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG));
add2ndToolbarFields(data, context);
pagingInfoToContext(state, context);
// put supplement item into context
supplementItemIntoContext(state, context, assignment, null);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT;
} // build_instructor_grade_assignment_context
/**
* make sure the state variable VIEW_SUBMISSION_LIST_OPTION is not null
* @param state
*/
private void initViewSubmissionListOption(SessionState state) {
if (state.getAttribute(VIEW_SUBMISSION_LIST_OPTION) == null)
{
state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, rb.getString("gen.viewallgroupssections"));
}
}
/**
* put the supplement item information into context
* @param state
* @param context
* @param assignment
* @param s
*/
private void supplementItemIntoContext(SessionState state, Context context, Assignment assignment, AssignmentSubmission s) {
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// for model answer
boolean allowViewModelAnswer = m_assignmentSupplementItemService.canViewModelAnswer(assignment, s);
context.put("allowViewModelAnswer", allowViewModelAnswer);
if (allowViewModelAnswer)
{
context.put("assignmentModelAnswerItem", m_assignmentSupplementItemService.getModelAnswer(assignment.getId()));
}
// for note item
boolean allowReadAssignmentNoteItem = m_assignmentSupplementItemService.canReadNoteItem(assignment, contextString);
context.put("allowReadAssignmentNoteItem", allowReadAssignmentNoteItem);
if (allowReadAssignmentNoteItem)
{
context.put("assignmentNoteItem", m_assignmentSupplementItemService.getNoteItem(assignment.getId()));
}
// for all purpose item
boolean allowViewAllPurposeItem = m_assignmentSupplementItemService.canViewAllPurposeItem(assignment);
context.put("allowViewAllPurposeItem", allowViewAllPurposeItem);
if (allowViewAllPurposeItem)
{
context.put("assignmentAllPurposeItem", m_assignmentSupplementItemService.getAllPurposeItem(assignment.getId()));
}
}
/**
* build the instructor view of an assignment
*/
protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("tlang", rb);
String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID);
Assignment assignment = getAssignment(assignmentId, "build_instructor_view_assignment_context", state);
if (assignment != null)
{
context.put("assignment", assignment);
// put the resubmit information into context
assignment_resubmission_option_into_context(context, state);
// put creator information into context
putCreatorIntoContext(context, assignment);
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
List<DecoratedTaggingProvider> providers = addProviders(context, state);
List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>();
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
for (DecoratedTaggingProvider provider : providers)
{
TaggingHelperInfo helper = provider.getProvider()
.getActivityHelperInfo(
assignmentActivityProducer.getActivity(
assignment).getReference());
if (helper != null)
{
activityHelpers.add(helper);
}
}
addActivity(context, assignment);
context.put("activityHelpers", activityHelpers);
context.put("taggable", Boolean.valueOf(true));
}
context.put("currentTime", TimeService.newTime());
context.put("submissionTypeTable", submissionTypeTable());
context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG));
context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT;
} // build_instructor_view_assignment_context
private void putCreatorIntoContext(Context context, Assignment assignment) {
// the creator
String creatorId = assignment.getCreator();
try
{
User creator = UserDirectoryService.getUser(creatorId);
context.put("creator", creator.getDisplayName());
}
catch (Exception ee)
{
context.put("creator", creatorId);
M_log.warn(this + ":build_instructor_view_assignment_context " + ee.getMessage());
}
}
/**
* build the instructor view of reordering assignments
*/
protected String build_instructor_reorder_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("context", state.getAttribute(STATE_CONTEXT_STRING));
List assignments = prepPage(state);
context.put("assignments", assignments.iterator());
context.put("assignmentsize", assignments.size());
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
context.put("site", site);
}
catch (Exception ignore)
{
M_log.warn(this + ":build_instructor_reorder_assignment_context " + ignore.getMessage());
}
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("userDirectoryService", UserDirectoryService.getInstance());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT;
} // build_instructor_reorder_assignment_context
/**
* build the instructor view to view the list of students for an assignment
*/
protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// get the realm and its member
List studentMembers = new Vector();
List allowSubmitMembers = AssignmentService.allowAddAnySubmissionUsers(contextString);
for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();)
{
// get user
try
{
String userId = (String) allowSubmitMembersIterator.next();
User user = UserDirectoryService.getUser(userId);
studentMembers.add(user);
}
catch (Exception ee)
{
M_log.warn(this + ":build_instructor_view_student_assignment_context " + ee.getMessage());
}
}
context.put("studentMembers", new SortedIterator(studentMembers.iterator(), new AssignmentComparator(state, SORTED_USER_BY_SORTNAME, Boolean.TRUE.toString())));
context.put("assignmentService", AssignmentService.getInstance());
Hashtable showStudentAssignments = new Hashtable();
if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null)
{
Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
context.put("studentListShowSet", showStudentListSet);
for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();)
{
// get user
try
{
String userId = (String) showStudentListSetIterator.next();
User user = UserDirectoryService.getUser(userId);
// sort the assignments into the default order before adding
Iterator assignmentSorter = AssignmentService.getAssignmentsForContext(contextString, userId);
// filter to obtain only grade-able assignments
List rv = new Vector();
while (assignmentSorter.hasNext())
{
Assignment a = (Assignment) assignmentSorter.next();
if (AssignmentService.allowGradeSubmission(a.getReference()))
{
rv.add(a);
}
}
Iterator assignmentSortFinal = new SortedIterator(rv.iterator(), new AssignmentComparator(state, SORTED_BY_DEFAULT, Boolean.TRUE.toString()));
showStudentAssignments.put(user, assignmentSortFinal);
}
catch (Exception ee)
{
M_log.warn(this + ":build_instructor_view_student_assignment_context " + ee.getMessage());
}
}
}
context.put("studentAssignmentsTable", showStudentAssignments);
add2ndToolbarFields(data, context);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT;
} // build_instructor_view_students_assignment_context
/**
* build the instructor view to report the submissions
*/
protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("submissions", prepPage(state));
context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY));
context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC));
context.put("sortedBy_lastName", SORTED_SUBMISSION_BY_LASTNAME);
context.put("sortedBy_submitTime", SORTED_SUBMISSION_BY_SUBMIT_TIME);
context.put("sortedBy_grade", SORTED_SUBMISSION_BY_GRADE);
context.put("sortedBy_status", SORTED_SUBMISSION_BY_STATUS);
context.put("sortedBy_released", SORTED_SUBMISSION_BY_RELEASED);
context.put("sortedBy_assignment", SORTED_SUBMISSION_BY_ASSIGNMENT);
context.put("sortedBy_maxGrade", SORTED_SUBMISSION_BY_MAX_GRADE);
add2ndToolbarFields(data, context);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("accessPointUrl", ServerConfigurationService.getAccessUrl()
+ AssignmentService.gradesSpreadsheetReference(contextString, null));
pagingInfoToContext(state, context);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS;
} // build_instructor_report_submissions
// Is Gradebook defined for the site?
protected boolean isGradebookDefined()
{
boolean rv = false;
try
{
GradebookService g = (GradebookService) ComponentManager
.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
if (g.isGradebookDefined(gradebookUid) && (g.currentUserHasEditPerm(gradebookUid) || g.currentUserHasGradingPerm(gradebookUid)))
{
rv = true;
}
}
catch (Exception e)
{
M_log.debug(this + "isGradebookDefined " + rb.getString("addtogradebook.alertMessage") + "\n" + e.getMessage());
}
return rv;
} // isGradebookDefined()
/**
* build the instructor view to download/upload information from archive file
*/
protected String build_instructor_download_upload_all(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
boolean download = (((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_DOWNLOAD_ALL));
context.put("download", Boolean.valueOf(download));
context.put("hasSubmissionText", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT));
context.put("hasSubmissionAttachment", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT));
context.put("hasGradeFile", state.getAttribute(UPLOAD_ALL_HAS_GRADEFILE));
context.put("hasComments", state.getAttribute(UPLOAD_ALL_HAS_COMMENTS));
context.put("hasFeedbackText", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT));
context.put("hasFeedbackAttachment", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT));
context.put("releaseGrades", state.getAttribute(UPLOAD_ALL_RELEASE_GRADES));
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference(
contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF))));
String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
Assignment a = getAssignment(assignmentRef, "build_instructor_download_upload_all", state);
if (a != null)
{
String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference(
contextString, assignmentRef));
context.put("accessPointUrl", accessPointUrl);
// if the assignment is of text-only or allow both text and attachment, include option for uploading student submit text
context.put("includeSubmissionText", Boolean.valueOf(Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION == a.getContent().getTypeOfSubmission() || Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION == a.getContent().getTypeOfSubmission()));
// if the assignment is of attachment-only or allow both text and attachment, include option for uploading student attachment
context.put("includeSubmissionAttachment", Boolean.valueOf(Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION == a.getContent().getTypeOfSubmission() || Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION == a.getContent().getTypeOfSubmission()));
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_UPLOAD_ALL;
} // build_instructor_upload_all
/**
** Retrieve tool title from Tool configuration file or use default
** (This should return i18n version of tool title if available)
**/
private String getToolTitle()
{
Tool tool = ToolManager.getTool(ASSIGNMENT_TOOL_ID);
String toolTitle = null;
if (tool == null)
toolTitle = "Assignments";
else
toolTitle = tool.getTitle();
return toolTitle;
}
/**
* integration with gradebook
*
* @param state
* @param assignmentRef Assignment reference
* @param associateGradebookAssignment The title for the associated GB assignment
* @param addUpdateRemoveAssignment "add" for adding the assignment; "update" for updating the assignment; "remove" for remove assignment
* @param oldAssignment_title The original assignment title
* @param newAssignment_title The updated assignment title
* @param newAssignment_maxPoints The maximum point of the assignment
* @param newAssignment_dueTime The due time of the assignment
* @param submissionRef Any submission grade need to be updated? Do bulk update if null
* @param updateRemoveSubmission "update" for update submission;"remove" for remove submission
*/
protected void integrateGradebook (SessionState state, String assignmentRef, String associateGradebookAssignment, String addUpdateRemoveAssignment, String oldAssignment_title, String newAssignment_title, int newAssignment_maxPoints, Time newAssignment_dueTime, String submissionRef, String updateRemoveSubmission, long category)
{
associateGradebookAssignment = StringUtil.trimToNull(associateGradebookAssignment);
// add or remove external grades to gradebook
// a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden
// b. if Gradebook exists, just call addExternal and removeExternal and swallow any exception. The
// exception are indication that the assessment is already in the Gradebook or there is nothing
// to remove.
String assignmentToolTitle = getToolTitle();
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
GradebookExternalAssessmentService gExternal = (GradebookExternalAssessmentService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
if (g.isGradebookDefined(gradebookUid) && g.currentUserHasGradingPerm(gradebookUid))
{
boolean isExternalAssignmentDefined=gExternal.isExternalAssignmentDefined(gradebookUid, assignmentRef);
boolean isExternalAssociateAssignmentDefined = gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment);
boolean isAssignmentDefined = g.isAssignmentDefined(gradebookUid, associateGradebookAssignment);
if (addUpdateRemoveAssignment != null)
{
// add an entry into Gradebook for newly created assignment or modified assignment, and there wasn't a correspond record in gradebook yet
if ((addUpdateRemoveAssignment.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD) || ("update".equals(addUpdateRemoveAssignment) && !isExternalAssignmentDefined)) && associateGradebookAssignment == null)
{
// add assignment into gradebook
try
{
// add assignment to gradebook
gExternal.addExternalAssessment(gradebookUid, assignmentRef, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), assignmentToolTitle, false, category != -1?Long.valueOf(category):null);
}
catch (AssignmentHasIllegalPointsException e)
{
addAlert(state, rb.getString("addtogradebook.illegalPoints"));
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
catch (ConflictingAssignmentNameException e)
{
// add alert prompting for change assignment title
addAlert(state, rb.getFormattedMessage("addtogradebook.nonUniqueTitle", new Object[]{"\"" + newAssignment_title + "\""}));
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
catch (ConflictingExternalIdException e)
{
// this shouldn't happen, as we have already checked for assignment reference before. Log the error
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
catch (GradebookNotFoundException e)
{
// this shouldn't happen, as we have checked for gradebook existence before
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
catch (Exception e)
{
// ignore
M_log.warn(this + ":integrateGradebook " + e.getMessage());
}
}
else if ("update".equals(addUpdateRemoveAssignment))
{
if (associateGradebookAssignment != null && isExternalAssociateAssignmentDefined)
{
// if there is an external entry created in Gradebook based on this assignment, update it
try
{
// update attributes if the GB assignment was created for the assignment
gExternal.updateExternalAssessment(gradebookUid, associateGradebookAssignment, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), false);
}
catch(Exception e)
{
addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef}));
M_log.warn(this + ":integrateGradebook " + rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef}));
}
}
} // addUpdateRemove != null
else if ("remove".equals(addUpdateRemoveAssignment))
{
// remove assignment and all submission grades
removeNonAssociatedExternalGradebookEntry((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentRef, associateGradebookAssignment, gExternal, gradebookUid);
}
}
if (updateRemoveSubmission != null)
{
Assignment a = getAssignment(assignmentRef, "integrateGradebook", state);
if (a != null)
{
if ("update".equals(updateRemoveSubmission)
&& a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null
&& !a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK).equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)
&& a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
if (submissionRef == null)
{
// bulk add all grades for assignment into gradebook
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
Map m = new HashMap();
// any score to copy over? get all the assessmentGradingData and copy over
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
if (aSubmission.getGradeReleased())
{
User[] submitters = aSubmission.getSubmitters();
if (submitters != null && submitters.length > 0) {
String submitterId = submitters[0].getId();
String gradeString = StringUtil.trimToNull(aSubmission.getGrade(false));
String grade = gradeString != null ? displayGrade(state,gradeString) : null;
m.put(submitterId, grade);
}
}
}
// need to update only when there is at least one submission
if (!m.isEmpty())
{
if (associateGradebookAssignment != null)
{
if (isExternalAssociateAssignmentDefined)
{
// the associated assignment is externally maintained
gExternal.updateExternalAssessmentScoresString(gradebookUid, associateGradebookAssignment, m);
}
else if (isAssignmentDefined)
{
// the associated assignment is internal one, update records one by one
Iterator mKeys = m.keySet().iterator();
while (mKeys.hasNext())
{
String submitterId = (String) mKeys.next();
String grade = StringUtil.trimToNull(displayGrade(state, (String) m.get(submitterId)));
if (grade != null)
{
g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitterId, grade, "");
}
}
}
}
else if (isExternalAssignmentDefined)
{
gExternal.updateExternalAssessmentScoresString(gradebookUid, assignmentRef, m);
}
}
}
else
{
// only update one submission
AssignmentSubmission aSubmission = getSubmission(submissionRef, "integrateGradebook", state);
if (aSubmission != null)
{
User[] submitters = aSubmission.getSubmitters();
String gradeString = displayGrade(state, StringUtil.trimToNull(aSubmission.getGrade(false)));
if (submitters != null && submitters.length > 0)
{
if (associateGradebookAssignment != null)
{
if (gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment))
{
// the associated assignment is externally maintained
gExternal.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? gradeString : "");
}
else if (g.isAssignmentDefined(gradebookUid, associateGradebookAssignment))
{
// the associated assignment is internal one, update records
g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? gradeString : "", "");
}
}
else
{
gExternal.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? gradeString : "");
}
}
}
}
}
else if ("remove".equals(updateRemoveSubmission))
{
if (submissionRef == null)
{
// remove all submission grades (when changing the associated entry in Gradebook)
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
// any score to copy over? get all the assessmentGradingData and copy over
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
User[] submitters = aSubmission.getSubmitters();
if (submitters != null && submitters.length > 0)
{
if (isExternalAssociateAssignmentDefined)
{
// if the old associated assignment is an external maintained one
gExternal.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null);
}
else if (isAssignmentDefined)
{
g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null, assignmentToolTitle);
}
}
}
}
else
{
// remove only one submission grade
AssignmentSubmission aSubmission = getSubmission(submissionRef, "integrateGradebook", state);
if (aSubmission != null)
{
User[] submitters = aSubmission.getSubmitters();
if (submitters != null && submitters.length > 0)
{
gExternal.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), null);
}
}
}
}
}
}
}
} // integrateGradebook
/**
* Go to the instructor view
*/
public void doView_instructor(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doView_instructor
/**
* Go to the student view
*/
public void doView_student(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// to the student list of assignment view
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doView_student
/**
* Action is to view the content of one specific assignment submission
*/
public void doView_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the submission context
resetViewSubmission(state);
ParameterParser params = data.getParameters();
String assignmentReference = params.getString("assignmentReference");
state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference);
User u = (User) state.getAttribute(STATE_USER);
Assignment a = getAssignment(assignmentReference, "doView_submission", state);
if (a != null)
{
AssignmentSubmission submission = getSubmission(assignmentReference, u, "doView_submission", state);
if (submission != null)
{
state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText());
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (Boolean.valueOf(submission.getHonorPledgeFlag())).toString());
List v = EntityManager.newReferenceList();
Iterator l = submission.getSubmittedAttachments().iterator();
while (l.hasNext())
{
v.add(l.next());
}
state.setAttribute(ATTACHMENTS, v);
}
else
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false");
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
// put resubmission option into state
assignment_resubmission_option_into_state(a, submission, state);
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION);
if (submission != null)
{
// submission read event
m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submission.getId(), false));
}
else
{
// otherwise, the student just read assignment description and prepare for submission
m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, a.getId(), false));
}
}
} // doView_submission
/**
* Action is to view the content of one specific assignment submission
*/
public void doView_submission_list_option(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String view = params.getString("view");
state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, view);
} // doView_submission_list_option
/**
* Preview of the submission
*/
public void doPreview_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, aReference);
Assignment a = getAssignment(aReference, "doPreview_submission", state);
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
state.setAttribute(PREVIEW_SUBMISSION_TEXT, text);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
// assign the honor pledge attribute
String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honor_pledge_yes == null)
{
honor_pledge_yes = "false";
}
state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes);
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes);
// get attachment input and generate alert message according to assignment submission type
checkSubmissionTextAttachmentInput(data, state, a, text);
state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION);
}
} // doPreview_submission
/**
* Preview of the grading of submission
*/
public void doPreview_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read user input
readGradeForm(data, state, "read");
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION);
}
} // doPreview_grade_submission
/**
* Action is to end the preview submission process
*/
public void doDone_preview_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION);
} // doDone_preview_submission
/**
* Action is to end the view assignment process
*/
public void doDone_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doDone_view_assignments
/**
* Action is to end the preview new assignment process
*/
public void doDone_preview_new_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the new assignment page
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
} // doDone_preview_new_assignment
/**
* Action is to end the user view assignment process and redirect him to the assignment list view
*/
public void doCancel_student_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view assignment
state.setAttribute(VIEW_ASSIGNMENT_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_student_view_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_show_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view assignment
state.setAttribute(VIEW_ASSIGNMENT_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_show_submission
/**
* Action is to cancel the delete assignment process
*/
public void doCancel_delete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the show assignment object
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
// back to the instructor list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_delete_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_edit_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the assignment object
resetAssignment(state);
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
// reset sorting
setDefaultSort(state);
} // doCancel_edit_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_new_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the assignment object
resetAssignment(state);
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
// reset sorting
setDefaultSort(state);
} // doCancel_new_assignment
/**
* Action is to cancel the grade submission process
*/
public void doCancel_grade_submission(RunData data)
{
// put submission information into state
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
putSubmissionInfoIntoState(state, assignmentId, sId);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
} // doCancel_grade_submission
/**
* clean the state variables related to grading page
* @param state
*/
private void resetGradeSubmission(SessionState state) {
// reset the grade parameters
state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT);
state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
state.removeAttribute(GRADE_SUBMISSION_GRADE);
state.removeAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
state.removeAttribute(GRADE_SUBMISSION_DONE);
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
resetAllowResubmitParams(state);
}
/**
* Action is to cancel the preview grade process
*/
public void doCancel_preview_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the instructor view of grading a submission
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
} // doCancel_preview_grade_submission
/**
* Action is to cancel the reorder process
*/
public void doCancel_reorder(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_reorder
/**
* Action is to cancel the preview grade process
*/
public void doCancel_preview_to_list_submission(RunData data)
{
doCancel_grade_submission(data);
} // doCancel_preview_to_list_submission
/**
* Action is to return to the view of list assignments
*/
public void doList_assignments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doList_assignments
/**
* Action is to cancel the student view grade process
*/
public void doCancel_view_grade(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view grade submission id
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_view_grade
/**
* Action is to save the grade to submission
*/
public void doSave_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "save");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "save");
}
} // doSave_grade_submission
/**
* Action is to release the grade to submission
*/
public void doRelease_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "release");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "release");
}
} // doRelease_grade_submission
/**
* Action is to return submission with or without grade
*/
public void doReturn_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "return");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "return");
}
} // doReturn_grade_submission
/**
* Action is to return submission with or without grade from preview
*/
public void doReturn_preview_grade_submission(RunData data)
{
grade_submission_option(data, "return");
} // doReturn_grade_preview_submission
/**
* Action is to save submission with or without grade from preview
*/
public void doSave_preview_grade_submission(RunData data)
{
grade_submission_option(data, "save");
} // doSave_grade_preview_submission
/**
* Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade.
*/
private void grade_submission_option(RunData data, String gradeOption)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false;
String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID);
// for points grading, one have to enter number as the points
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
AssignmentSubmissionEdit sEdit = editSubmission(sId, "grade_submission_option", state);
if (sEdit != null)
{
Assignment a = sEdit.getAssignment();
int typeOfGrade = a.getContent().getTypeOfGrade();
if (!withGrade)
{
// no grade input needed for the without-grade version of assignment tool
sEdit.setGraded(true);
if ("return".equals(gradeOption) || "release".equals(gradeOption))
{
sEdit.setGradeReleased(true);
}
}
else if (grade == null)
{
sEdit.setGrade("");
sEdit.setGraded(false);
sEdit.setGradeReleased(false);
}
else
{
sEdit.setGrade(grade);
if (grade.length() != 0)
{
sEdit.setGraded(true);
}
else
{
sEdit.setGraded(false);
}
}
if ("release".equals(gradeOption))
{
sEdit.setGradeReleased(true);
sEdit.setGraded(true);
// clear the returned flag
sEdit.setReturned(false);
sEdit.setTimeReturned(null);
}
else if ("return".equals(gradeOption))
{
sEdit.setGradeReleased(true);
sEdit.setGraded(true);
sEdit.setReturned(true);
sEdit.setTimeReturned(TimeService.newTime());
sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue());
}
else if ("save".equals(gradeOption))
{
sEdit.setGradeReleased(false);
sEdit.setReturned(false);
sEdit.setTimeReturned(null);
}
ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit();
if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// get resubmit number
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null)
{
// get resubmit time
Time closeTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
}
else
{
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
}
else
{
// clean resubmission property
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
// the instructor comment
String feedbackCommentString = StringUtil
.trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
if (feedbackCommentString != null)
{
sEdit.setFeedbackComment(feedbackCommentString);
}
// the instructor inline feedback
String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
if (feedbackTextString != null)
{
sEdit.setFeedbackText(feedbackTextString);
}
List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
if (v != null)
{
// clear the old attachments first
sEdit.clearFeedbackAttachments();
for (int i = 0; i < v.size(); i++)
{
sEdit.addFeedbackAttachment((Reference) v.get(i));
}
}
String sReference = sEdit.getReference();
AssignmentService.commitEdit(sEdit);
// update grades in gradebook
String aReference = a.getReference();
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if ("release".equals(gradeOption) || "return".equals(gradeOption))
{
// update grade in gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update", -1);
}
else
{
// remove grade from gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "remove", -1);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// put submission information into state
putSubmissionInfoIntoState(state, assignmentId, sId);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
state.setAttribute(GRADE_SUBMISSION_DONE, Boolean.TRUE);
}
else
{
state.removeAttribute(GRADE_SUBMISSION_DONE);
}
} // grade_submission_option
/**
* Action is to save the submission as a draft
*/
public void doSave_submission(RunData data)
{
// save submission
post_save_submission(data, false);
} // doSave_submission
/**
* set the resubmission related properties in AssignmentSubmission object
* @param a
* @param edit
*/
private void setResubmissionProperties(Assignment a,
AssignmentSubmissionEdit edit) {
// get the assignment setting for resubmitting
ResourceProperties assignmentProperties = a.getProperties();
String assignmentAllowResubmitNumber = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (assignmentAllowResubmitNumber != null)
{
edit.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
edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, assignmentAllowResubmitCloseDate != null?assignmentAllowResubmitCloseDate:String.valueOf(a.getCloseTime().getTime()));
}
}
/**
* Action is to post the submission
*/
public void doPost_submission(RunData data)
{
// post submission
post_save_submission(data, true);
} // doPost_submission
/**
* Inner method used for post or save submission
* @param data
* @param post
*/
private void post_save_submission(RunData data, boolean post)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment a = getAssignment(aReference, "post_save_submission", state);
if (a != null && AssignmentService.canSubmit(contextString, a))
{
ParameterParser params = data.getParameters();
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // check formatting error whether the student is posting or saving
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
if (text == null)
{
text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT);
}
else
{
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
}
String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honorPledgeYes == null)
{
honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
}
if (honorPledgeYes == null)
{
honorPledgeYes = "false";
}
User u = (User) state.getAttribute(STATE_USER);
String assignmentId = "";
if (state.getAttribute(STATE_MESSAGE) == null)
{
assignmentId = a.getId();
if (a.getContent().getHonorPledge() != 1)
{
if (!Boolean.valueOf(honorPledgeYes).booleanValue())
{
addAlert(state, rb.getString("youarenot18"));
}
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes);
}
// get attachment input and generate alert message according to assignment submission type
checkSubmissionTextAttachmentInput(data, state, a, text);
}
if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null))
{
AssignmentSubmission submission = getSubmission(a.getReference(), u, "post_save_submission", state);
if (submission != null)
{
// the submission already exists, change the text and honor pledge value, post it
AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "post_save_submission", state);
if (sEdit != null)
{
ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit();
sEdit.setSubmittedText(text);
sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
sEdit.setTimeSubmitted(TimeService.newTime());
sEdit.setSubmitted(post);
// decrease the allow_resubmit_number, if this submission has been submitted.
if (sEdit.getSubmitted() && sEdit.getTimeSubmitted() != null && sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
// minus 1 from the submit number, if the number is not -1 (not unlimited)
if (number>=1)
{
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1));
}
}
// for resubmissions
// when resubmit, keep the Returned flag on till the instructor grade again.
Time now = TimeService.newTime();
if (sEdit.getGraded() && sEdit.getReturned() && sEdit.getGradeReleased())
{
// add the current grade into previous grade histroy
String previousGrades = (String) sEdit.getProperties().getProperty(
ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES);
if (previousGrades == null)
{
previousGrades = (String) sEdit.getProperties().getProperty(
ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES);
if (previousGrades != null)
{
int typeOfGrade = a.getContent().getTypeOfGrade();
if (typeOfGrade == 3)
{
// point grade assignment type
// some old unscaled grades, need to scale the number and remove the old property
String[] grades = StringUtil.split(previousGrades, " ");
String newGrades = "";
for (int jj = 0; jj < grades.length; jj++)
{
String grade = grades[jj];
if (grade.indexOf(".") == -1)
{
// show the grade with decimal point
grade = grade.concat(".0");
}
newGrades = newGrades.concat(grade + " ");
}
previousGrades = newGrades;
}
sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES);
}
else
{
previousGrades = "";
}
}
previousGrades = "<h4>" + now.toStringLocalFull() + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getGradeDisplay() + "</div>" +previousGrades;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES,
previousGrades);
// clear the current grade and make the submission ungraded
sEdit.setGraded(false);
sEdit.setGrade("");
sEdit.setGradeReleased(false);
// keep the history of assignment feed back text
String feedbackTextHistory = sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)
: "";
feedbackTextHistory = "<h4>" + now.toStringLocalFull() + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getFeedbackText() + "</div>" + feedbackTextHistory;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT,
feedbackTextHistory);
// keep the history of assignment feed back comment
String feedbackCommentHistory = sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)
: "";
feedbackCommentHistory = "<h4>" + now.toStringLocalFull() + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getFeedbackComment() + "</div>" + feedbackCommentHistory;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT,
feedbackCommentHistory);
// keep the history of assignment feed back comment
String feedbackAttachmentHistory = sPropertiesEdit
.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit
.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS)
: "";
List feedbackAttachments = sEdit.getFeedbackAttachments();
String att = "";
for (int k = 0; k<feedbackAttachments.size();k++)
{
// use comma as separator for attachments
att = att + ((Reference) feedbackAttachments.get(k)).getReference() + ",";
}
feedbackAttachmentHistory = att + feedbackAttachmentHistory;
sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS,
feedbackAttachmentHistory);
// reset the previous grading context
sEdit.setFeedbackText("");
sEdit.setFeedbackComment("");
sEdit.clearFeedbackAttachments();
}
sEdit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
//Post the attachments before clearing so that we don't sumbit duplicate attachments
//Check if we need to post the attachments
if (a.getContent().getAllowReviewService()) {
if (!attachments.isEmpty()) {
sEdit.postAttachment(attachments);
}
}
// clear the old attachments first
sEdit.clearSubmittedAttachments();
// add each new attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
sEdit.addSubmittedAttachment((Reference) it.next());
}
}
AssignmentService.commitEdit(sEdit);
}
}
else
{
// new submission
try
{
AssignmentSubmissionEdit edit = AssignmentService.addSubmission(contextString, assignmentId, SessionManager.getCurrentSessionUserId());
edit.setSubmittedText(text);
edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
edit.setTimeSubmitted(TimeService.newTime());
edit.setSubmitted(post);
edit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
// add each attachment
if ((!attachments.isEmpty()) && a.getContent().getAllowReviewService())
edit.postAttachment(attachments);
// add each attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
edit.addSubmittedAttachment((Reference) it.next());
}
}
// set the resubmission properties
setResubmissionProperties(a, edit);
AssignmentService.commitEdit(edit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot13"));
M_log.warn(this + ":post_save_submission " + e.getMessage());
}
} // if-else
} // if
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION);
}
} // if
} // post_save_submission
private void checkSubmissionTextAttachmentInput(RunData data,
SessionState state, Assignment a, String text) {
if (a != null)
{
// check the submission inputs based on the submission type
int submissionType = a.getContent().getTypeOfSubmission();
if (submissionType == 1)
{
// for the inline only submission
if (text.length() == 0)
{
addAlert(state, rb.getString("youmust7"));
}
}
else if (submissionType == 2)
{
// dealing with single file uplaod
doAttachUpload(data, false);
// for the attachment only submission
Vector v = (Vector) state.getAttribute(ATTACHMENTS);
if ((v == null) || (v.size() == 0))
{
addAlert(state, rb.getString("youmust1"));
}
}
else if (submissionType == 3)
{
// dealing with single file uplaod
doAttachUpload(data, false);
// for the inline and attachment submission
Vector v = (Vector) state.getAttribute(ATTACHMENTS);
if ((text.length() == 0 || "<br/>".equals(text)) && ((v == null) || (v.size() == 0)))
{
addAlert(state, rb.getString("youmust2"));
}
}
else if (submissionType == Assignment.SINGLE_ATTACHMENT_SUBMISSION)
{
// dealing with single file uplaod
doAttachUpload(data, true);
}
}
}
/**
* Action is to confirm the submission and return to list view
*/
public void doConfirm_assignment_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
/**
* Action is to show the new assignment screen
*/
public void doNew_assignment(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
initializeAssignment(state);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot_addAssignment"));
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
}
} // doNew_Assignment
/**
* Action is to show the reorder assignment screen
*/
public void doReorder(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// this insures the default order is loaded into the reordering tool
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
if (!alertGlobalNavigation(state, data))
{
if (AssignmentService.allowAllGroups((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REORDER_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot19"));
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
}
} // doReorder
/**
* Action is to save the input infos for assignment fields
*
* @param validify
* Need to validify the inputs or not
*/
protected void setNewAssignmentParameters(RunData data, boolean validify)
{
// read the form inputs
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// put the input value into the state attributes
String title = params.getString(NEW_ASSIGNMENT_TITLE);
state.setAttribute(NEW_ASSIGNMENT_TITLE, title);
String order = params.getString(NEW_ASSIGNMENT_ORDER);
state.setAttribute(NEW_ASSIGNMENT_ORDER, order);
if (title == null || title.length() == 0)
{
// empty assignment title
addAlert(state, rb.getString("plespethe1"));
}
// open time
Time openTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM, "date.opendate");
// due time
Time dueTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM, "date.duedate");
// show alert message when due date is in past. Remove it after user confirms the choice.
if (dueTime != null && dueTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) == null)
{
state.setAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE, Boolean.TRUE);
}
else
{
// clean the attribute after user confirm
state.removeAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE);
}
if (state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) != null && validify)
{
addAlert(state, rb.getString("assig4"));
}
if (openTime != null && dueTime != null && !dueTime.after(openTime))
{
addAlert(state, rb.getString("assig3"));
}
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true));
// close time
Time closeTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM, "date.closedate");
if (openTime != null && closeTime != null && !closeTime.after(openTime))
{
addAlert(state, rb.getString("acesubdea3"));
}
if (dueTime != null && closeTime != null && closeTime.before(dueTime))
{
addAlert(state, rb.getString("acesubdea2"));
}
// SECTION MOD
String sections_string = "";
String mode = (String) state.getAttribute(STATE_MODE);
if (mode == null) mode = "";
state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string);
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE)));
// Skip category if it was never set.
Long catInt = Long.valueOf(-1);
if(params.getString(NEW_ASSIGNMENT_CATEGORY) != null)
catInt = Long.valueOf(params.getString(NEW_ASSIGNMENT_CATEGORY));
state.setAttribute(NEW_ASSIGNMENT_CATEGORY, catInt);
int gradeType = -1;
// grade type and grade points
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE));
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(gradeType));
}
String r = params.getString(NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
String b;
// set whether we use the review service or not
if (r == null) b = Boolean.FALSE.toString();
else b = Boolean.TRUE.toString();
state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, b);
//set whether students can view the review service results
r = params.getString(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW);
if (r == null) b = Boolean.FALSE.toString();
else b = Boolean.TRUE.toString();
state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, b);
// treat the new assignment description as formatted text
boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors
String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION),
checkForFormattingErrors);
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description);
if (state.getAttribute(CALENDAR) != null)
{
// calendar enabled for the site
if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null
&& params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString());
}
else
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString());
}
}
else
{
// no calendar yet for the site
state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
}
if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null
&& params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)
.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString());
}
else
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString());
}
String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
// set the honor pledge to be "no honor pledge"
if (s == null) s = "1";
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s);
String grading = params.getString(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading);
// only when choose to associate with assignment in Gradebook
String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (grading != null)
{
if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE))
{
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment);
}
else
{
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, "");
}
if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// gradebook integration only available to point-grade assignment
if (gradeType != Assignment.SCORE_GRADE_TYPE)
{
addAlert(state, rb.getString("addtogradebook.wrongGradeScale"));
}
// if chosen as "associate", have to choose one assignment from Gradebook
if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtil.trimToNull(associateAssignment) == null)
{
addAlert(state, rb.getString("grading.associate.alert"));
}
}
}
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments == null || attachments.isEmpty())
{
// read from vm file
String[] attachmentIds = data.getParameters().getStrings("attachments");
if (attachmentIds != null && attachmentIds.length != 0)
{
attachments = new Vector();
for (int i= 0; i<attachmentIds.length;i++)
{
attachments.add(EntityManager.newReference(attachmentIds[i]));
}
}
}
state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments);
if (validify)
{
if ((description == null) || (description.length() == 0) || ("<br/>".equals(description)) && ((attachments == null || attachments.size() == 0)))
{
// if there is no description nor an attachment, show the following alert message.
// One could ignore the message and still post the assignment
if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null)
{
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString());
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
}
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
}
}
if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null)
{
addAlert(state, rb.getString("thiasshas"));
}
// assignment range?
String range = data.getParameters().getString("range");
state.setAttribute(NEW_ASSIGNMENT_RANGE, range);
if ("groups".equals(range))
{
String[] groupChoice = data.getParameters().getStrings("selectedGroups");
if (groupChoice != null && groupChoice.length != 0)
{
state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice)));
}
else
{
state.setAttribute(NEW_ASSIGNMENT_GROUPS, null);
addAlert(state, rb.getString("java.alert.youchoosegroup"));
}
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
}
// allow resubmission numbers
if (params.getString("allowResToggle") != null && params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// read in allowResubmit params
readAllowResubmitParams(params, state, null);
}
else
{
resetAllowResubmitParams(state);
}
// assignment notification option
String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS);
if (notiOption != null)
{
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption);
}
// release grade notification option
String releaseGradeOption = params.getString(ASSIGNMENT_RELEASEGRADE_NOTIFICATION);
if (releaseGradeOption != null)
{
state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, releaseGradeOption);
}
// read inputs for supplement items
setNewAssignmentParametersSupplementItems(validify, state, params);
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
// the grade point
String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS);
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints);
if (gradePoints != null)
{
if (gradeType == 3)
{
if ((gradePoints.length() == 0))
{
// in case of point grade assignment, user must specify maximum grade point
addAlert(state, rb.getString("plespethe3"));
}
else
{
validPointGrade(state, gradePoints);
// when scale is points, grade must be integer and less than maximum value
if (state.getAttribute(STATE_MESSAGE) == null)
{
gradePoints = scalePointGrade(state, gradePoints);
}
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints);
}
}
}
}
} // setNewAssignmentParameters
/**
* read inputs for supplement items
* @param validify
* @param state
* @param params
*/
private void setNewAssignmentParametersSupplementItems(boolean validify,
SessionState state, ParameterParser params) {
/********************* MODEL ANSWER ITEM *********************/
String modelAnswer_to_delete = StringUtil.trimToNull(params.getString("modelanswer_to_delete"));
if (modelAnswer_to_delete != null)
{
state.setAttribute(MODELANSWER_TO_DELETE, modelAnswer_to_delete);
}
String modelAnswer_text = StringUtil.trimToNull(params.getString("modelanswer_text"));
if (modelAnswer_text != null)
{
state.setAttribute(MODELANSWER_TEXT, modelAnswer_text);
}
String modelAnswer_showto = StringUtil.trimToNull(params.getString("modelanswer_showto"));
if (modelAnswer_showto != null)
{
state.setAttribute(MODELANSWER_SHOWTO, modelAnswer_showto);
}
if (modelAnswer_text != null || !"0".equals(modelAnswer_showto) || state.getAttribute(MODELANSWER_ATTACHMENTS) != null)
{
// there is Model Answer input
state.setAttribute(MODELANSWER, Boolean.TRUE);
if (validify && !"true".equalsIgnoreCase(modelAnswer_to_delete))
{
// show alert when there is no model answer input
if (modelAnswer_text == null)
{
addAlert(state, rb.getString("modelAnswer.alert.modelAnswer"));
}
// show alert when user didn't select show-to option
if ("0".equals(modelAnswer_showto))
{
addAlert(state, rb.getString("modelAnswer.alert.showto"));
}
}
}
else
{
state.removeAttribute(MODELANSWER);
}
/**************** NOTE ITEM ********************/
String note_to_delete = StringUtil.trimToNull(params.getString("note_to_delete"));
if (note_to_delete != null)
{
state.setAttribute(NOTE_TO_DELETE, note_to_delete);
}
String note_text = StringUtil.trimToNull(params.getString("note_text"));
if (note_text != null)
{
state.setAttribute(NOTE_TEXT, note_text);
}
String note_to = StringUtil.trimToNull(params.getString("note_to"));
if (note_to != null)
{
state.setAttribute(NOTE_SHAREWITH, note_to);
}
if (note_text != null || !"0".equals(note_to))
{
// there is Note Item input
state.setAttribute(NOTE, Boolean.TRUE);
if (validify && !"true".equalsIgnoreCase(note_to_delete))
{
// show alert when there is no note text
if (note_text == null)
{
addAlert(state, rb.getString("note.alert.text"));
}
// show alert when there is no share option
if ("0".equals(note_to))
{
addAlert(state, rb.getString("note.alert.to"));
}
}
}
else
{
state.removeAttribute(NOTE);
}
/****************** ALL PURPOSE ITEM **********************/
String allPurpose_to_delete = StringUtil.trimToNull(params.getString("allPurpose_to_delete"));
if ( allPurpose_to_delete != null)
{
state.setAttribute(ALLPURPOSE_TO_DELETE, allPurpose_to_delete);
}
String allPurposeTitle = StringUtil.trimToNull(params.getString("allPurposeTitle"));
if (allPurposeTitle != null)
{
state.setAttribute(ALLPURPOSE_TITLE, allPurposeTitle);
}
String allPurposeText = StringUtil.trimToNull(params.getString("allPurposeText"));
if (allPurposeText != null)
{
state.setAttribute(ALLPURPOSE_TEXT, allPurposeText);
}
if (StringUtil.trimToNull(params.getString("allPurposeHide")) != null)
{
state.setAttribute(ALLPURPOSE_HIDE, Boolean.valueOf(params.getString("allPurposeHide")));
}
if (StringUtil.trimToNull(params.getString("allPurposeShowFrom")) != null)
{
state.setAttribute(ALLPURPOSE_SHOW_FROM, Boolean.valueOf(params.getString("allPurposeShowFrom")));
// allpurpose release time
putTimeInputInState(params, state, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, ALLPURPOSE_RELEASE_AMPM, "date.allpurpose.releasedate");
}
else
{
state.removeAttribute(ALLPURPOSE_SHOW_FROM);
}
if (StringUtil.trimToNull(params.getString("allPurposeShowTo")) != null)
{
state.setAttribute(ALLPURPOSE_SHOW_TO, Boolean.valueOf(params.getString("allPurposeShowTo")));
// allpurpose retract time
putTimeInputInState(params, state, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, ALLPURPOSE_RETRACT_AMPM, "date.allpurpose.retractdate");
}
else
{
state.removeAttribute(ALLPURPOSE_SHOW_TO);
}
String siteId = (String)state.getAttribute(STATE_CONTEXT_STRING);
List<String> accessList = new Vector<String>();
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(siteId));
Set<Role> roles = realm.getRoles();
for(Iterator iRoles = roles.iterator(); iRoles.hasNext();)
{
// iterator through roles first
Role role = (Role) iRoles.next();
if (params.getString("allPurpose_" + role.getId()) != null)
{
accessList.add(role.getId());
}
else
{
// if the role is not selected, iterate through the users with this role
Set userIds = realm.getUsersHasRole(role.getId());
for(Iterator iUserIds = userIds.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
if (params.getString("allPurpose_" + userId) != null)
{
accessList.add(userId);
}
}
}
}
}
catch (Exception e)
{
M_log.warn(this + ":setNewAssignmentParameters" + e.toString() + "error finding authzGroup for = " + siteId);
}
state.setAttribute(ALLPURPOSE_ACCESS, accessList);
if (allPurposeTitle != null || allPurposeText != null || (accessList != null && !accessList.isEmpty()) || state.getAttribute(ALLPURPOSE_ATTACHMENTS) != null)
{
// there is allpupose item input
state.setAttribute(ALLPURPOSE, Boolean.TRUE);
if (validify && !"true".equalsIgnoreCase(allPurpose_to_delete))
{
if (allPurposeTitle == null)
{
// missing title
addAlert(state, rb.getString("allPurpose.alert.title"));
}
if (allPurposeText == null)
{
// missing text
addAlert(state, rb.getString("allPurpose.alert.text"));
}
if (accessList == null || accessList.isEmpty())
{
// missing access choice
addAlert(state, rb.getString("allPurpose.alert.access"));
}
}
}
else
{
state.removeAttribute(ALLPURPOSE);
}
}
/**
* read time input and assign it to state attributes
* @param params
* @param state
* @param monthString
* @param dayString
* @param yearString
* @param hourString
* @param minString
* @param ampmString
* @param invalidBundleMessage
* @return
*/
Time putTimeInputInState(ParameterParser params, SessionState state, String monthString, String dayString, String yearString, String hourString, String minString, String ampmString, String invalidBundleMessage)
{
int month = (Integer.valueOf(params.getString(monthString))).intValue();
state.setAttribute(monthString, Integer.valueOf(month));
int day = (Integer.valueOf(params.getString(dayString))).intValue();
state.setAttribute(dayString, Integer.valueOf(day));
int year = (Integer.valueOf(params.getString(yearString))).intValue();
state.setAttribute(yearString, Integer.valueOf(year));
int hour = (Integer.valueOf(params.getString(hourString))).intValue();
state.setAttribute(hourString, Integer.valueOf(hour));
int min = (Integer.valueOf(params.getString(minString))).intValue();
state.setAttribute(minString, Integer.valueOf(min));
String ampm = params.getString(ampmString);
state.setAttribute(ampmString, ampm);
if (("PM".equals(ampm)) && (hour != 12))
{
hour = hour + 12;
}
if ((hour == 12) && ("AM".equals(ampm)))
{
hour = 0;
}
// validate date
if (!Validator.checkDate(day, month, year))
{
addAlert(state, rb.getFormattedMessage("date.invalid", new Object[]{rb.getString(invalidBundleMessage)}));
}
return TimeService.newTimeLocal(year, month, day, hour, min, 0, 0);
}
/**
* Action is to hide the preview assignment student view
*/
public void doHide_submission_assignment_instruction(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false));
// save user input
readGradeForm(data, state, "read");
} // doHide_preview_assignment_student_view
/**
* Action is to show the preview assignment student view
*/
public void doShow_submission_assignment_instruction(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true));
// save user input
readGradeForm(data, state, "read");
} // doShow_submission_assignment_instruction
/**
* Action is to hide the preview assignment student view
*/
public void doHide_preview_assignment_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(true));
} // doHide_preview_assignment_student_view
/**
* Action is to show the preview assignment student view
*/
public void doShow_preview_assignment_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(false));
} // doShow_preview_assignment_student_view
/**
* Action is to hide the preview assignment assignment infos
*/
public void doHide_preview_assignment_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(true));
} // doHide_preview_assignment_assignment
/**
* Action is to show the preview assignment assignment info
*/
public void doShow_preview_assignment_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false));
} // doShow_preview_assignment_assignment
/**
* Action is to hide the assignment content in the view assignment page
*/
public void doHide_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(true));
} // doHide_view_assignment
/**
* Action is to show the assignment content in the view assignment page
*/
public void doShow_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(false));
} // doShow_view_assignment
/**
* Action is to hide the student view in the view assignment page
*/
public void doHide_view_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(true));
} // doHide_view_student_view
/**
* Action is to show the student view in the view assignment page
*/
public void doShow_view_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(false));
} // doShow_view_student_view
/**
* Action is to post assignment
*/
public void doPost_assignment(RunData data)
{
// post assignment
post_save_assignment(data, "post");
} // doPost_assignment
/**
* Action is to tag items via an items tagging helper
*/
public void doHelp_items(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String activityRef = params.getString(ACTIVITY_REF);
TaggingHelperInfo helperInfo = provider
.getItemsHelperInfo(activityRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (Iterator<String> keys = helperParms.keySet().iterator(); keys
.hasNext();) {
String key = keys.next();
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_items
/**
* Action is to tag an individual item via an item tagging helper
*/
public void doHelp_item(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String itemRef = params.getString(ITEM_REF);
TaggingHelperInfo helperInfo = provider
.getItemHelperInfo(itemRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (Iterator<String> keys = helperParms.keySet().iterator(); keys
.hasNext();) {
String key = keys.next();
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_item
/**
* Action is to tag an activity via an activity tagging helper
*/
public void doHelp_activity(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String activityRef = params.getString(ACTIVITY_REF);
TaggingHelperInfo helperInfo = provider
.getActivityHelperInfo(activityRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (String key : helperParms.keySet()) {
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_activity
/**
* post or save assignment
*/
private void post_save_assignment(RunData data, String postOrSave)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING);
boolean post = (postOrSave != null) && "post".equals(postOrSave);
// assignment old title
String aOldTitle = null;
// assignment old associated Gradebook entry if any
String oAssociateGradebookAssignment = null;
String mode = (String) state.getAttribute(STATE_MODE);
if (!MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode))
{
// read input data if the mode is not preview mode
setNewAssignmentParameters(data, true);
}
String assignmentId = params.getString("assignmentId");
String assignmentContentId = params.getString("assignmentContentId");
// whether this is an editing which changes non-electronic assignment to any other type?
boolean bool_change_from_non_electronic = false;
// whether this is an editing which changes non-point graded assignment to point graded assignment?
boolean bool_change_from_non_point = false;
// whether there is a change in the assignment resubmission choice
boolean bool_change_resubmit_option = false;
if (state.getAttribute(STATE_MESSAGE) == null)
{
// AssignmentContent object
AssignmentContentEdit ac = editAssignmentContent(assignmentContentId, "post_save_assignment", state, true);
bool_change_from_non_electronic = change_from_non_electronic(state, assignmentId, assignmentContentId, ac);
bool_change_from_non_point = change_from_non_point(state, assignmentId, assignmentContentId, ac);
// Assignment
AssignmentEdit a = editAssignment(assignmentId, "post_save_assignment", state, true);
bool_change_resubmit_option = change_resubmit_option(state, a);
// put the names and values into vm file
String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE);
String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER);
// open time
Time openTime = getTimeFromState(state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM);
// due time
Time dueTime = getTimeFromState(state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM);
// close time
Time closeTime = dueTime;
boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue();
if (enableCloseDate)
{
closeTime = getTimeFromState(state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM);
}
// sections
String section = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION);
int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue();
int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue();
String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION);
String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null;
String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ;
long category = state.getAttribute(NEW_ASSIGNMENT_CATEGORY) != null ? ((Long) state.getAttribute(NEW_ASSIGNMENT_CATEGORY)).longValue() : -1;
String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null;
if (ac != null && ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// resubmit option is not allowed for non-electronic type
allowResubmitNumber = null;
}
boolean useReviewService = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE));
boolean allowStudentViewReport = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW));
// the attachments
List attachments = (List) state.getAttribute(NEW_ASSIGNMENT_ATTACHMENT);
// set group property
String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE);
Collection groups = new Vector();
try
{
Site site = SiteService.getSite(siteId);
Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS);
if (Assignment.AssignmentAccess.GROUPED.equals(range) && (groupChoice == null || groupChoice.size() == 0))
{
// show alert if no group is selected for the group access assignment
addAlert(state, rb.getString("java.alert.youchoosegroup"));
}
else if (groupChoice != null)
{
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupId = (String) iGroups.next();
groups.add(site.getGroup(groupId));
}
}
}
catch (Exception e)
{
M_log.warn(this + ":post_save_assignment " + e.getMessage());
}
if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null))
{
aOldTitle = a.getTitle();
// old open time
Time oldOpenTime = a.getOpenTime();
// old due time
Time oldDueTime = a.getDueTime();
// commit the changes to AssignmentContent object
commitAssignmentContentEdit(state, ac, title, submissionType,useReviewService,allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments);
// set the Assignment Properties object
ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit();
oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
Time resubmitCloseTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit, post, resubmitCloseTime);
// the notification option
if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null)
{
aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
}
// the release grade notification option
if (state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null)
{
aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE));
}
// comment the changes to Assignment object
commitAssignmentEdit(state, post, ac, a, title, openTime, dueTime, closeTime, enableCloseDate, section, range, groups);
if (post)
{
// we need to update the submission
if (bool_change_from_non_electronic || bool_change_from_non_point || bool_change_resubmit_option)
{
List submissions = AssignmentService.getSubmissions(a);
if (submissions != null && submissions.size() >0)
{
// assignment already exist and with submissions
for (Iterator iSubmissions = submissions.iterator(); iSubmissions.hasNext();)
{
AssignmentSubmission s = (AssignmentSubmission) iSubmissions.next();
AssignmentSubmissionEdit sEdit = editSubmission(s.getReference(), "post_save_assignment", state);
if (sEdit != null)
{
ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit();
if (bool_change_from_non_electronic)
{
sEdit.setSubmitted(false);
sEdit.setTimeSubmitted(null);
}
else if (bool_change_from_non_point)
{
// set the grade to be empty for now
sEdit.setGrade("");
sEdit.setGraded(false);
sEdit.setGradeReleased(false);
sEdit.setReturned(false);
}
if (bool_change_resubmit_option)
{
String aAllowResubmitNumber = a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (aAllowResubmitNumber == null || aAllowResubmitNumber.length() == 0 || "0".equals(aAllowResubmitNumber))
{
sPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
sPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
else
{
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME));
}
}
AssignmentService.commitEdit(sEdit);
}
}
}
}
} //if
// save supplement item information
saveAssignmentSupplementItem(state, params, siteId, a);
// set default sorting
setDefaultSort(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// set the state navigation variables
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
resetAssignment(state);
// integrate with other tools only if the assignment is posted
if (post)
{
// add the due date to schedule if the schedule exists
integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit);
// the open date been announced
integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime);
// integrate with Gradebook
try
{
initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range, category);
}
catch (AssignmentHasIllegalPointsException e)
{
addAlert(state, rb.getString("addtogradebook.illegalPoints"));
M_log.warn(this + ":post_save_assignment " + e.getMessage());
}
}
}
} // if
} // if
} // post_save_assignment
/**
* supplement item related information
* @param state
* @param params
* @param siteId
* @param a
*/
private void saveAssignmentSupplementItem(SessionState state,
ParameterParser params, String siteId, AssignmentEdit a) {
// assignment supplement items
String aId = a.getId();
//model answer
if (state.getAttribute(MODELANSWER_TO_DELETE) != null && "true".equals((String) state.getAttribute(MODELANSWER_TO_DELETE)))
{
// to delete the model answer
AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId);
if (mAnswer != null)
m_assignmentSupplementItemService.removeModelAnswer(mAnswer);
}
else if (state.getAttribute(MODELANSWER_TEXT) != null)
{
// edit/add model answer
AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId);
if (mAnswer == null)
{
mAnswer = m_assignmentSupplementItemService.newModelAnswer();
m_assignmentSupplementItemService.saveModelAnswer(mAnswer);
}
mAnswer.setAssignmentId(a.getId());
mAnswer.setText((String) state.getAttribute(MODELANSWER_TEXT));
mAnswer.setShowTo(state.getAttribute(MODELANSWER_SHOWTO) != null ? Integer.parseInt((String) state.getAttribute(MODELANSWER_SHOWTO)) : 0);
mAnswer.setAttachmentSet(getAssignmentSupplementItemAttachment(state, mAnswer, MODELANSWER_ATTACHMENTS));
m_assignmentSupplementItemService.saveModelAnswer(mAnswer);
}
// note
if (state.getAttribute(NOTE_TO_DELETE) != null && "true".equals((String) state.getAttribute(NOTE_TO_DELETE)))
{
// to remove note item
AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId);
if (nNote != null)
m_assignmentSupplementItemService.removeNoteItem(nNote);
}
else if (state.getAttribute(NOTE_TEXT) != null)
{
// edit/add private note
AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId);
if (nNote == null)
nNote = m_assignmentSupplementItemService.newNoteItem();
nNote.setAssignmentId(a.getId());
nNote.setNote((String) state.getAttribute(NOTE_TEXT));
nNote.setShareWith(state.getAttribute(NOTE_SHAREWITH) != null ? Integer.parseInt((String) state.getAttribute(NOTE_SHAREWITH)) : 0);
nNote.setCreatorId(UserDirectoryService.getCurrentUser().getId());
m_assignmentSupplementItemService.saveNoteItem(nNote);
}
// all purpose
if (state.getAttribute(ALLPURPOSE_TO_DELETE) != null && "true".equals((String) state.getAttribute(ALLPURPOSE_TO_DELETE)))
{
// to remove allPurpose item
AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId);
if (nAllPurpose != null)
m_assignmentSupplementItemService.removeAllPurposeItem(nAllPurpose);
}
else if (state.getAttribute(ALLPURPOSE_TITLE) != null)
{
// edit/add private note
AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId);
if (nAllPurpose == null)
{
nAllPurpose = m_assignmentSupplementItemService.newAllPurposeItem();
m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose);
}
nAllPurpose.setAssignmentId(a.getId());
nAllPurpose.setTitle((String) state.getAttribute(ALLPURPOSE_TITLE));
nAllPurpose.setText((String) state.getAttribute(ALLPURPOSE_TEXT));
boolean allPurposeShowFrom = state.getAttribute(ALLPURPOSE_SHOW_FROM) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_FROM)).booleanValue() : false;
boolean allPurposeShowTo = state.getAttribute(ALLPURPOSE_SHOW_TO) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_TO)).booleanValue() : false;
boolean allPurposeHide = state.getAttribute(ALLPURPOSE_HIDE) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_HIDE)).booleanValue() : false;
nAllPurpose.setHide(allPurposeHide);
// save the release and retract dates
if (allPurposeShowFrom && !allPurposeHide)
{
// save release date
Time releaseTime = getTimeFromState(state, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, ALLPURPOSE_RELEASE_AMPM);
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(releaseTime.getTime());
nAllPurpose.setReleaseDate(cal.getTime());
}
else
{
nAllPurpose.setReleaseDate(null);
}
if (allPurposeShowTo && !allPurposeHide)
{
// save retract date
Time retractTime = getTimeFromState(state, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, ALLPURPOSE_RETRACT_AMPM);
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(retractTime.getTime());
nAllPurpose.setRetractDate(cal.getTime());
}
else
{
nAllPurpose.setRetractDate(null);
}
nAllPurpose.setAttachmentSet(getAssignmentSupplementItemAttachment(state, nAllPurpose, ALLPURPOSE_ATTACHMENTS));
// clean the access list first
if (state.getAttribute(ALLPURPOSE_ACCESS) != null)
{
// get the access settings
List<String> accessList = (List<String>) state.getAttribute(ALLPURPOSE_ACCESS);
m_assignmentSupplementItemService.cleanAllPurposeItemAccess(nAllPurpose);
Set<AssignmentAllPurposeItemAccess> accessSet = new HashSet<AssignmentAllPurposeItemAccess>();
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(siteId));
Set<Role> roles = realm.getRoles();
for(Iterator iRoles = roles.iterator(); iRoles.hasNext();)
{
// iterator through roles first
Role r = (Role) iRoles.next();
if (accessList.contains(r.getId()))
{
AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService.newAllPurposeItemAccess();
access.setAccess(r.getId());
access.setAssignmentAllPurposeItem(nAllPurpose);
m_assignmentSupplementItemService.saveAllPurposeItemAccess(access);
accessSet.add(access);
}
else
{
// if the role is not selected, iterate through the users with this role
Set userIds = realm.getUsersHasRole(r.getId());
for(Iterator iUserIds = userIds.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
if (accessList.contains(userId))
{
AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService.newAllPurposeItemAccess();
access.setAccess(userId);
access.setAssignmentAllPurposeItem(nAllPurpose);
m_assignmentSupplementItemService.saveAllPurposeItemAccess(access);
accessSet.add(access);
}
}
}
}
}
catch (Exception e)
{
M_log.warn(this + ":post_save_assignment " + e.toString() + "error finding authzGroup for = " + siteId);
}
nAllPurpose.setAccessSet(accessSet);
}
m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose);
}
}
private Set<AssignmentSupplementItemAttachment> getAssignmentSupplementItemAttachment(SessionState state, AssignmentSupplementItemWithAttachment mItem, String attachmentString) {
Set<AssignmentSupplementItemAttachment> sAttachments = new HashSet<AssignmentSupplementItemAttachment>();
List<String> attIdList = m_assignmentSupplementItemService.getAttachmentListForSupplementItem(mItem);
if (state.getAttribute(attachmentString) != null)
{
List currentAttachments = (List) state.getAttribute(attachmentString);
for (Iterator aIterator = currentAttachments.iterator(); aIterator.hasNext();)
{
Reference attRef = (Reference) aIterator.next();
String attRefId = attRef.getReference();
// if the attachment is not exist, add it into db
if (!attIdList.contains(attRefId))
{
AssignmentSupplementItemAttachment mAttach = m_assignmentSupplementItemService.newAttachment();
mAttach.setAssignmentSupplementItemWithAttachment(mItem);
mAttach.setAttachmentId(attRefId);
m_assignmentSupplementItemService.saveAttachment(mAttach);
sAttachments.add(mAttach);
}
}
}
return sAttachments;
}
/**
*
*/
private boolean change_from_non_electronic(SessionState state, String assignmentId, String assignmentContentId, AssignmentContentEdit ac)
{
// whether this is an editing which changes non-electronic assignment to any other type?
if (StringUtil.trimToNull(assignmentId) != null && StringUtil.trimToNull(assignmentContentId) != null)
{
// editing
if (ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION
&& ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// changing from non-electronic type
return true;
}
}
return false;
}
/**
*
*/
private boolean change_from_non_point(SessionState state, String assignmentId, String assignmentContentId, AssignmentContentEdit ac)
{
// whether this is an editing which changes non point_grade type to point grade type?
if (StringUtil.trimToNull(assignmentId) != null && StringUtil.trimToNull(assignmentContentId) != null)
{
// editing
if (ac.getTypeOfGrade() != Assignment.SCORE_GRADE_TYPE
&& ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue() == Assignment.SCORE_GRADE_TYPE)
{
// changing from non-point grade type to point grade type?
return true;
}
}
return false;
}
/**
* whether the resubmit option has been changed
* @param state
* @param a
* @return
*/
private boolean change_resubmit_option(SessionState state, Entity entity)
{
if (entity != null)
{
// editing
return propertyValueChanged(state, entity, AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) || propertyValueChanged(state, entity, AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
return false;
}
/**
* whether there is a change between state variable and object's property value
* @param state
* @param entity
* @param propertyName
* @return
*/
private boolean propertyValueChanged(SessionState state, Entity entity, String propertyName) {
String o_property_value = entity.getProperties().getProperty(propertyName);
String n_property_value = state.getAttribute(propertyName) != null? (String) state.getAttribute(propertyName):null;
if (o_property_value == null && n_property_value != null
|| o_property_value != null && n_property_value == null
|| o_property_value != null && n_property_value != null && !o_property_value.equals(n_property_value))
{
// there is a change
return true;
}
return false;
}
/**
* default sorting
*/
private void setDefaultSort(SessionState state) {
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
}
/**
* Add submission objects if necessary for non-electronic type of assignment
* @param state
* @param a
*/
private void addRemoveSubmissionsForNonElectronicAssignment(SessionState state, List submissions, HashSet<String> addSubmissionForUsers, HashSet<String> removeSubmissionForUsers, Assignment a)
{
// create submission object for those user who doesn't have one yet
for (Iterator iUserIds = addSubmissionForUsers.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
// only include those users that can submit to this assignment
if (u != null)
{
// construct fake submissions for grading purpose
AssignmentSubmissionEdit submission = AssignmentService.addSubmission(a.getContext(), a.getId(), userId);
submission.setTimeSubmitted(TimeService.newTime());
submission.setSubmitted(true);
submission.setAssignment(a);
AssignmentService.commitEdit(submission);
}
}
catch (Exception e)
{
M_log.warn(this + ":addRemoveSubmissionsForNonElectronicAssignment " + e.toString() + "error adding submission for userId = " + userId);
}
}
// remove submission object for those who no longer in the site
for (Iterator iUserIds = removeSubmissionForUsers.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
String submissionRef = null;
// TODO: we don't have an efficient way to retrieve specific user's submission now, so until then, we still need to iterate the whole submission list
for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext() && submissionRef == null;)
{
AssignmentSubmission submission = (AssignmentSubmission) iSubmissions.next();
List submitterIds = submission.getSubmitterIds();
if (submitterIds != null && submitterIds.size() > 0 && userId.equals((String) submitterIds.get(0)))
{
submissionRef = submission.getReference();
}
}
if (submissionRef != null)
{
AssignmentSubmissionEdit submissionEdit = editSubmission(submissionRef, "addRemoveSubmissionsForNonElectronicAssignment", state);
if (submissionEdit != null)
{
try
{
AssignmentService.removeSubmission(submissionEdit);
}
catch (PermissionException e)
{
addAlert(state, rb.getFormattedMessage("youarenot_removeSubmission", new Object[]{submissionEdit.getReference()}));
M_log.warn(this + ":deleteAssignmentObjects " + e.getMessage() + " " + submissionEdit.getReference());
}
}
}
}
}
private void initIntegrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range, long category) {
GradebookExternalAssessmentService gExternal = (GradebookExternalAssessmentService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService");
String context = (String) state.getAttribute(STATE_CONTEXT_STRING);
boolean gradebookExists = isGradebookDefined();
// only if the gradebook is defined
if (gradebookExists)
{
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
String aReference = a.getReference();
String addUpdateRemoveAssignment = "remove";
if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// if integrate with Gradebook
if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && ("groups".equals(range)))
{
// if grouped assignment is not allowed to add into Gradebook
addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB"));
String ref = a.getReference();
AssignmentEdit aEdit = editAssignment(a.getReference(), "initINtegrateWithGradebook", state, false);
if (aEdit != null)
{
aEdit.getPropertiesEdit().removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
AssignmentService.commitEdit(aEdit);
}
integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null, category);
}
else
{
if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD))
{
addUpdateRemoveAssignment = AssignmentService.GRADEBOOK_INTEGRATION_ADD;
}
else if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE))
{
addUpdateRemoveAssignment = "update";
}
if (!"remove".equals(addUpdateRemoveAssignment) && gradeType == 3)
{
try
{
integrateGradebook(state, aReference, associateGradebookAssignment, addUpdateRemoveAssignment, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, null, category);
// add all existing grades, if any, into Gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update", category);
// if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook
if (StringUtil.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment))
{
// if the old assoicated assignment entry in GB is an external one, but doesn't have anything assoicated with it in Assignment tool, remove it
removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,gExternal, gradebookUid);
}
}
catch (NumberFormatException nE)
{
alertInvalidPoint(state, gradePoints);
M_log.warn(this + ":initIntegrateWithGradebook " + nE.getMessage());
}
}
else
{
integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null, category);
}
}
}
else
{
// need to remove the associated gradebook entry if 1) it is external and 2) no other assignment are associated with it
removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,gExternal, gradebookUid);
}
}
}
private void removeNonAssociatedExternalGradebookEntry(String context, String assignmentReference, String associateGradebookAssignment, GradebookExternalAssessmentService gExternal, String gradebookUid) {
boolean isExternalAssignmentDefined=gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment);
if (isExternalAssignmentDefined)
{
// iterate through all assignments currently in the site, see if any is associated with this GB entry
Iterator i = AssignmentService.getAssignmentsForContext(context);
boolean found = false;
while (!found && i.hasNext())
{
Assignment aI = (Assignment) i.next();
String gbEntry = aI.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (aI.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED) == null && gbEntry != null && gbEntry.equals(associateGradebookAssignment) && !aI.getReference().equals(assignmentReference))
{
found = true;
}
}
// so if none of the assignment in this site is associated with the entry, remove the entry
if (!found)
{
gExternal.removeExternalAssessment(gradebookUid, associateGradebookAssignment);
}
}
}
private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime)
{
if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString()))
{
AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL);
if (channel != null)
{
// whether the assignment's title or open date has been updated
boolean updatedTitle = false;
boolean updatedOpenDate = false;
String openDateAnnounced = StringUtil.trimToNull(a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED));
String openDateAnnouncementId = StringUtil.trimToNull(a.getPropertiesEdit().getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID));
if (openDateAnnounced != null && openDateAnnouncementId != null)
{
try
{
AnnouncementMessage message = channel.getAnnouncementMessage(openDateAnnouncementId);
if (!message.getAnnouncementHeader().getSubject().contains(title))/*whether title has been changed*/
{
updatedTitle = true;
}
if (!message.getBody().contains(openTime.toStringLocalFull())) /*whether open date has been changed*/
{
updatedOpenDate = true;
}
}
catch (IdUnusedException e)
{
M_log.warn(this + ":integrateWithAnnouncement " + e.getMessage());
}
catch (PermissionException e)
{
M_log.warn(this + ":integrateWithAnnouncement " + e.getMessage());
}
}
// need to create announcement message if assignment is added or assignment has been updated
if (openDateAnnounced == null || updatedTitle || updatedOpenDate)
{
try
{
AnnouncementMessageEdit message = channel.addAnnouncementMessage();
if (message != null)
{
AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit();
header.setDraft(/* draft */false);
header.replaceAttachments(/* attachment */EntityManager.newReferenceList());
if (openDateAnnounced == null)
{
// making new announcement
header.setSubject(/* subject */rb.getFormattedMessage("assig6", new Object[]{title}));
}
else
{
// updated title
header.setSubject(/* subject */rb.getFormattedMessage("assig5", new Object[]{title}));
}
if (updatedOpenDate)
{
// revised assignment open date
message.setBody(/* body */rb.getFormattedMessage("newope", new Object[]{FormattedText.convertPlaintextToFormattedText(title), openTime.toStringLocalFull()}));
}
else
{
// assignment open date
message.setBody(/* body */rb.getFormattedMessage("opedat", new Object[]{FormattedText.convertPlaintextToFormattedText(title), openTime.toStringLocalFull()}));
}
// group information
if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED))
{
try
{
// get the group ids selected
Collection groupRefs = a.getGroups();
// make a collection of Group objects
Collection groups = new Vector();
//make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();)
{
String groupRef = (String) iGroupRefs.next();
groups.add(site.getGroup(groupRef));
}
// set access
header.setGroupAccess(groups);
}
catch (Exception exception)
{
// log
M_log.warn(this + ":integrateWithAnnouncement " + exception.getMessage());
}
}
else
{
// site announcement
header.clearGroupAccess();
}
channel.commitMessage(message, m_notificationService.NOTI_NONE);
}
// commit related properties into Assignment object
AssignmentEdit aEdit = editAssignment(a.getReference(), "integrateWithAnnouncement", state, false);
if (aEdit != null)
{
aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString());
if (message != null)
{
aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId());
}
AssignmentService.commitEdit(aEdit);
}
}
catch (PermissionException ee)
{
M_log.warn(this + ":IntegrateWithAnnouncement " + rb.getString("cannotmak"));
}
}
}
} // if
}
private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit)
{
Calendar c = (Calendar) state.getAttribute(CALENDAR);
if (c != null)
{
String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
String oldEventId = aPropertiesEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
CalendarEvent e = null;
if (dueDateScheduled != null || oldEventId != null)
{
// find the old event
boolean found = false;
if (oldEventId != null)
{
try
{
e = c.getEvent(oldEventId);
found = true;
}
catch (IdUnusedException ee)
{
M_log.warn(this + ":integrateWithCalender The old event has been deleted: event id=" + oldEventId + ". ");
}
catch (PermissionException ee)
{
M_log.warn(this + ":integrateWithCalender You do not have the permission to view the schedule event id= "
+ oldEventId + ".");
}
}
else
{
TimeBreakdown b = oldDueTime.breakdownLocal();
// TODO: check- this was new Time(year...), not local! -ggolden
Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0);
Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999);
try
{
Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null)
.iterator();
while ((!found) && (events.hasNext()))
{
e = (CalendarEvent) events.next();
if (((String) e.getDisplayName()).indexOf(rb.getString("gen.assig") + " " + title) != -1)
{
found = true;
}
}
}
catch (PermissionException ignore)
{
// ignore PermissionException
}
}
if (found)
{
// remove the founded old event
try
{
c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
}
catch (PermissionException ee)
{
M_log.warn(this + ":integrateWithCalender " + rb.getFormattedMessage("cannotrem", new Object[]{title}));
}
catch (InUseException ee)
{
M_log.warn(this + ":integrateWithCalender " + rb.getString("somelsis_calendar"));
}
catch (IdUnusedException ee)
{
M_log.warn(this + ":integrateWithCalender " + rb.getFormattedMessage("cannotfin6", new Object[]{e.getId()}));
}
}
}
if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString()))
{
// commit related properties into Assignment object
AssignmentEdit aEdit = editAssignment(a.getReference(), "integrateWithCalendar", state, false);
if (aEdit != null)
{
try
{
e = null;
CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE;
Collection eGroups = new Vector();
if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED))
{
eAccess = CalendarEvent.EventAccess.GROUPED;
Collection groupRefs = aEdit.getGroups();
// make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();)
{
String groupRef = (String) iGroupRefs.next();
eGroups.add(site.getGroup(groupRef));
}
}
e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000),
/* title */rb.getString("gen.due") + " " + title,
/* description */rb.getFormattedMessage("assign_due_event_desc", new Object[]{title, dueTime.toStringLocalFull()}),
/* type */rb.getString("deadl"),
/* location */"",
/* access */ eAccess,
/* groups */ eGroups,
/* attachments */EntityManager.newReferenceList());
aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString());
if (e != null)
{
aEdit.getProperties().addProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID, e.getId());
// edit the calendar ojbject and add an assignment id field
CalendarEventEdit edit = c.getEditEvent(e.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_ADD_CALENDAR);
edit.setField(AssignmentConstants.NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID, a.getId());
c.commitEvent(edit);
}
// TODO do we care if the event is null?
}
catch (IdUnusedException ee)
{
M_log.warn(this + ":integrateWithCalender " + ee.getMessage());
}
catch (PermissionException ee)
{
M_log.warn(this + ":integrateWithCalender " + rb.getString("cannotfin1"));
}
catch (Exception ee)
{
M_log.warn(this + ":integrateWithCalender " + ee.getMessage());
}
// try-catch
AssignmentService.commitEdit(aEdit);
}
} // if
}
}
private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups)
{
a.setTitle(title);
a.setContent(ac);
a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING));
a.setSection(s);
a.setOpenTime(openTime);
a.setDueTime(dueTime);
// set the drop dead date as the due date
a.setDropDeadTime(dueTime);
if (enableCloseDate)
{
a.setCloseTime(closeTime);
}
else
{
// if editing an old assignment with close date
if (a.getCloseTime() != null)
{
a.setCloseTime(null);
}
}
// post the assignment
a.setDraft(!post);
try
{
if ("site".equals(range))
{
a.setAccess(Assignment.AssignmentAccess.SITE);
a.clearGroupAccess();
}
else if ("groups".equals(range))
{
a.setGroupAccess(groups);
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot1"));
M_log.warn(this + ":commitAssignmentEdit " + rb.getString("youarenot1") + e.getMessage());
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// commit assignment first
AssignmentService.commitEdit(a);
}
}
private void editAssignmentProperties(AssignmentEdit a, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit, boolean post, Time closeTime)
{
if (aPropertiesEdit.getProperty("newAssignment") != null)
{
if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString()))
{
// not a newly created assignment, been added.
aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString());
}
}
else
{
// for newly created assignment
aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString());
}
if (checkAddDueTime != null)
{
aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime);
}
else
{
aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
}
aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce);
aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook);
aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment);
if (post && addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD))
{
// if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then
aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE);
aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, a.getReference());
}
// allow resubmit number and default assignment resubmit closeTime (dueTime)
if (allowResubmitNumber != null && closeTime != null)
{
aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber);
aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
}
else if (allowResubmitNumber == null || allowResubmitNumber.length() == 0 || "0".equals(allowResubmitNumber))
{
aPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
aPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
}
private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String title, int submissionType,boolean useReviewService, boolean allowStudentViewReport, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments)
{
ac.setTitle(title);
ac.setInstructions(description);
ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge));
ac.setTypeOfSubmission(submissionType);
ac.setAllowReviewService(useReviewService);
ac.setAllowStudentViewReport(allowStudentViewReport);
ac.setTypeOfGrade(gradeType);
if (gradeType == 3)
{
try
{
ac.setMaxGradePoint(Integer.parseInt(gradePoints));
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, gradePoints);
M_log.warn(this + ":commitAssignmentContentEdit " + e.getMessage());
}
}
ac.setGroupProject(true);
ac.setIndividuallyGraded(false);
if (submissionType != 1)
{
ac.setAllowAttachments(true);
}
else
{
ac.setAllowAttachments(false);
}
// clear attachments
ac.clearAttachments();
if (attachments != null)
{
// add each attachment
Iterator it = EntityManager.newReferenceList(attachments).iterator();
while (it.hasNext())
{
Reference r = (Reference) it.next();
ac.addAttachment(r);
}
}
state.setAttribute(ATTACHMENTS_MODIFIED, Boolean.valueOf(false));
// commit the changes
AssignmentService.commitEdit(ac);
}
/**
* reorderAssignments
*/
private void reorderAssignments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List assignments = prepPage(state);
Iterator it = assignments.iterator();
// temporarily allow the user to read and write from assignments (asn.revise permission)
enableSecurityAdvisor();
while (it.hasNext()) // reads and writes the parameter for default ordering
{
Assignment a = (Assignment) it.next();
String assignmentid = a.getId();
String assignmentposition = params.getString("position_" + assignmentid);
AssignmentEdit ae = editAssignment(assignmentid, "reorderAssignments", state, true);
if (ae != null)
{
ae.setPosition_order(Long.valueOf(assignmentposition).intValue());
AssignmentService.commitEdit(ae);
}
}
// clear the permission
disableSecurityAdvisor();
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
} // reorderAssignments
private AssignmentContentEdit editAssignmentContent(String assignmentContentId, String callingFunctionName, SessionState state, boolean allowAdd)
{
AssignmentContentEdit ac = null;
if (assignmentContentId.length() == 0 && allowAdd)
{
// new assignment
try
{
ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot_addAssignmentContent"));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + (String) state.getAttribute(STATE_CONTEXT_STRING));
}
}
else
{
try
{
// edit assignment
ac = AssignmentService.editAssignmentContent(assignmentContentId);
}
catch (InUseException e)
{
addAlert(state, rb.getFormattedMessage("somelsis_assignmentContent", new Object[]{assignmentContentId}));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage());
}
catch (IdUnusedException e)
{
addAlert(state, rb.getFormattedMessage("cannotfin_assignmentContent", new Object[]{assignmentContentId}));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage());
}
catch (PermissionException e)
{
addAlert(state, rb.getFormattedMessage("youarenot_viewAssignmentContent", new Object[]{assignmentContentId}));
M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage());
}
}
return ac;
}
/**
* construct time object based on various state variables
* @param state
* @param monthString
* @param dayString
* @param yearString
* @param hourString
* @param minString
* @param ampmString
* @return
*/
private Time getTimeFromState(SessionState state, String monthString, String dayString, String yearString, String hourString, String minString, String ampmString)
{
if (state.getAttribute(monthString) != null ||
state.getAttribute(dayString) != null ||
state.getAttribute(yearString) != null ||
state.getAttribute(hourString) != null ||
state.getAttribute(minString) != null ||
state.getAttribute(ampmString) != null)
{
int month = ((Integer) state.getAttribute(monthString)).intValue();
int day = ((Integer) state.getAttribute(dayString)).intValue();
int year = ((Integer) state.getAttribute(yearString)).intValue();
int hour = ((Integer) state.getAttribute(hourString)).intValue();
int min = ((Integer) state.getAttribute(minString)).intValue();
String ampm = (String) state.getAttribute(ampmString);
if (("PM".equals(ampm)) && (hour != 12))
{
hour = hour + 12;
}
if ((hour == 12) && ("AM".equals(ampm)))
{
hour = 0;
}
return TimeService.newTimeLocal(year, month, day, hour, min, 0, 0);
}
else
{
return null;
}
}
/**
* Action is to post new assignment
*/
public void doSave_assignment(RunData data)
{
post_save_assignment(data, "save");
} // doSave_assignment
/**
* Action is to reorder assignments
*/
public void doReorder_assignment(RunData data)
{
reorderAssignments(data);
} // doReorder_assignments
/**
* Action is to preview the selected assignment
*/
public void doPreview_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
setNewAssignmentParameters(data, true);
String assignmentId = data.getParameters().getString("assignmentId");
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId);
String assignmentContentId = data.getParameters().getString("assignmentContentId");
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId);
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false));
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(true));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT);
}
} // doPreview_assignment
/**
* Action is to view the selected assignment
*/
public void doView_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// show the assignment portion
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(false));
// show the student view portion
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(true));
String assignmentId = params.getString("assignmentId");
state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId);
Assignment a = getAssignment(assignmentId, "doView_assignment", state);
// get resubmission option into state
assignment_resubmission_option_into_state(a, null, state);
// assignment read event
m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, assignmentId, false));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT);
}
} // doView_Assignment
/**
* Action is for student to view one assignment content
*/
public void doView_assignment_as_student(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = params.getString("assignmentId");
state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT);
}
} // doView_assignment_as_student
/**
* Action is to show the edit assignment screen
*/
public void doEdit_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = StringUtil.trimToNull(params.getString("assignmentId"));
if (AssignmentService.allowUpdateAssignment(assignmentId))
{
// whether the user can modify the assignment
state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId);
Assignment a = getAssignment(assignmentId, "doEdit_assignment", state);
if (a != null)
{
// for the non_electronice assignment, submissions are auto-generated by the time that assignment is created;
// don't need to go through the following checkings.
if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
if (submissions.hasNext())
{
// any submitted?
boolean anySubmitted = false;
for (;submissions.hasNext() && !anySubmitted;)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getSubmitted() && s.getTimeSubmitted() != null)
{
anySubmitted = true;
}
}
// any draft submission
boolean anyDraft = false;
for (;submissions.hasNext() && !anyDraft;)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (!s.getSubmitted())
{
anyDraft = true;
}
}
if (anySubmitted)
{
// if there is any submitted submission to this assignment, show alert
addAlert(state, rb.getString("gen.assig") + " " + a.getTitle() + " " + rb.getString("hassum"));
}
if (anyDraft)
{
// otherwise, show alert about someone has started working on the assignment, not necessarily submitted
addAlert(state, rb.getString("hasDraftSum"));
}
}
}
// SECTION MOD
state.setAttribute(STATE_SECTION_STRING, a.getSection());
// put the names and values into vm file
state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle());
state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order());
putTimePropertiesInState(state, a.getOpenTime(), NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM);
// generate alert when editing an assignment past open date
if (a.getOpenTime().before(TimeService.newTime()))
{
addAlert(state, rb.getString("youarenot20"));
}
putTimePropertiesInState(state, a.getDueTime(), NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM);
// generate alert when editing an assignment past due date
if (a.getDueTime().before(TimeService.newTime()))
{
addAlert(state, rb.getString("youarenot17"));
}
if (a.getCloseTime() != null)
{
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true));
putTimePropertiesInState(state, a.getCloseTime(), NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM);
}
else
{
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(false));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR));
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN));
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, state.getAttribute(NEW_ASSIGNMENT_DUEAMPM));
}
state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection());
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(a.getContent().getTypeOfSubmission()));
state.setAttribute(NEW_ASSIGNMENT_CATEGORY, getAssignmentCategoryAsInt(a));
int typeOfGrade = a.getContent().getTypeOfGrade();
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(typeOfGrade));
if (typeOfGrade == 3)
{
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay());
}
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions());
ResourceProperties properties = a.getProperties();
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty(
ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty(
ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge()));
state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
state.setAttribute(ATTACHMENTS, a.getContent().getAttachments());
// submission notification option
if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null)
{
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
}
// release grade notification option
if (properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null)
{
state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE));
}
// group setting
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
state.setAttribute(NEW_ASSIGNMENT_RANGE, "site");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups");
}
// put the resubmission option into state
assignment_resubmission_option_into_state(a, null, state);
// set whether we use the review service or not
state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, Boolean.valueOf(a.getContent().getAllowReviewService()).toString());
//set whether students can view the review service results
state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, Boolean.valueOf(a.getContent().getAllowStudentViewReport()).toString());
state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups());
// get all supplement item info into state
setAssignmentSupplementItemInState(state, a);
}
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot6"));
}
} // doEdit_Assignment
/**
* put all assignment supplement item info into state
* @param state
* @param a
*/
private void setAssignmentSupplementItemInState(SessionState state, Assignment a) {
String assignmentId = a.getId();
// model answer
AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(assignmentId);
if (mAnswer != null)
{
if (state.getAttribute(MODELANSWER_TEXT) == null)
{
state.setAttribute(MODELANSWER_TEXT, mAnswer.getText());
}
if (state.getAttribute(MODELANSWER_SHOWTO) == null)
{
state.setAttribute(MODELANSWER_SHOWTO, String.valueOf(mAnswer.getShowTo()));
}
if (state.getAttribute(MODELANSWER) == null)
{
state.setAttribute(MODELANSWER, Boolean.TRUE);
}
}
// get attachments for model answer object
putSupplementItemAttachmentInfoIntoState(state, mAnswer, MODELANSWER_ATTACHMENTS);
// private notes
AssignmentNoteItem mNote = m_assignmentSupplementItemService.getNoteItem(assignmentId);
if (mNote != null)
{
if (state.getAttribute(NOTE) == null)
{
state.setAttribute(NOTE, Boolean.TRUE);
}
if (state.getAttribute(NOTE_TEXT) == null)
{
state.setAttribute(NOTE_TEXT, mNote.getNote());
}
if (state.getAttribute(NOTE_SHAREWITH) == null)
{
state.setAttribute(NOTE_SHAREWITH, String.valueOf(mNote.getShareWith()));
}
}
// all purpose item
AssignmentAllPurposeItem aItem = m_assignmentSupplementItemService.getAllPurposeItem(assignmentId);
if (aItem != null)
{
if (state.getAttribute(ALLPURPOSE) == null)
{
state.setAttribute(ALLPURPOSE, Boolean.TRUE);
}
if (state.getAttribute(ALLPURPOSE_TITLE) == null)
{
state.setAttribute(ALLPURPOSE_TITLE, aItem.getTitle());
}
if (state.getAttribute(ALLPURPOSE_TEXT) == null)
{
state.setAttribute(ALLPURPOSE_TEXT, aItem.getText());
}
if (state.getAttribute(ALLPURPOSE_HIDE) == null)
{
state.setAttribute(ALLPURPOSE_HIDE, Boolean.valueOf(aItem.getHide()));
}
if (state.getAttribute(ALLPURPOSE_SHOW_FROM) == null)
{
state.setAttribute(ALLPURPOSE_SHOW_FROM, aItem.getReleaseDate() != null);
}
if (state.getAttribute(ALLPURPOSE_SHOW_TO) == null)
{
state.setAttribute(ALLPURPOSE_SHOW_TO, aItem.getRetractDate() != null);
}
if (state.getAttribute(ALLPURPOSE_ACCESS) == null)
{
Set<AssignmentAllPurposeItemAccess> aSet = aItem.getAccessSet();
List<String> aList = new Vector<String>();
for(Iterator<AssignmentAllPurposeItemAccess> aIterator = aSet.iterator(); aIterator.hasNext();)
{
AssignmentAllPurposeItemAccess access = aIterator.next();
aList.add(access.getAccess());
}
state.setAttribute(ALLPURPOSE_ACCESS, aList);
}
// get attachments for model answer object
putSupplementItemAttachmentInfoIntoState(state, aItem, ALLPURPOSE_ATTACHMENTS);
}
// get the AllPurposeItem and AllPurposeReleaseTime/AllPurposeRetractTime
//default to assignment open time
Time releaseTime = a.getOpenTime();
// default to assignment close time
Time retractTime = a.getCloseTime();
if (aItem != null)
{
Date releaseDate = aItem.getReleaseDate();
if (releaseDate != null)
{
// overwrite if there is a release date
releaseTime = TimeService.newTime(releaseDate.getTime());
}
Date retractDate = aItem.getRetractDate();
if (retractDate != null)
{
// overwriteif there is a retract date
retractTime = TimeService.newTime(retractDate.getTime());
}
}
putTimePropertiesInState(state, releaseTime, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, ALLPURPOSE_RELEASE_AMPM);
putTimePropertiesInState(state, retractTime, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, ALLPURPOSE_RETRACT_AMPM);
}
/**
* Action is to show the delete assigment confirmation screen
*/
public void doDelete_confirm_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String[] assignmentIds = params.getStrings("selectedAssignments");
if (assignmentIds != null)
{
Vector ids = new Vector();
for (int i = 0; i < assignmentIds.length; i++)
{
String id = (String) assignmentIds[i];
if (!AssignmentService.allowRemoveAssignment(id))
{
addAlert(state, rb.getFormattedMessage("youarenot_removeAssignment", new Object[]{id}));
}
ids.add(id);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// can remove all the selected assignments
state.setAttribute(DELETE_ASSIGNMENT_IDS, ids);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT);
}
}
else
{
addAlert(state, rb.getString("youmust6"));
}
} // doDelete_confirm_Assignment
/**
* Action is to delete the confirmed assignments
*/
public void doDelete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the delete assignment ids
Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < ids.size(); i++)
{
String assignmentId = (String) ids.get(i);
AssignmentEdit aEdit = editAssignment(assignmentId, "doDelete_assignment", state, false);
if (aEdit != null)
{
ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit();
String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
String title = aEdit.getTitle();
// remove related event if there is one
removeCalendarEvent(state, aEdit, pEdit, title);
// remove related announcement if there is one
removeAnnouncement(state, pEdit);
// we use to check "assignment.delete.cascade.submission" setting. But the implementation now is always remove submission objects when the assignment is removed.
// delete assignment and its submissions altogether
deleteAssignmentObjects(state, aEdit, true);
// remove from Gradebook
integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null, -1);
}
} // for
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
// reset paging information after the assignment been deleted
resetPaging(state);
}
} // doDelete_Assignment
/**
* private function to remove assignment related announcement
* @param state
* @param pEdit
*/
private void removeAnnouncement(SessionState state,
ResourcePropertiesEdit pEdit) {
AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL);
if (channel != null)
{
String openDateAnnounced = StringUtil.trimToNull(pEdit.getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED));
String openDateAnnouncementId = StringUtil.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(this + ":removeAnnouncement " + e.getMessage());
}
}
}
}
/**
* private method to remove assignment and related objects
* @param state
* @param aEdit
* @param removeSubmissions Whether or not to remove the submission objects
*/
private void deleteAssignmentObjects(SessionState state, AssignmentEdit aEdit, boolean removeSubmissions) {
if (removeSubmissions)
{
// if this is non-electronic submission, remove all the submissions
List submissions = AssignmentService.getSubmissions(aEdit);
if (submissions != null)
{
for (Iterator sIterator=submissions.iterator(); sIterator.hasNext();)
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
AssignmentSubmissionEdit sEdit = editSubmission((s.getReference()), "deleteAssignmentObjects", state);
try
{
AssignmentService.removeSubmission(sEdit);
}
catch (Exception eee)
{
addAlert(state, rb.getFormattedMessage("youarenot_removeSubmission", new Object[]{s.getReference()}));
M_log.warn(this + ":deleteAssignmentObjects " + eee.getMessage() + " " + s.getReference());
}
}
}
}
AssignmentContent aContent = aEdit.getContent();
if (aContent != null)
{
try
{
// remove the assignment content
AssignmentContentEdit acEdit = editAssignmentContent(aContent.getId(), "deleteAssignmentObjects", state, false);
if (acEdit != null)
AssignmentService.removeAssignmentContent(acEdit);
}
catch (Exception ee)
{
addAlert(state, rb.getString("youarenot11_c") + " " + aEdit.getContentReference() + ". ");
M_log.warn(this + ":deleteAssignmentObjects " + ee.getMessage());
}
}
try
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
if (taggingManager.isTaggable()) {
for (TaggingProvider provider : taggingManager
.getProviders()) {
provider.removeTags(assignmentActivityProducer
.getActivity(aEdit));
}
}
AssignmentService.removeAssignment(aEdit);
}
catch (PermissionException ee)
{
addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". ");
M_log.warn(this + ":deleteAssignmentObjects " + ee.getMessage());
}
}
private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title)
{
String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString()))
{
// remove the associated calendar event
Calendar c = (Calendar) state.getAttribute(CALENDAR);
if (c != null)
{
// already has calendar object
// get the old event
CalendarEvent e = null;
boolean found = false;
String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
if (oldEventId != null)
{
try
{
e = c.getEvent(oldEventId);
found = true;
}
catch (IdUnusedException ee)
{
// no action needed for this condition
M_log.warn(this + ":removeCalendarEvent " + ee.getMessage());
}
catch (PermissionException ee)
{
M_log.warn(this + ":removeCalendarEvent " + ee.getMessage());
}
}
else
{
TimeBreakdown b = aEdit.getDueTime().breakdownLocal();
// TODO: check- this was new Time(year...), not local! -ggolden
Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0);
Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999);
try
{
Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator();
while ((!found) && (events.hasNext()))
{
e = (CalendarEvent) events.next();
if (((String) e.getDisplayName()).indexOf(rb.getString("gen.assig") + " " + title) != -1)
{
found = true;
}
}
}
catch (PermissionException pException)
{
addAlert(state, rb.getFormattedMessage("cannot_getEvents", new Object[]{c.getReference()}));
}
}
// remove the founded old event
if (found)
{
// found the old event delete it
try
{
c.removeEvent(c.getEditEvent(e.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(this + ":removeCalendarEvent " + rb.getFormattedMessage("cannotrem", new Object[]{title}));
}
catch (InUseException ee)
{
M_log.warn(this + ":removeCalendarEvent " + rb.getString("somelsis_calendar"));
}
catch (IdUnusedException ee)
{
M_log.warn(this + ":removeCalendarEvent " + rb.getFormattedMessage("cannotfin6", new Object[]{e.getId()}));
}
}
}
}
}
/**
* Action is to delete the assignment and also the related AssignmentSubmission
*/
public void doDeep_delete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the delete assignment ids
Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < ids.size(); i++)
{
String currentId = (String) ids.get(i);
AssignmentEdit a = editAssignment(currentId, "doDeep_delete_assignment", state, false);
if (a != null)
{
try
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
if (taggingManager.isTaggable()) {
for (TaggingProvider provider : taggingManager
.getProviders()) {
provider.removeTags(assignmentActivityProducer
.getActivity(a));
}
}
AssignmentService.removeAssignment(a);
}
catch (PermissionException e)
{
addAlert(state, rb.getFormattedMessage("youarenot_editAssignment", new Object[]{a.getTitle()}));
M_log.warn(this + ":doDeep_delete_assignment " + e.getMessage());
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
} // doDeep_delete_Assignment
/**
* Action is to show the duplicate assignment screen
*/
public void doDuplicate_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the view, so start with first page again.
resetPaging(state);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
ParameterParser params = data.getParameters();
String assignmentId = StringUtil.trimToNull(params.getString("assignmentId"));
if (assignmentId != null)
{
try
{
AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId);
// clean the duplicate's property
ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit();
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED);
aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID);
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
aPropertiesEdit.removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
AssignmentService.commitEdit(aEdit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot5"));
M_log.warn(this + ":doDuplicate_assignment " + e.getMessage());
}
catch (IdInvalidException e)
{
addAlert(state, rb.getFormattedMessage("theassiid_isnotval", new Object[]{assignmentId}));
M_log.warn(this + ":doDuplicate_assignment " + e.getMessage());
}
catch (IdUnusedException e)
{
addAlert(state, rb.getFormattedMessage("theassiid_hasnotbee", new Object[]{assignmentId}));
M_log.warn(this + ":doDuplicate_assignment " + e.getMessage());
}
catch (Exception e)
{
M_log.warn(this + ":doDuplicate_assignment " + e.getMessage());
}
}
} // doDuplicate_Assignment
/**
* Action is to show the grade submission screen
*/
public void doGrade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the submission context
resetViewSubmission(state);
ParameterParser params = data.getParameters();
String assignmentId = params.getString("assignmentId");
String submissionId = params.getString("submissionId");
// put submission information into state
putSubmissionInfoIntoState(state, assignmentId, submissionId);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false));
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
// assignment read event
m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submissionId, false));
}
} // doGrade_submission
/**
* put all the submission information into state variables
* @param state
* @param assignmentId
* @param submissionId
*/
private void putSubmissionInfoIntoState(SessionState state, String assignmentId, String submissionId)
{
// reset grading submission variables
resetGradeSubmission(state);
// reset the grade assignment id and submission id
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, assignmentId);
state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId);
// allow resubmit number
String allowResubmitNumber = "0";
Assignment a = getAssignment(assignmentId, "putSubmissionInfoIntoState", state);
if (a != null)
{
AssignmentSubmission s = getSubmission(submissionId, "putSubmissionInfoIntoState", state);
if (s != null)
{
if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0))
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText());
}
else
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText());
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment());
List v = EntityManager.newReferenceList();
Iterator attachments = s.getFeedbackAttachments().iterator();
while (attachments.hasNext())
{
v.add(attachments.next());
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT,v);
state.setAttribute(ATTACHMENTS, v);
state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade());
// put the resubmission info into state
assignment_resubmission_option_into_state(a, s, state);
}
}
}
/**
* Action is to release all the grades of the submission
*/
public void doRelease_grades(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = params.getString("assignmentId");
// get the assignment
Assignment a = getAssignment(assignmentId, "doRelease_grades", state);
if (a != null)
{
String aReference = a.getReference();
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
while (submissions.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getGraded())
{
String sRef = s.getReference();
AssignmentSubmissionEdit sEdit = editSubmission(sRef, "doRelease_grades", state);
if (sEdit != null)
{
String grade = s.getGrade();
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES))
.booleanValue() : false;
if (withGrade)
{
// for the assignment tool with grade option, a valide grade is needed
if (grade != null && !"".equals(grade))
{
sEdit.setGradeReleased(true);
}
}
else
{
// for the assignment tool without grade option, no grade is needed
sEdit.setGradeReleased(true);
}
// also set the return status
sEdit.setReturned(true);
sEdit.setTimeReturned(TimeService.newTime());
sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue());
AssignmentService.commitEdit(sEdit);
}
}
} // while
// add grades into Gradebook
String integrateWithGradebook = a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// integrate with Gradebook
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update", -1);
}
}
} // doRelease_grades
/**
* Action is to show the assignment in grading page
*/
public void doExpand_grade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true));
} // doExpand_grade_assignment
/**
* Action is to hide the assignment in grading page
*/
public void doCollapse_grade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false));
} // doCollapse_grade_assignment
/**
* Action is to show the submissions in grading page
*/
public void doExpand_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(true));
} // doExpand_grade_submission
/**
* Action is to hide the submissions in grading page
*/
public void doCollapse_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(false));
} // doCollapse_grade_submission
/**
* Action is to show the grade assignment
*/
public void doGrade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// clean state attribute
state.removeAttribute(USER_SUBMISSIONS);
state.removeAttribute(SHOW_ALLOW_RESUBMISSION);
String assignmentId = params.getString("assignmentId");
state.setAttribute(EXPORT_ASSIGNMENT_REF, assignmentId);
Assignment a = getAssignment(assignmentId, "doGrade_assignment", state);
if (a != null)
{
state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false));
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(true));
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
// initialize the resubmission params
assignment_resubmission_option_into_state(a, null, state);
// we are changing the view, so start with first page again.
resetPaging(state);
}
} // doGrade_assignment
/**
* Action is to show the View Students assignment screen
*/
public void doView_students_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT);
} // doView_students_Assignment
/**
* Action is to show the student submissions
*/
public void doShow_student_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
ParameterParser params = data.getParameters();
String id = params.getString("studentId");
// add the student id into the table
t.add(id);
state.setAttribute(STUDENT_LIST_SHOW_TABLE, t);
} // doShow_student_submission
/**
* Action is to hide the student submissions
*/
public void doHide_student_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
ParameterParser params = data.getParameters();
String id = params.getString("studentId");
// remove the student id from the table
t.remove(id);
state.setAttribute(STUDENT_LIST_SHOW_TABLE, t);
} // doHide_student_submission
/**
* Action is to show the graded assignment submission
*/
public void doView_grade(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId"));
// whether the user can access the Submission object
if (getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID), "doView_grade", state ) != null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE);
}
} // doView_grade
/**
* Action is to show the graded assignment submission while keeping specific information private
*/
public void doView_grade_private(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId"));
// whether the user can access the Submission object
if (getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID), "doView_grade_private", state ) != null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE_PRIVATE);
}
} // doView_grade_private
/**
* Action is to show the student submissions
*/
public void doReport_submissions(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS);
state.setAttribute(SORTED_BY, SORTED_SUBMISSION_BY_LASTNAME);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doReport_submissions
/**
*
*
*/
public void doAssignment_form(RunData data)
{
ParameterParser params = data.getParameters();
//Added by Branden Visser: Grab the submission id from the query string
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String actualGradeSubmissionId = (String) params.getString("submissionId");
Log.debug("chef", "doAssignment_form(): actualGradeSubmissionId = " + actualGradeSubmissionId);
String option = (String) params.getString("option");
if (option != null)
{
if ("post".equals(option))
{
// post assignment
doPost_assignment(data);
}
else if ("save".equals(option))
{
// save assignment
doSave_assignment(data);
}
else if ("reorder".equals(option))
{
// reorder assignments
doReorder_assignment(data);
}
else if ("preview".equals(option))
{
// preview assignment
doPreview_assignment(data);
}
else if ("cancel".equals(option))
{
// cancel creating assignment
doCancel_new_assignment(data);
}
else if ("canceledit".equals(option))
{
// cancel editing assignment
doCancel_edit_assignment(data);
}
else if ("attach".equals(option))
{
// attachments
doAttachmentsFrom(data, null);
}
else if ("modelAnswerAttach".equals(option))
{
doAttachmentsFrom(data, "modelAnswer");
}
else if ("allPurposeAttach".equals(option))
{
doAttachmentsFrom(data, "allPurpose");
}
else if ("view".equals(option))
{
// view
doView(data);
}
else if ("permissions".equals(option))
{
// permissions
doPermissions(data);
}
else if ("returngrade".equals(option))
{
//Added by Branden Visser - Check that the state is consistent
if (checkSubmissionStateConsistency(state, actualGradeSubmissionId)) {
// return grading
doReturn_grade_submission(data);
}
}
else if ("savegrade".equals(option))
{
//Added by Branden Visser - Check that the state is consistent
if (checkSubmissionStateConsistency(state, actualGradeSubmissionId)) {
// save grading
doSave_grade_submission(data);
}
}
else if ("previewgrade".equals(option))
{
//Added by Branden Visser - Check that the state is consistent
if (checkSubmissionStateConsistency(state, actualGradeSubmissionId)) {
// preview grading
doPreview_grade_submission(data);
}
}
else if ("cancelgrade".equals(option))
{
// cancel grading
doCancel_grade_submission(data);
}
else if ("cancelreorder".equals(option))
{
// cancel reordering
doCancel_reorder(data);
}
else if ("sortbygrouptitle".equals(option))
{
// read input data
setNewAssignmentParameters(data, true);
// sort by group title
doSortbygrouptitle(data);
}
else if ("sortbygroupdescription".equals(option))
{
// read input data
setNewAssignmentParameters(data, true);
// sort group by description
doSortbygroupdescription(data);
}
else if ("hide_instruction".equals(option))
{
// hide the assignment instruction
doHide_submission_assignment_instruction(data);
}
else if ("show_instruction".equals(option))
{
// show the assignment instruction
doShow_submission_assignment_instruction(data);
}
else if ("sortbygroupdescription".equals(option))
{
// show the assignment instruction
doShow_submission_assignment_instruction(data);
}
else if ("revise".equals(option) || "done".equals(option))
{
// back from the preview mode
doDone_preview_new_assignment(data);
}
else if ("prevsubmission".equals(option))
{
// save and navigate to previous submission
doPrev_back_next_submission(data, "prev");
}
else if ("nextsubmission".equals(option))
{
// save and navigate to previous submission
doPrev_back_next_submission(data, "next");
}
else if ("cancelgradesubmission".equals(option))
{
// back to the list view
doPrev_back_next_submission(data, "back");
}
else if ("reorderNavigation".equals(option))
{
// save and do reorder
doReorder(data);
}
}
}
// added by Branden Visser - Check that the state is consistent
boolean checkSubmissionStateConsistency(SessionState state, String actualGradeSubmissionId) {
String stateGradeSubmissionId = (String)state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
Log.debug("chef", "doAssignment_form(): stateGradeSubmissionId = " + stateGradeSubmissionId);
boolean is_good = stateGradeSubmissionId.equals(actualGradeSubmissionId);
if (!is_good) {
Log.warn("chef", "doAssignment_form(): State is inconsistent! Aborting grade save.");
addAlert(state, rb.getString("grading.alert.multiTab"));
}
return is_good;
}
/**
* Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked
*/
public void doAttachmentsFrom(RunData data, String from)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
doAttachments(data);
// use the real attachment list
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (from != null && "modelAnswer".equals(from))
{
state.setAttribute(ATTACHMENTS_FOR, MODELANSWER_ATTACHMENTS);
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(MODELANSWER_ATTACHMENTS));
state.setAttribute(MODELANSWER, Boolean.TRUE);
}
else if (from != null && "allPurpose".equals(from))
{
state.setAttribute(ATTACHMENTS_FOR, ALLPURPOSE_ATTACHMENTS);
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ALLPURPOSE_ATTACHMENTS));
state.setAttribute(ALLPURPOSE, Boolean.TRUE);
}
}
}
/**
* put supplement item attachment info into state
* @param state
* @param item
* @param attachmentsKind
*/
private void putSupplementItemAttachmentInfoIntoState(SessionState state, AssignmentSupplementItemWithAttachment item, String attachmentsKind)
{
List refs = new Vector();
if (item != null)
{
// get reference list
Set<AssignmentSupplementItemAttachment> aSet = item.getAttachmentSet();
if (aSet != null && aSet.size() > 0)
{
for(Iterator<AssignmentSupplementItemAttachment> aIterator = aSet.iterator(); aIterator.hasNext();)
{
AssignmentSupplementItemAttachment att = aIterator.next();
// add reference
refs.add(EntityManager.newReference(att.getAttachmentId()));
}
state.setAttribute(attachmentsKind, refs);
}
}
}
/**
* put supplement item attachment state attribute value into context
* @param state
* @param context
* @param attachmentsKind
*/
private void putSupplementItemAttachmentStateIntoContext(SessionState state, Context context, String attachmentsKind)
{
List refs = new Vector();
String attachmentsFor = (String) state.getAttribute(ATTACHMENTS_FOR);
if (attachmentsFor != null && attachmentsFor.equals(attachmentsKind))
{
ToolSession session = SessionManager.getCurrentToolSession();
if (session.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null &&
session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null)
{
refs = (List)session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
// set the correct state variable
state.setAttribute(attachmentsKind, refs);
}
session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
state.removeAttribute(ATTACHMENTS_FOR);
}
// show attachments content
if (state.getAttribute(attachmentsKind) != null)
{
context.put(attachmentsKind, state.getAttribute(attachmentsKind));
}
// this is to keep the proper node div open
context.put("attachments_for", attachmentsKind);
}
/**
* Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked
*/
public void doAttachments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String mode = (String) state.getAttribute(STATE_MODE);
if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode))
{
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT),
checkForFormattingErrors);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null)
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true");
}
// need also to upload local file if any
doAttachUpload(data, false);
// TODO: file picker to save in dropbox? -ggolden
// User[] users = { UserDirectoryService.getCurrentUser() };
// state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users);
}
else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode))
{
setNewAssignmentParameters(data, false);
}
else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode))
{
readGradeForm(data, state, "read");
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.filepicker");
state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig"));
state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr"));
// use the real attachment list
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ATTACHMENTS));
}
}
/**
* read grade information form and see if any grading information has been changed
* @param data
* @param state
* @param gradeOption
* @return
*/
public boolean readGradeForm(RunData data, SessionState state, String gradeOption)
{
// whether user has changed anything from previous grading information
boolean hasChange = false;
ParameterParser params = data.getParameters();
String sId = params.getString("submissionId");
// security check for allowing grading submission or not
if (AssignmentService.allowGradeSubmission(sId))
{
int typeOfGrade = -1;
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()
: false;
boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors
String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT),
checkForFormattingErrors);
// comment value changed?
hasChange = !hasChange ? valueDiffFromStateAttribute(state, feedbackComment, GRADE_SUBMISSION_FEEDBACK_COMMENT):hasChange;
if (feedbackComment != null)
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment);
}
String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT));
// feedbackText value changed?
hasChange = !hasChange ? valueDiffFromStateAttribute(state, feedbackText, GRADE_SUBMISSION_FEEDBACK_TEXT):hasChange;
if (feedbackText != null)
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText);
}
// any change inside attachment list?
if (!hasChange)
{
List stateAttachments = state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT) == null?null:((List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT)).isEmpty()?null:(List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
List inputAttachments = state.getAttribute(ATTACHMENTS) == null?null:((List) state.getAttribute(ATTACHMENTS)).isEmpty()?null:(List) state.getAttribute(ATTACHMENTS);
if (stateAttachments == null && inputAttachments != null
|| stateAttachments != null && inputAttachments == null
|| stateAttachments != null && inputAttachments != null && !(stateAttachments.containsAll(inputAttachments) && inputAttachments.containsAll(stateAttachments)))
{
hasChange = true;
}
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS));
String g = StringUtil.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE));
AssignmentSubmission submission = getSubmission(sId, "readGradeForm", state);
if (submission != null)
{
Assignment a = submission.getAssignment();
typeOfGrade = a.getContent().getTypeOfGrade();
if (withGrade)
{
// any change in grade. Do not check for ungraded assignment type
hasChange = (!hasChange && typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) ? (typeOfGrade == Assignment.SCORE_GRADE_TYPE?valueDiffFromStateAttribute(state, scalePointGrade(state, g), GRADE_SUBMISSION_GRADE):valueDiffFromStateAttribute(state, g, GRADE_SUBMISSION_GRADE)):hasChange;
if (g != null)
{
state.setAttribute(GRADE_SUBMISSION_GRADE, g);
}
else
{
state.removeAttribute(GRADE_SUBMISSION_GRADE);
}
// for points grading, one have to enter number as the points
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
// do grade validation only for Assignment with Grade tool
if (typeOfGrade == Assignment.SCORE_GRADE_TYPE)
{
if ((grade != null))
{
// the preview grade process might already scaled up the grade by 10
if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION))
{
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))}));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
M_log.warn(this + ":readGradeForm " + e.getMessage());
}
}
state.setAttribute(GRADE_SUBMISSION_GRADE, grade);
}
}
}
// if ungraded and grade type is not "ungraded" type
if ((grade == null || "ungraded".equals(grade)) && (typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) && "release".equals(gradeOption))
{
addAlert(state, rb.getString("plespethe2"));
}
}
// allow resubmit number and due time
if (params.getString("allowResToggle") != null && params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// read in allowResubmit params
readAllowResubmitParams(params, state, submission);
}
else
{
resetAllowResubmitParams(state);
}
// record whether the resubmission options has been changed or not
hasChange = hasChange || change_resubmit_option(state, submission);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
grade = (typeOfGrade == Assignment.SCORE_GRADE_TYPE)?scalePointGrade(state, grade):grade;
state.setAttribute(GRADE_SUBMISSION_GRADE, grade);
}
}
else
{
// generate alert
addAlert(state, rb.getFormattedMessage("not_allowed_to_grade_submission", new Object[]{sId}));
}
return hasChange;
}
/**
* whether the current input value is different from existing session state value
* @param state
* @param value
* @param stateAttribute
* @return
*/
private boolean valueDiffFromStateAttribute(SessionState state, String value, String stateAttribute)
{
boolean rv = false;
value = StringUtil.trimToNull(value);
String stateAttributeValue = state.getAttribute(stateAttribute) == null?null:StringUtil.trimToNull((String) state.getAttribute(stateAttribute));
if (stateAttributeValue == null && value != null
|| stateAttributeValue != null && value == null
|| stateAttributeValue != null && value != null && !stateAttributeValue.equals(value))
{
rv = true;
}
return rv;
}
/**
* read in the resubmit parameters into state variables
* @param params
* @param state
*/
protected void readAllowResubmitParams(ParameterParser params, SessionState state, Entity entity)
{
String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (allowResubmitNumberString != null && Integer.parseInt(allowResubmitNumberString) != 0)
{
int closeMonth = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, Integer.valueOf(closeMonth));
int closeDay = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, Integer.valueOf(closeDay));
int closeYear = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, Integer.valueOf(closeYear));
int closeHour = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, Integer.valueOf(closeHour));
int closeMin = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, Integer.valueOf(closeMin));
String closeAMPM = params.getString(ALLOW_RESUBMIT_CLOSEAMPM);
state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, closeAMPM);
if (("PM".equals(closeAMPM)) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && ("AM".equals(closeAMPM)))
{
closeHour = 0;
}
Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
// no need to show alert if the resubmission setting has not changed
if (entity == null || change_resubmit_option(state, entity))
{
// validate date
if (closeTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) == null)
{
state.setAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE, Boolean.TRUE);
}
else
{
// clean the attribute after user confirm
state.removeAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE);
}
if (state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) != null)
{
addAlert(state, rb.getString("acesubdea5"));
}
if (!Validator.checkDate(closeDay, closeMonth, closeYear))
{
addAlert(state, rb.getFormattedMessage("date.invalid", new Object[]{rb.getString("date.resubmission.closedate")}));
}
}
}
else
{
// reset the state attributes
resetAllowResubmitParams(state);
}
}
protected void resetAllowResubmitParams(SessionState state)
{
state.removeAttribute(ALLOW_RESUBMIT_CLOSEMONTH);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEDAY);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEYEAR);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEHOUR);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEMIN);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEAMPM);
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
/**
* Populate the state object, if needed - override to do something!
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data)
{
super.initState(state, portlet, data);
if (m_contentHostingService == null)
{
m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
}
if (m_assignmentSupplementItemService == null)
{
m_assignmentSupplementItemService = (AssignmentSupplementItemService) ComponentManager.get("org.sakaiproject.assignment.api.model.AssignmentSupplementItemService");
}
if (m_eventTrackingService == null)
{
m_eventTrackingService = (EventTrackingService) ComponentManager.get("org.sakaiproject.event.api.EventTrackingService");
}
if (m_notificationService == null)
{
m_notificationService = (NotificationService) ComponentManager.get("org.sakaiproject.event.api.NotificationService");
}
String siteId = ToolManager.getCurrentPlacement().getContext();
// show the list of assignment view first
if (state.getAttribute(STATE_SELECTED_VIEW) == null)
{
state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS);
}
if (state.getAttribute(STATE_USER) == null)
{
state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser());
}
/** The content type image lookup service in the State. */
ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
if (iService == null)
{
iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance();
state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService);
} // if
/** The calendar tool */
if (state.getAttribute(CALENDAR_TOOL_EXIST) == null)
{
if (!siteHasTool(siteId, "sakai.schedule"))
{
state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.FALSE);
state.removeAttribute(CALENDAR);
}
else
{
state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE);
if (state.getAttribute(CALENDAR) == null )
{
state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE);
CalendarService cService = org.sakaiproject.calendar.cover.CalendarService.getInstance();
state.setAttribute(STATE_CALENDAR_SERVICE, cService);
String calendarId = ServerConfigurationService.getString("calendar", null);
if (calendarId == null)
{
calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER);
try
{
state.setAttribute(CALENDAR, cService.getCalendar(calendarId));
}
catch (IdUnusedException e)
{
state.removeAttribute(CALENDAR);
M_log.info(this + ":initState No calendar found for site " + siteId + " " + e.getMessage());
}
catch (PermissionException e)
{
state.removeAttribute(CALENDAR);
M_log.info(this + ":initState No permission to get the calender. " + e.getMessage());
}
catch (Exception ex)
{
state.removeAttribute(CALENDAR);
M_log.info(this + ":initState Assignment : Action : init state : calendar exception : " + ex.getMessage());
}
}
}
}
}
/** The Announcement tool */
if (state.getAttribute(ANNOUNCEMENT_TOOL_EXIST) == null)
{
if (!siteHasTool(siteId, "sakai.announcements"))
{
state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.FALSE);
state.removeAttribute(ANNOUNCEMENT_CHANNEL);
}
else
{
state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.TRUE);
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) == null )
{
/** The announcement service in the State. */
AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE);
if (aService == null)
{
aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance();
state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService);
String channelId = ServerConfigurationService.getString("channel", null);
if (channelId == null)
{
channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER);
try
{
state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId));
}
catch (IdUnusedException e)
{
M_log.warn(this + ":initState No announcement channel found. " + e.getMessage());
state.removeAttribute(ANNOUNCEMENT_CHANNEL);
}
catch (PermissionException e)
{
M_log.warn(this + ":initState No permission to annoucement channel. " + e.getMessage());
}
catch (Exception ex)
{
M_log.warn(this + ":initState Assignment : Action : init state : calendar exception : " + ex.getMessage());
}
}
}
}
}
} // if
if (state.getAttribute(STATE_CONTEXT_STRING) == null)
{
state.setAttribute(STATE_CONTEXT_STRING, siteId);
} // if context string is null
if (state.getAttribute(SORTED_BY) == null)
{
setDefaultSort(state);
}
if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null)
{
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME);
}
if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null)
{
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString());
}
if (state.getAttribute(SORTED_SUBMISSION_BY) == null)
{
state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME);
}
if (state.getAttribute(SORTED_SUBMISSION_ASC) == null)
{
state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString());
}
if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null)
{
state.setAttribute(STUDENT_LIST_SHOW_TABLE, new HashSet());
}
if (state.getAttribute(ATTACHMENTS_MODIFIED) == null)
{
state.setAttribute(ATTACHMENTS_MODIFIED, Boolean.valueOf(false));
}
// SECTION MOD
if (state.getAttribute(STATE_SECTION_STRING) == null)
{
state.setAttribute(STATE_SECTION_STRING, "001");
}
// // setup the observer to notify the Main panel
// if (state.getAttribute(STATE_OBSERVER) == null)
// {
// // the delivery location for this tool
// String deliveryId = clientWindowId(state, portlet.getID());
//
// // the html element to update on delivery
// String elementId = mainPanelUpdateId(portlet.getID());
//
// // the event resource reference pattern to watch for
// String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), "");
//
// state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern));
// }
if (state.getAttribute(STATE_MODE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null)
{
state.setAttribute(STATE_TOP_PAGE_MESSAGE, Integer.valueOf(0));
}
if (state.getAttribute(WITH_GRADES) == null)
{
PortletConfig config = portlet.getPortletConfig();
String withGrades = StringUtil.trimToNull(config.getInitParameter("withGrades"));
if (withGrades == null)
{
withGrades = Boolean.FALSE.toString();
}
state.setAttribute(WITH_GRADES, Boolean.valueOf(withGrades));
}
// whether to display the number of submission/ungraded submission column
// default to show
if (state.getAttribute(SHOW_NUMBER_SUBMISSION_COLUMN) == null)
{
PortletConfig config = portlet.getPortletConfig();
String value = StringUtil.trimToNull(config.getInitParameter(SHOW_NUMBER_SUBMISSION_COLUMN));
if (value == null)
{
value = Boolean.TRUE.toString();
}
state.setAttribute(SHOW_NUMBER_SUBMISSION_COLUMN, Boolean.valueOf(value));
}
if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM) == null)
{
state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM, Integer.valueOf(2002));
}
if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO) == null)
{
state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO, Integer.valueOf(2012));
}
} // initState
/**
* whether the site has the specified tool
* @param siteId
* @return
*/
private boolean siteHasTool(String siteId, String toolId) {
boolean rv = false;
try
{
Site s = SiteService.getSite(siteId);
if (s.getToolForCommonId(toolId) != null)
{
rv = true;
}
}
catch (Exception e)
{
M_log.warn(this + "siteHasTool" + e.getMessage() + siteId);
}
return rv;
}
/**
* reset the attributes for view submission
*/
private void resetViewSubmission(SessionState state)
{
state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
state.removeAttribute(VIEW_SUBMISSION_TEXT);
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false");
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
} // resetViewSubmission
/**
* initialize assignment attributes
* @param state
*/
private void initializeAssignment(SessionState state)
{
// put the input value into the state attributes
state.setAttribute(NEW_ASSIGNMENT_TITLE, "");
// get current time
Time t = TimeService.newTime();
TimeBreakdown tB = t.breakdownLocal();
int month = tB.getMonth();
int day = tB.getDay();
int year = tB.getYear();
// set the open time to be 12:00 PM
state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, Integer.valueOf(month));
state.setAttribute(NEW_ASSIGNMENT_OPENDAY, Integer.valueOf(day));
state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, Integer.valueOf(year));
state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, Integer.valueOf(12));
state.setAttribute(NEW_ASSIGNMENT_OPENMIN, Integer.valueOf(0));
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM");
// set the all purpose item release time
state.setAttribute(ALLPURPOSE_RELEASE_MONTH, Integer.valueOf(month));
state.setAttribute(ALLPURPOSE_RELEASE_DAY, Integer.valueOf(day));
state.setAttribute(ALLPURPOSE_RELEASE_YEAR, Integer.valueOf(year));
state.setAttribute(ALLPURPOSE_RELEASE_HOUR, Integer.valueOf(12));
state.setAttribute(ALLPURPOSE_RELEASE_MIN, Integer.valueOf(0));
state.setAttribute(ALLPURPOSE_RELEASE_AMPM, "PM");
// due date is shifted forward by 7 days
t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000);
tB = t.breakdownLocal();
month = tB.getMonth();
day = tB.getDay();
year = tB.getYear();
// set the due time to be 5:00pm
state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, Integer.valueOf(month));
state.setAttribute(NEW_ASSIGNMENT_DUEDAY, Integer.valueOf(day));
state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, Integer.valueOf(year));
state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, Integer.valueOf(5));
state.setAttribute(NEW_ASSIGNMENT_DUEMIN, Integer.valueOf(0));
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM");
// set the resubmit time to be the same as due time
state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, Integer.valueOf(month));
state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, Integer.valueOf(day));
state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, Integer.valueOf(year));
state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, Integer.valueOf(5));
state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, Integer.valueOf(0));
state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, "PM");
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, Integer.valueOf(1));
// enable the close date by default
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true));
// set the close time to be 5:00 pm, same as the due time by default
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, Integer.valueOf(month));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, Integer.valueOf(day));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, Integer.valueOf(year));
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, Integer.valueOf(5));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, Integer.valueOf(0));
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM");
// set the all purpose retract time
state.setAttribute(ALLPURPOSE_RETRACT_MONTH, Integer.valueOf(month));
state.setAttribute(ALLPURPOSE_RETRACT_DAY, Integer.valueOf(day));
state.setAttribute(ALLPURPOSE_RETRACT_YEAR, Integer.valueOf(year));
state.setAttribute(ALLPURPOSE_RETRACT_HOUR, Integer.valueOf(5));
state.setAttribute(ALLPURPOSE_RETRACT_MIN, Integer.valueOf(0));
state.setAttribute(ALLPURPOSE_RETRACT_AMPM, "PM");
state.setAttribute(NEW_ASSIGNMENT_SECTION, "001");
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION));
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(Assignment.UNGRADED_GRADE_TYPE));
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, "");
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, "");
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString());
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString());
// make the honor pledge not include as the default
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (Integer.valueOf(Assignment.HONOR_PLEDGE_NONE)).toString());
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList());
state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE);
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
state.removeAttribute(NEW_ASSIGNMENT_RANGE);
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
// remove the edit assignment id if any
state.removeAttribute(EDIT_ASSIGNMENT_ID);
// remove the resubmit number
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// remove the supplement attributes
state.removeAttribute(MODELANSWER);
state.removeAttribute(MODELANSWER_TEXT);
state.removeAttribute(MODELANSWER_SHOWTO);
state.removeAttribute(MODELANSWER_ATTACHMENTS);
state.removeAttribute(NOTE);
state.removeAttribute(NOTE_TEXT);
state.removeAttribute(NOTE_SHAREWITH);
state.removeAttribute(ALLPURPOSE);
state.removeAttribute(ALLPURPOSE_TITLE);
state.removeAttribute(ALLPURPOSE_TEXT);
state.removeAttribute(ALLPURPOSE_HIDE);
state.removeAttribute(ALLPURPOSE_SHOW_FROM);
state.removeAttribute(ALLPURPOSE_SHOW_TO);
state.removeAttribute(ALLPURPOSE_RELEASE_DATE);
state.removeAttribute(ALLPURPOSE_RETRACT_DATE);
state.removeAttribute(ALLPURPOSE_ACCESS);
state.removeAttribute(ALLPURPOSE_ATTACHMENTS);
} // resetNewAssignment
/**
* reset the attributes for assignment
*/
private void resetAssignment(SessionState state)
{
state.removeAttribute(NEW_ASSIGNMENT_TITLE);
state.removeAttribute(NEW_ASSIGNMENT_OPENMONTH);
state.removeAttribute(NEW_ASSIGNMENT_OPENDAY);
state.removeAttribute(NEW_ASSIGNMENT_OPENYEAR);
state.removeAttribute(NEW_ASSIGNMENT_OPENHOUR);
state.removeAttribute(NEW_ASSIGNMENT_OPENMIN);
state.removeAttribute(NEW_ASSIGNMENT_OPENAMPM);
state.removeAttribute(ALLPURPOSE_RELEASE_MONTH);
state.removeAttribute(ALLPURPOSE_RELEASE_DAY);
state.removeAttribute(ALLPURPOSE_RELEASE_YEAR);
state.removeAttribute(ALLPURPOSE_RELEASE_HOUR);
state.removeAttribute(ALLPURPOSE_RELEASE_MIN);
state.removeAttribute(ALLPURPOSE_RELEASE_AMPM);
state.removeAttribute(NEW_ASSIGNMENT_DUEMONTH);
state.removeAttribute(NEW_ASSIGNMENT_DUEDAY);
state.removeAttribute(NEW_ASSIGNMENT_DUEYEAR);
state.removeAttribute(NEW_ASSIGNMENT_DUEHOUR);
state.removeAttribute(NEW_ASSIGNMENT_DUEMIN);
state.removeAttribute(NEW_ASSIGNMENT_DUEAMPM);
state.removeAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEMONTH);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEDAY);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEYEAR);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEHOUR);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEMIN);
state.removeAttribute(NEW_ASSIGNMENT_CLOSEAMPM);
// set the all purpose retract time
state.removeAttribute(ALLPURPOSE_RETRACT_MONTH);
state.removeAttribute(ALLPURPOSE_RETRACT_DAY);
state.removeAttribute(ALLPURPOSE_RETRACT_YEAR);
state.removeAttribute(ALLPURPOSE_RETRACT_HOUR);
state.removeAttribute(ALLPURPOSE_RETRACT_MIN);
state.removeAttribute(ALLPURPOSE_RETRACT_AMPM);
state.removeAttribute(NEW_ASSIGNMENT_SECTION);
state.removeAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE);
state.removeAttribute(NEW_ASSIGNMENT_GRADE_TYPE);
state.removeAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION);
state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
state.removeAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
state.removeAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
state.removeAttribute(NEW_ASSIGNMENT_ATTACHMENT);
state.removeAttribute(NEW_ASSIGNMENT_FOCUS);
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
state.removeAttribute(NEW_ASSIGNMENT_RANGE);
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
// remove the edit assignment id if any
state.removeAttribute(EDIT_ASSIGNMENT_ID);
// remove the resubmit number
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// remove the supplement attributes
state.removeAttribute(MODELANSWER);
state.removeAttribute(MODELANSWER_TEXT);
state.removeAttribute(MODELANSWER_SHOWTO);
state.removeAttribute(MODELANSWER_ATTACHMENTS);
state.removeAttribute(NOTE);
state.removeAttribute(NOTE_TEXT);
state.removeAttribute(NOTE_SHAREWITH);
state.removeAttribute(ALLPURPOSE);
state.removeAttribute(ALLPURPOSE_TITLE);
state.removeAttribute(ALLPURPOSE_TEXT);
state.removeAttribute(ALLPURPOSE_HIDE);
state.removeAttribute(ALLPURPOSE_SHOW_FROM);
state.removeAttribute(ALLPURPOSE_SHOW_TO);
state.removeAttribute(ALLPURPOSE_RELEASE_DATE);
state.removeAttribute(ALLPURPOSE_RETRACT_DATE);
state.removeAttribute(ALLPURPOSE_ACCESS);
state.removeAttribute(ALLPURPOSE_ATTACHMENTS);
// remove content-review setting
state.removeAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
} // resetNewAssignment
/**
* construct a Hashtable using integer as the key and three character string of the month as the value
*/
private Hashtable monthTable()
{
Hashtable n = new Hashtable();
n.put(Integer.valueOf(1), rb.getString("jan"));
n.put(Integer.valueOf(2), rb.getString("feb"));
n.put(Integer.valueOf(3), rb.getString("mar"));
n.put(Integer.valueOf(4), rb.getString("apr"));
n.put(Integer.valueOf(5), rb.getString("may"));
n.put(Integer.valueOf(6), rb.getString("jun"));
n.put(Integer.valueOf(7), rb.getString("jul"));
n.put(Integer.valueOf(8), rb.getString("aug"));
n.put(Integer.valueOf(9), rb.getString("sep"));
n.put(Integer.valueOf(10), rb.getString("oct"));
n.put(Integer.valueOf(11), rb.getString("nov"));
n.put(Integer.valueOf(12), rb.getString("dec"));
return n;
} // monthTable
/**
* construct a Hashtable using the integer as the key and grade type String as the value
*/
private Hashtable gradeTypeTable()
{
Hashtable n = new Hashtable();
n.put(Integer.valueOf(2), rb.getString("letter"));
n.put(Integer.valueOf(3), rb.getString("points"));
n.put(Integer.valueOf(4), rb.getString("pass"));
n.put(Integer.valueOf(5), rb.getString("check"));
n.put(Integer.valueOf(1), rb.getString("ungra"));
return n;
} // gradeTypeTable
/**
* construct a Hashtable using the integer as the key and submission type String as the value
*/
private Hashtable submissionTypeTable()
{
Hashtable n = new Hashtable();
n.put(Integer.valueOf(1), rb.getString("inlin"));
n.put(Integer.valueOf(2), rb.getString("attaonly"));
n.put(Integer.valueOf(3), rb.getString("inlinatt"));
n.put(Integer.valueOf(4), rb.getString("nonelec"));
n.put(Integer.valueOf(5), rb.getString("singleatt"));
return n;
} // submissionTypeTable
/**
* Add the list of categories from the gradebook tool
* construct a Hashtable using the integer as the key and category String as the value
* @return
*/
private Hashtable<Long, String> categoryTable()
{
boolean gradebookExists = isGradebookDefined();
Hashtable<Long, String> catTable = new Hashtable<Long, String>();
if (gradebookExists) {
GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
List<CategoryDefinition> categoryDefinitions = g.getCategoryDefinitions(gradebookUid);
catTable.put(Long.valueOf(-1), rb.getString("grading.unassigned"));
for (CategoryDefinition category: categoryDefinitions) {
catTable.put(category.getId(), category.getName());
}
}
return catTable;
} // categoryTable
/**
* Sort based on the given property
*/
public void doSort(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
setupSort(data, data.getParameters().getString("criteria"));
}
/**
* setup sorting parameters
*
* @param criteria
* String for sortedBy
*/
private void setupSort(RunData data, String criteria)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_BY)))
{
state.setAttribute(SORTED_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
} // doSort
/**
* Do sort by group title
*/
public void doSortbygrouptitle(RunData data)
{
setupSort(data, SORTED_BY_GROUP_TITLE);
} // doSortbygrouptitle
/**
* Do sort by group description
*/
public void doSortbygroupdescription(RunData data)
{
setupSort(data, SORTED_BY_GROUP_DESCRIPTION);
} // doSortbygroupdescription
/**
* Sort submission based on the given property
*/
public void doSort_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
// get the ParameterParser from RunData
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY)))
{
state.setAttribute(SORTED_SUBMISSION_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_SUBMISSION_ASC, asc);
}
else
{
// current sorting sequence
state.setAttribute(SORTED_SUBMISSION_BY, criteria);
asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_SUBMISSION_ASC, asc);
}
} // doSort_submission
/**
* Sort submission based on the given property in instructor grade view
*/
public void doSort_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
// get the ParameterParser from RunData
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY)))
{
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria);
//for content review default is desc
if (criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
asc = Boolean.FALSE.toString();
else
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc);
}
else
{
// current sorting sequence
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria);
asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc);
}
} // doSort_grade_submission
public void doSort_tags(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
String providerId = params.getString(PROVIDER_ID);
String savedText = params.getString("savedText");
state.setAttribute(VIEW_SUBMISSION_TEXT, savedText);
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
for (DecoratedTaggingProvider dtp : providers) {
if (dtp.getProvider().getId().equals(providerId)) {
Sort sort = dtp.getSort();
if (sort.getSort().equals(criteria)) {
sort.setAscending(sort.isAscending() ? false : true);
} else {
sort.setSort(criteria);
sort.setAscending(true);
}
break;
}
}
}
public void doPage_tags(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String page = params.getString("page");
String pageSize = params.getString("pageSize");
String providerId = params.getString(PROVIDER_ID);
String savedText = params.getString("savedText");
state.setAttribute(VIEW_SUBMISSION_TEXT, savedText);
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
for (DecoratedTaggingProvider dtp : providers) {
if (dtp.getProvider().getId().equals(providerId)) {
Pager pager = dtp.getPager();
pager.setPageSize(Integer.valueOf(pageSize));
if (Pager.FIRST.equals(page)) {
pager.setFirstItem(0);
} else if (Pager.PREVIOUS.equals(page)) {
pager.setFirstItem(pager.getFirstItem()
- pager.getPageSize());
} else if (Pager.NEXT.equals(page)) {
pager.setFirstItem(pager.getFirstItem()
+ pager.getPageSize());
} else if (Pager.LAST.equals(page)) {
pager.setFirstItem((pager.getTotalItems() / pager
.getPageSize())
* pager.getPageSize());
}
break;
}
}
}
/**
* the UserSubmission clas
*/
public class UserSubmission
{
/**
* the User object
*/
User m_user = null;
/**
* the AssignmentSubmission object
*/
AssignmentSubmission m_submission = null;
public UserSubmission(User u, AssignmentSubmission s)
{
m_user = u;
m_submission = s;
}
/**
* Returns the AssignmentSubmission object
*/
public AssignmentSubmission getSubmission()
{
return m_submission;
}
/**
* Returns the User object
*/
public User getUser()
{
return m_user;
}
}
/**
* the AssignmentComparator clas
*/
private class AssignmentComparator implements Comparator
{
Collator collator = Collator.getInstance();
/**
* the SessionState object
*/
SessionState m_state = null;
/**
* the criteria
*/
String m_criteria = null;
/**
* the criteria
*/
String m_asc = null;
/**
* the user
*/
User m_user = null;
/**
* constructor
*
* @param state
* The state object
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
*/
public AssignmentComparator(SessionState state, String criteria, String asc)
{
m_state = state;
m_criteria = criteria;
m_asc = asc;
} // constructor
/**
* constructor
*
* @param state
* The state object
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
* @param user
* The user object
*/
public AssignmentComparator(SessionState state, String criteria, String asc, User user)
{
m_state = state;
m_criteria = criteria;
m_asc = asc;
m_user = user;
} // constructor
/**
* caculate the range string for an assignment
*/
private String getAssignmentRange(Assignment a)
{
String rv = "";
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
// site assignment
rv = rb.getString("range.allgroups");
}
else
{
try
{
// get current site
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
for (Iterator k = a.getGroups().iterator(); k.hasNext();)
{
// announcement by group
rv = rv.concat(site.getGroup((String) k.next()).getTitle());
}
}
catch (Exception ignore)
{
M_log.warn(this + ":getAssignmentRange" + ignore.getMessage());
}
}
return rv;
} // getAssignmentRange
/**
* 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;
if (m_criteria == null)
{
m_criteria = SORTED_BY_DEFAULT;
}
/** *********** for sorting assignments ****************** */
if (m_criteria.equals(SORTED_BY_DEFAULT))
{
int s1 = ((Assignment) o1).getPosition_order();
int s2 = ((Assignment) o2).getPosition_order();
if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate
{
// 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.equals(t2))
{
t1 = ((Assignment) o1).getTimeCreated();
t2 = ((Assignment) o2).getTimeCreated();
}
else if (t1.before(t2))
{
result = 1;
}
else
{
result = -1;
}
}
}
else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list
{
result = 1;
}
else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom
{
result = -1;
}
else // 2 legitimate postion orders
{
result = (s1 < s2) ? -1 : 1;
}
}
if (m_criteria.equals(SORTED_BY_TITLE))
{
// sorted by the assignment title
String s1 = ((Assignment) o1).getTitle();
String s2 = ((Assignment) o2).getTitle();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_SECTION))
{
// sorted by the assignment section
String s1 = ((Assignment) o1).getSection();
String s2 = ((Assignment) o2).getSection();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_DUEDATE))
{
// 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 (m_criteria.equals(SORTED_BY_OPENDATE))
{
// sorted by the assignment open
Time t1 = ((Assignment) o1).getOpenTime();
Time t2 = ((Assignment) o2).getOpenTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS))
{
result = compareString(((Assignment) o1).getStatus(), ((Assignment) o2).getStatus());
}
else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS))
{
// sort by numbers of submissions
// initialize
int subNum1 = 0;
int subNum2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted()) subNum1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted()) subNum2++;
}
result = (subNum1 > subNum2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED))
{
// sort by numbers of ungraded submissions
// initialize
int ungraded1 = 0;
int ungraded2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++;
}
result = (ungraded1 > ungraded2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_GRADE) || m_criteria.equals(SORTED_BY_SUBMISSION_STATUS))
{
AssignmentSubmission submission1 = getSubmission(((Assignment) o1).getId(), m_user, "compare", null);
String grade1 = " ";
if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased())
{
grade1 = submission1.getGrade();
}
AssignmentSubmission submission2 = getSubmission(((Assignment) o2).getId(), m_user, "compare", null);
String grade2 = " ";
if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased())
{
grade2 = submission2.getGrade();
}
result = compareString(grade1, grade2);
}
else if (m_criteria.equals(SORTED_BY_MAX_GRADE))
{
String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1);
String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
M_log.warn(this + ":AssignmentComparator compare" + e.getMessage());
// otherwise do an alpha-compare
result = compareString(maxGrade1, maxGrade2);
}
}
// group related sorting
else if (m_criteria.equals(SORTED_BY_FOR))
{
// sorted by the public view attribute
String factor1 = getAssignmentRange((Assignment) o1);
String factor2 = getAssignmentRange((Assignment) o2);
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_TITLE))
{
// sorted by the group title
String factor1 = ((Group) o1).getTitle();
String factor2 = ((Group) o2).getTitle();
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION))
{
// sorted by the group description
String factor1 = ((Group) o1).getDescription();
String factor2 = ((Group) o2).getDescription();
if (factor1 == null)
{
factor1 = "";
}
if (factor2 == null)
{
factor2 = "";
}
result = compareString(factor1, factor2);
}
/** ***************** for sorting submissions in instructor grade assignment view ************* */
else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
{
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null )
{
result = 1;
}
else
{
int score1 = u1.getSubmission().getReviewScore();
int score2 = u2.getSubmission().getReviewScore();
result = (Integer.valueOf(score1)).intValue() > (Integer.valueOf(score2)).intValue() ? 1 : -1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
String lName1 = u1.getUser().getSortName();
String lName2 = u2.getUser().getSortName();
result = compareString(lName1, lName2);
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null || s1.getTimeSubmitted() == null)
{
result = -1;
}
else if (s2 == null || s2.getTimeSubmitted() == null)
{
result = 1;
}
else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted()))
{
result = -1;
}
else
{
result = 1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
String status1 = "";
String status2 = "";
if (u1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
if (s1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
status1 = s1.getStatus();
}
}
if (u2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s2 = u2.getSubmission();
if (s2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
status2 = s2.getStatus();
}
}
result = compareString(status1, status2);
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
//sort by submission grade
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
String grade1 = s1.getGrade();
String grade2 = s2.getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((s1.getAssignment().getContent().getTypeOfGrade() == 3)
&& ((s2.getAssignment().getContent().getTypeOfGrade() == 3)))
{
if ("".equals(grade1))
{
result = -1;
}
else if ("".equals(grade2))
{
result = 1;
}
else
{
result = compareDouble(grade1, grade2);
}
}
else
{
result = compareString(grade1, grade2);
}
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
// sort by submission released
String released1 = (Boolean.valueOf(s1.getGradeReleased())).toString();
String released2 = (Boolean.valueOf(s2.getGradeReleased())).toString();
result = compareString(released1, released2);
}
}
}
/****** for other sort on submissions **/
else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
User[] u1 = ((AssignmentSubmission) o1).getSubmitters();
User[] u2 = ((AssignmentSubmission) o2).getSubmitters();
if (u1 == null || u1.length == 0 || u2 == null || u2.length ==0)
{
return 1;
}
else
{
String submitters1 = "";
String submitters2 = "";
for (int j = 0; j < u1.length; j++)
{
if (u1[j] != null && u1[j].getSortName() != null)
{
if (j > 0)
{
submitters1 = submitters1.concat("; ");
}
submitters1 = submitters1.concat("" + u1[j].getSortName());
}
}
for (int j = 0; j < u2.length; j++)
{
if (u2[j] != null && u2[j].getSortName() != null)
{
if (j > 0)
{
submitters2 = submitters2.concat("; ");
}
submitters2 = submitters2.concat(u2[j].getSortName());
}
}
result = compareString(submitters1, submitters2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted();
Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS))
{
// sort by submission status
result = compareString(((AssignmentSubmission) o1).getStatus(), ((AssignmentSubmission) o2).getStatus());
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if ("".equals(grade1))
{
result = -1;
}
else if ("".equals(grade2))
{
result = 1;
}
else
{
result = compareDouble(grade1, grade2);
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if ("".equals(grade1))
{
result = -1;
}
else if ("".equals(grade2))
{
result = 1;
}
else
{
result = compareDouble(grade1, grade2);
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE))
{
Assignment a1 = ((AssignmentSubmission) o1).getAssignment();
Assignment a2 = ((AssignmentSubmission) o2).getAssignment();
String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1);
String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
M_log.warn(this + ":AssignmentComparator compare" + e.getMessage());
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED))
{
// sort by submission released
String released1 = (Boolean.valueOf(((AssignmentSubmission) o1).getGradeReleased())).toString();
String released2 = (Boolean.valueOf(((AssignmentSubmission) o2).getGradeReleased())).toString();
result = compareString(released1, released2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT))
{
// sort by submission's assignment
String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle();
String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle();
result = compareString(title1, title2);
}
/*************** sort user by sort name ***************/
else if (m_criteria.equals(SORTED_USER_BY_SORTNAME))
{
// sort by user's sort name
String name1 = ((User) o1).getSortName();
String name2 = ((User) o2).getSortName();
result = compareString(name1, name2);
}
// sort ascending or descending
if (!Boolean.valueOf(m_asc))
{
result = -result;
}
return result;
}
/**
* Compare two strings as double values. Deal with the case when either of the strings cannot be parsed as double value.
* @param grade1
* @param grade2
* @return
*/
private int compareDouble(String grade1, String grade2) {
int result;
try
{
result = (Double.valueOf(grade1)).doubleValue() > (Double.valueOf(grade2)).doubleValue() ? 1 : -1;
}
catch (Exception formatException)
{
// in case either grade1 or grade2 cannot be parsed as Double
result = compareString(grade1, grade2);
M_log.warn(this + ":AssignmentComparator compareDouble " + formatException.getMessage());
}
return result;
} // compareDouble
private int compareString(String s1, String s2)
{
int result;
if (s1 == null && s2 == null) {
result = 0;
} else if (s2 == null) {
result = 1;
} else if (s1 == null) {
result = -1;
} else {
result = collator.compare(s1.toLowerCase(), s2.toLowerCase());
}
return result;
}
/**
* get assignment maximun grade available based on the assignment grade type
*
* @param gradeType
* The int value of grade type
* @param a
* The assignment object
* @return The max grade String
*/
private String maxGrade(int gradeType, Assignment a)
{
String maxGrade = "";
if (gradeType == -1)
{
// Grade type not set
maxGrade = rb.getString("granotset");
}
else if (gradeType == 1)
{
// Ungraded grade type
maxGrade = rb.getString("gen.nograd");
}
else if (gradeType == 2)
{
// Letter grade type
maxGrade = "A";
}
else if (gradeType == 3)
{
// Score based grade type
maxGrade = Integer.toString(a.getContent().getMaxGradePoint());
}
else if (gradeType == 4)
{
// Pass/fail grade type
maxGrade = rb.getString("pass");
}
else if (gradeType == 5)
{
// Grade type that only requires a check
maxGrade = rb.getString("check");
}
return maxGrade;
} // maxGrade
} // DiscussionComparator
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
// we are changing the view, so start with first page again.
resetPaging(state);
// clear search form
doSearch_clear(data, null);
if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String siteRef = SiteService.siteReference(contextString);
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " "
+ SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "asn.");
// ... pass the resource loader object
ResourceLoader pRb = new ResourceLoader("permissions");
HashMap<String, String> pRbValues = new HashMap<String, String>();
for (Iterator iKeys = pRb.keySet().iterator();iKeys.hasNext();)
{
String key = (String) iKeys.next();
pRbValues.put(key, (String) pRb.get(key));
}
state.setAttribute("permissionDescriptions", pRbValues);
// disable auto-updates while leaving the list view
justDelivered(state);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
// switching back to assignment list view
state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS);
doList_assignments(data);
}
} // doPermissions
/**
* transforms the Iterator to Vector
*/
private Vector iterator_to_vector(Iterator l)
{
Vector v = new Vector();
while (l.hasNext())
{
v.add(l.next());
}
return v;
} // iterator_to_vector
/**
* Implement this to return alist of all the resources that there are to page. Sort them as appropriate.
*/
protected List readResourcesPage(SessionState state, int first, int last)
{
List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS);
PagingPosition page = new PagingPosition(first, last);
page.validate(returnResources.size());
returnResources = returnResources.subList(page.getFirst() - 1, page.getLast());
return returnResources;
} // readAllResources
/*
* (non-Javadoc)
*
* @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState)
*/
protected int sizeResources(SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// all the resources for paging
List returnResources = new Vector();
boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString);
if (MODE_LIST_ASSIGNMENTS.equals(mode))
{
String view = "";
if (state.getAttribute(STATE_SELECTED_VIEW) != null)
{
view = (String) state.getAttribute(STATE_SELECTED_VIEW);
}
if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS))
{
// read all Assignments
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW)
|| (!allowAddAssignment && AssignmentService.allowAddSubmission((String) state
.getAttribute(STATE_CONTEXT_STRING))))
{
// in the student list view of assignments
Iterator assignments = AssignmentService
.getAssignmentsForContext(contextString);
Time currentTime = TimeService.newTime();
while (assignments.hasNext())
{
Assignment a = (Assignment) assignments.next();
String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if (deleted == null || "".equals(deleted))
{
// show not deleted assignments
Time openTime = a.getOpenTime();
if (openTime != null && currentTime.after(openTime) && !a.getDraft())
{
returnResources.add(a);
}
}
else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
&& getSubmission(a.getReference(), (User) state.getAttribute(STATE_USER), "sizeResources", state) != null)
{
// and those deleted but not non-electronic assignments but the user has made submissions to them
returnResources.add(a);
}
}
}
else
{
// read all Assignments
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
state.setAttribute(HAS_MULTIPLE_ASSIGNMENTS, Boolean.valueOf(returnResources.size() > 1));
}
else if (MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode))
{
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode))
{
Vector submissions = new Vector();
Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext(contextString));
if (assignments.size() > 0)
{
// users = AssignmentService.allowAddSubmissionUsers (((Assignment)assignments.get(0)).getReference ());
}
try
{
// get the site object first
Site site = SiteService.getSite(contextString);
for (int j = 0; j < assignments.size(); j++)
{
Assignment a = (Assignment) assignments.get(j);
//get the list of users which are allowed to grade this assignment
List allowGradeAssignmentUsers = AssignmentService.allowGradeAssignmentUsers(a.getReference());
String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if ((deleted == null || "".equals(deleted)) && (!a.getDraft()) && AssignmentService.allowGradeSubmission(a.getReference()))
{
try
{
List assignmentSubmissions = AssignmentService.getSubmissions(a);
for (int k = 0; k < assignmentSubmissions.size(); k++)
{
AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k);
if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s
.getTimeReturned())))))
{
// has been subitted or has been returned and not work on it yet
User[] submitters = s.getSubmitters();
if (submitters != null && submitters.length > 0 && !allowGradeAssignmentUsers.contains(submitters[0]))
{
// find whether the submitter is still an active member of the site
Member member = site.getMember(submitters[0].getId());
if(member != null && member.isActive()) {
// only include the active student submission
submissions.add(s);
}
}
} // if-else
}
}
catch (Exception e)
{
M_log.warn(this + ":sizeResources " + e.getMessage());
}
}
}
}
catch (IdUnusedException idUnusedException)
{
M_log.warn(this + ":sizeResources " + idUnusedException.getMessage() + " site id=" + contextString);
}
returnResources = submissions;
}
else if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode))
{
// range
Collection groups = new Vector();
String aRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
Assignment a = getAssignment(aRef, "sizeResources", state);
if (a != null)
{
// all submissions
List submissions = AssignmentService.getSubmissions(a);
// now are we view all sections/groups or just specific one?
initViewSubmissionListOption(state);
String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION);
if (allOrOneGroup.equals(rb.getString("gen.viewallgroupssections")))
{
if (AssignmentService.allowAllGroups(contextString))
{
// site range
try {
groups.add(SiteService.getSite(contextString));
} catch (IdUnusedException e) {
addAlert(state, rb.getFormattedMessage("cannotfin_site", new Object[]{contextString}));
M_log.warn(this + ":sizeResources " + mode + " " + e.getMessage() + " " + contextString);
}
}
else
{
// get all groups user can grade
groups = AssignmentService.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(this + "sizeResources " + e.getMessage() + " groupId=" + allOrOneGroup);
}
}
// all users that can submit
List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
HashSet userIdSet = new HashSet();
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
if (!userIdSet.contains(userId))
{
try
{
User u = UserDirectoryService.getUser(userId);
if (u != null)
{
boolean found = false;
for (int i = 0; !found && i<submissions.size();i++)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.get(i);
if (s.getSubmitterIds().contains(userId))
{
returnResources.add(new UserSubmission(u, s));
found = true;
}
}
// add those users who haven't made any submissions and with submission rights
if (!found && allowAddSubmissionUsers.contains(u))
{
// construct fake submissions for grading purpose if the user has right for grading
if (AssignmentService.allowGradeSubmission(a.getReference()))
{
// temporarily allow the user to read and write from assignments (asn.revise permission)
enableSecurityAdvisor();
AssignmentSubmissionEdit s = AssignmentService.addSubmission(contextString, a.getId(), userId);
s.setSubmitted(true);
s.setAssignment(a);
// set the resubmission properties
setResubmissionProperties(a, s);
AssignmentService.commitEdit(s);
// update the UserSubmission list by adding newly created Submission object
AssignmentSubmission sub = getSubmission(s.getReference(), "sizeResources", state);
returnResources.add(new UserSubmission(u, sub));
// clear the permission
disableSecurityAdvisor();
}
}
}
}
catch (Exception e)
{
M_log.warn(this + ":sizeResources " + e.getMessage() + " userId = " + userId);
}
// add userId into set to prevent showing user multiple times
userIdSet.add(userId);
}
}
}
catch (Exception eee)
{
M_log.warn(this + ":sizeResources " + eee.getMessage() + " authGroupId=" + authzGroupRef);
}
}
}
}
}
// sort them all
String ascending = "true";
String sort = "";
ascending = (String) state.getAttribute(SORTED_ASC);
sort = (String) state.getAttribute(SORTED_BY);
if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode) && (sort == null || !sort.startsWith("sorted_grade_submission_by")))
{
ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC);
sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY);
}
else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode) && (sort == null || sort.startsWith("sorted_submission_by")))
{
ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC);
sort = (String) state.getAttribute(SORTED_SUBMISSION_BY);
}
else
{
ascending = (String) state.getAttribute(SORTED_ASC);
sort = (String) state.getAttribute(SORTED_BY);
}
if ((returnResources.size() > 1) && !MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(mode))
{
try
{
Collections.sort(returnResources, new AssignmentComparator(state, sort, ascending));
}
catch (Exception e)
{
// log exception during sorting for helping debugging
M_log.warn(this + ":sizeResources mode=" + mode + " sort=" + sort + " ascending=" + ascending + " " + e.getStackTrace());
}
}
// record the total item number
state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources);
return returnResources.size();
}
public void doView(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
// we are changing the view, so start with first page again.
resetPaging(state);
// clear search form
doSearch_clear(data, null);
String viewMode = data.getParameters().getString("view");
state.setAttribute(STATE_SELECTED_VIEW, viewMode);
if (MODE_LIST_ASSIGNMENTS.equals(viewMode))
{
doList_assignments(data);
}
else if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(viewMode))
{
doView_students_assignment(data);
}
else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(viewMode))
{
doReport_submissions(data);
}
else if (MODE_STUDENT_VIEW.equals(viewMode))
{
doView_student(data);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
}
} // doView
/**
* put those variables related to 2ndToolbar into context
*/
private void add2ndToolbarFields(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
context.put("totalPageNumber", Integer.valueOf(totalPageNumber(state)));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
context.put("selectedView", state.getAttribute(STATE_MODE));
} // add2ndToolbarFields
/**
* valid grade for point based type
* returns a double value in a string from the localized input
*/
private String validPointGrade(SessionState state, String grade)
{
if (grade != null && !"".equals(grade))
{
if (grade.startsWith("-"))
{
// check for negative sign
addAlert(state, rb.getString("plesuse3"));
}
else
{
// 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);
}
DecimalFormat dcFormat = (DecimalFormat) nbFormat;
String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + "";
// only the right decimal separator is allowed and no other grouping separator
if ((",".equals(decSeparator) && grade.indexOf(".") != -1) ||
(".".equals(decSeparator) && grade.indexOf(",") != -1) ||
grade.indexOf(" ") != -1) {
addAlert(state, rb.getString("plesuse1"));
return grade;
}
// parse grade from localized number format
try {
Double dblGrade = new Double (nbFormat.parse(grade).doubleValue());
grade = dblGrade.toString();
int index = grade.indexOf(".");
if (index != -1)
{
// when there is decimal points inside the grade, scale the number by 10
// but only one decimal place is supported
// for example, change 100.0 to 1000
if (!grade.equals("."))
{
if (grade.length() > index + 2)
{
// if there are more than one decimal point
addAlert(state, rb.getString("plesuse2"));
}
else
{
// decimal points is the only allowed character inside grade
// replace it with '1', and try to parse the new String into int
String gradeString = (grade.endsWith(".")) ? grade.substring(0, index).concat("0") : grade.substring(0,
index).concat(grade.substring(index + 1));
try
{
Integer.parseInt(gradeString);
}
catch (NumberFormatException e)
{
M_log.warn(this + ":validPointGrade " + e.getMessage());
alertInvalidPoint(state, gradeString);
}
}
}
else
{
// grade is "."
addAlert(state, rb.getString("plesuse1"));
}
}
else
{
// There is no decimal point; should be int number
String gradeString = grade + "0";
try
{
Integer.parseInt(gradeString);
}
catch (NumberFormatException e)
{
M_log.warn(this + ":validPointGrade " + e.getMessage());
alertInvalidPoint(state, gradeString);
}
}
}
catch (ParseException e) {
// grade does not meet the number format and could not be parsed
addAlert(state, rb.getString("plesuse1"));
}
}
}
return grade;
} // validPointGrade
/**
* valid grade for point based type
*/
private void validLetterGrade(SessionState state, String grade)
{
String VALID_CHARS_FOR_LETTER_GRADE = " ABCDEFGHIJKLMNOPQRSTUVWXYZ+-";
boolean invalid = false;
if (grade != null)
{
grade = grade.toUpperCase();
for (int i = 0; i < grade.length() && !invalid; i++)
{
char c = grade.charAt(i);
if (VALID_CHARS_FOR_LETTER_GRADE.indexOf(c) == -1)
{
invalid = true;
}
}
if (invalid)
{
addAlert(state, rb.getString("plesuse0"));
}
}
}
private void alertInvalidPoint(SessionState state, String grade)
{
String VALID_CHARS_FOR_INT = "-01234567890";
boolean invalid = false;
// case 1: contains invalid char for int
for (int i = 0; i < grade.length() && !invalid; i++)
{
char c = grade.charAt(i);
if (VALID_CHARS_FOR_INT.indexOf(c) == -1)
{
invalid = true;
}
}
if (invalid)
{
addAlert(state, rb.getString("plesuse1"));
}
else
{
int maxInt = Integer.MAX_VALUE / 10;
int maxDec = Integer.MAX_VALUE - maxInt * 10;
// case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10
addAlert(state, rb.getFormattedMessage("plesuse4", new Object[]{grade.substring(0, grade.length()-1) + "." + grade.substring(grade.length()-1), maxInt + "." + maxDec}));
}
}
/**
* display grade properly
*/
private String displayGrade(SessionState state, String grade)
{
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (grade != null && (grade.length() >= 1))
{
// 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);
// check if grade uses a comma as separator because of number format and change to a point
// remove group separator
DecimalFormat dcformat = (DecimalFormat) nbFormat;
String decSeparator = dcformat.getDecimalFormatSymbols().getDecimalSeparator() + "";
if (",".equals(decSeparator) && grade.indexOf(decSeparator) != -1) {
grade = grade.replace(",", ".");
}
if (grade.indexOf(".") != -1)
{
if (grade.startsWith("."))
{
grade = "0".concat(grade);
}
else if (grade.endsWith("."))
{
grade = grade.concat("0");
}
}
else
{
try
{
Integer.parseInt(grade);
grade = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1);
}
catch (NumberFormatException e)
{
// alert
alertInvalidPoint(state, grade);
M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage());
}
}
try {
// show grade in localized number format
Double dblGrade = new Double(grade);
grade = nbFormat.format(dblGrade);
}
catch (Exception e) {
// alert
alertInvalidPoint(state, grade);
M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage());
}
}
else
{
grade = "";
}
}
return grade;
} // displayGrade
/**
* scale the point value by 10 if there is a valid point grade
*/
private String scalePointGrade(SessionState state, String point)
{
point = validPointGrade(state, point);
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (point != null && (point.length() >= 1))
{
// when there is decimal points inside the grade, scale the number by 10
// but only one decimal place is supported
// for example, change 100.0 to 1000
int index = point.indexOf(".");
if (index != -1)
{
if (index == 0)
{
// if the point is the first char, add a 0 for the integer part
point = "0".concat(point.substring(1));
}
else if (index < point.length() - 1)
{
// use scale integer for gradePoint
point = point.substring(0, index) + point.substring(index + 1);
}
else
{
// decimal point is the last char
point = point.substring(0, index) + "0";
}
}
else
{
// if there is no decimal place, scale up the integer by 10
point = point + "0";
}
// filter out the "zero grade"
if ("00".equals(point))
{
point = "0";
}
}
}
if (StringUtil.trimToNull(point) != null)
{
try
{
point = Integer.valueOf(point).toString();
}
catch (Exception e)
{
M_log.warn(this + " scalePointGrade: cannot parse " + point + " into integer. " + e.getMessage());
}
}
return point;
} // scalePointGrade
/**
* Processes formatted text that is coming back from the browser (from the formatted text editing widget).
*
* @param state
* Used to pass in any user-visible alerts or errors when processing the text
* @param strFromBrowser
* The string from the browser
* @param checkForFormattingErrors
* Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors.
* @return The formatted text
*/
private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors)
{
StringBuilder alertMsg = new StringBuilder();
try
{
boolean replaceWhitespaceTags = true;
String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors,
replaceWhitespaceTags);
if (alertMsg.length() > 0) addAlert(state, alertMsg.toString());
return text;
}
catch (Exception e)
{
M_log.warn(this + ":processFormattedTextFromBrowser " + e.getMessage());
return strFromBrowser;
}
}
/**
* Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced.
*/
private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser)
{
if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser;
StringBuilder buf = new StringBuilder(strFromBrowser);
int pos = -1;
int numopentags = 0;
while ((pos = buf.indexOf("{{")) != -1)
{
buf.replace(pos, pos + "{{".length(), "<ins>");
numopentags++;
}
while ((pos = buf.indexOf("}}")) != -1)
{
buf.replace(pos, pos + "}}".length(), "</ins>");
numopentags--;
}
while (numopentags > 0)
{
buf.append("</ins>");
numopentags--;
}
boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors
buf = new StringBuilder(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors));
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();
}
/**
* Called to deal with old Chef-style assignment feedback annotation, {{like this}}.
*
* @param value
* A formatted text string that may contain {{}} style markup
* @return HTML ready to for display on a browser
*/
public static String escapeAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
value = fixAssignmentFeedback(value);
StringBuilder buf = new StringBuilder(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());
}
/**
* Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget)
*/
public static String escapeAssignmentFeedbackTextarea(String value)
{
if (value == null || value.length() == 0) return value;
value = fixAssignmentFeedback(value);
return FormattedText.escapeHtmlFormattedTextarea(value);
}
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
private static String fixAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuilder buf = new StringBuilder(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
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
public static String showPrevFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuilder buf = new StringBuilder(value);
int pos = -1;
// <br/> -> \n
while ((pos = buf.indexOf("\n")) != -1)
{
buf.replace(pos, pos + "\n".length(), "<br />");
}
return buf.toString();
} // showPrevFeedback
private boolean alertGlobalNavigation(SessionState state, RunData data)
{
String mode = (String) state.getAttribute(STATE_MODE);
ParameterParser params = data.getParameters();
if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode) || MODE_STUDENT_PREVIEW_SUBMISSION.equals(mode)
|| MODE_STUDENT_VIEW_GRADE.equals(mode) || MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode)
|| MODE_INSTRUCTOR_DELETE_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode)
|| MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION.equals(mode)|| MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode)
|| MODE_INSTRUCTOR_VIEW_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode))
{
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null)
{
addAlert(state, rb.getString("alert.globalNavi"));
state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE);
if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode))
{
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT),
checkForFormattingErrors);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null)
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true");
}
state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt"));
// TODO: file picker to save in dropbox? -ggolden
// User[] users = { UserDirectoryService.getCurrentUser() };
// state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users);
}
else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode))
{
setNewAssignmentParameters(data, false);
}
else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode))
{
readGradeForm(data, state, "read");
}
return true;
}
}
return false;
} // alertGlobalNavigation
/**
* Dispatch function inside add submission page
*/
public void doRead_add_submission_form(RunData data)
{
String option = data.getParameters().getString("option");
if ("cancel".equals(option))
{
// cancel
doCancel_show_submission(data);
}
else if ("preview".equals(option))
{
// preview
doPreview_submission(data);
}
else if ("save".equals(option))
{
// save draft
doSave_submission(data);
}
else if ("post".equals(option))
{
// post
doPost_submission(data);
}
else if ("revise".equals(option))
{
// done preview
doDone_preview_submission(data);
}
else if ("attach".equals(option))
{
// attach
ToolSession toolSession = SessionManager.getCurrentToolSession();
String userId = SessionManager.getCurrentSessionUserId();
String siteId = SiteService.getUserSiteId(userId);
String collectionId = m_contentHostingService.getSiteCollection(siteId);
toolSession.setAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID, collectionId);
doAttachments(data);
}
else if ("removeAttachment".equals(option))
{
// remove selected attachment
doRemove_attachment(data);
}
}
public void doRemove_attachment(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String removeAttachmentId = params.getString("currentAttachment");
List attachments = state.getAttribute(ATTACHMENTS) == null?null:((List) state.getAttribute(ATTACHMENTS)).isEmpty()?null:(List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
Reference found = null;
for(Object attachment : attachments)
{
if (((Reference) attachment).getId().equals(removeAttachmentId))
{
found = (Reference) attachment;
break;
}
}
if (found != null)
{
attachments.remove(found);
// refresh state variable
state.setAttribute(ATTACHMENTS, attachments);
}
}
}
/**
* Set default score for all ungraded non electronic submissions
* @param data
*/
public void doSet_defaultNotGradedNonElectronicScore(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String grade = StringUtil.trimToNull(params.getString("defaultGrade"));
if (grade == null)
{
addAlert(state, rb.getString("plespethe2"));
}
String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
// record the default grade setting for no-submission
AssignmentEdit aEdit = editAssignment(assignmentId, "doSet_defaultNotGradedNonElectronicScore", state, false);
if (aEdit != null)
{
aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade);
AssignmentService.commitEdit(aEdit);
}
Assignment a = getAssignment(assignmentId, "doSet_defaultNotGradedNonElectronicScore", state);
if (a != null && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
//for point-based grades
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))}));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
M_log.warn(this + ":setDefaultNotGradedNonElectronicScore " + e.getMessage());
alertInvalidPoint(state, grade);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade = scalePointGrade(state, grade);
}
}
if (grade != null && state.getAttribute(STATE_MESSAGE) == null)
{
// get the user list
List submissions = AssignmentService.getSubmissions(a);
for (int i = 0; i<submissions.size(); i++)
{
// get the submission object
AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i);
if (submission.getSubmitted() && !submission.getGraded())
{
String sRef = submission.getReference();
// update the grades for those existing non-submissions
AssignmentSubmissionEdit sEdit = editSubmission(sRef, "doSet_defaultNotGradedNonElectronicScore", state);
if (sEdit != null)
{
sEdit.setGrade(grade);
sEdit.setGraded(true);
AssignmentService.commitEdit(sEdit);
}
}
}
}
}
/**
*
*/
public void doSet_defaultNoSubmissionScore(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String grade = StringUtil.trimToNull(params.getString("defaultGrade"));
if (grade == null)
{
addAlert(state, rb.getString("plespethe2"));
}
String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
// record the default grade setting for no-submission
AssignmentEdit aEdit = editAssignment(assignmentId, "doSet_defaultNoSubmissionScore", state, false);
if (aEdit != null)
{
aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade);
AssignmentService.commitEdit(aEdit);
}
Assignment a = getAssignment(assignmentId, "doSet_defaultNoSubmissionScore", state);
if (a != null && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
//for point-based grades
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))}));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
M_log.warn(this + ":setDefaultNoSubmissionScore " + e.getMessage());
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade = scalePointGrade(state, grade);
}
}
if (grade != null && state.getAttribute(STATE_MESSAGE) == null)
{
// get the submission list
List submissions = AssignmentService.getSubmissions(a);
for (int i = 0; i<submissions.size(); i++)
{
// get the submission object
AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i);
if (StringUtil.trimToNull(submission.getGrade()) == null)
{
// update the grades for those existing non-submissions
AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "doSet_defaultNoSubmissionScore", state);
if (sEdit != null)
{
sEdit.setGrade(grade);
sEdit.setSubmitted(true);
sEdit.setGraded(true);
AssignmentService.commitEdit(sEdit);
}
}
else if (StringUtil.trimToNull(submission.getGrade()) != null && !submission.getGraded())
{
// correct the grade status if there is a grade but the graded is false
AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "doSet_defaultNoSubmissionScore", state);
if (sEdit != null)
{
sEdit.setGraded(true);
AssignmentService.commitEdit(sEdit);
}
}
}
}
}
/**
*
* @return
*/
public void doDownload_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String flow = params.getString("flow");
if ("upload".equals(flow))
{
// upload
doUpload_all(data);
}
else if ("download".equals(flow))
{
// upload
doDownload_all(data);
}
else if ("cancel".equals(flow))
{
// cancel
doCancel_download_upload_all(data);
}
}
public void doDownload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
}
public void doUpload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String contextString = ToolManager.getCurrentPlacement().getContext();
String toolTitle = ToolManager.getTool(ASSIGNMENT_TOOL_ID).getTitle();
String aReference = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
String associateGradebookAssignment = null;
List<String> choices = params.getStrings("choices") != null?new ArrayList(Arrays.asList(params.getStrings("choices"))):null;
if (choices == null || choices.size() == 0)
{
// has to choose one upload feature
addAlert(state, rb.getString("uploadall.alert.choose.element"));
}
else
{
boolean hasSubmissionText = false;
boolean hasSubmissionAttachment = false;
boolean hasGradeFile = false;
boolean hasFeedbackText = false;
boolean hasComment = false;
boolean hasFeedbackAttachment = false;
boolean releaseGrades = false;
// check against the content elements selection
if (choices.contains("studentSubmissionText"))
{
// should contain student submission text information
hasSubmissionText = true;
}
if (choices.contains("studentSubmissionAttachment"))
{
// should contain student submission attachment information
hasSubmissionAttachment = true;
}
if (choices.contains("gradeFile"))
{
// should contain grade file
hasGradeFile = true;
}
if (choices.contains("feedbackTexts"))
{
// inline text
hasFeedbackText = true;
}
if (choices.contains("feedbackComments"))
{
// comments.txt should be available
hasComment = true;
}
if (choices.contains("feedbackAttachments"))
{
// feedback attachment
hasFeedbackAttachment = true;
}
if (params.getString("release") != null)
{
// comments.xml should be available
releaseGrades = params.getBoolean("release");
}
state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT, Boolean.valueOf(hasSubmissionText));
state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT, Boolean.valueOf(hasSubmissionAttachment));
state.setAttribute(UPLOAD_ALL_HAS_GRADEFILE, Boolean.valueOf(hasGradeFile));
state.setAttribute(UPLOAD_ALL_HAS_COMMENTS, Boolean.valueOf(hasComment));
state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT, Boolean.valueOf(hasFeedbackText));
state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT, Boolean.valueOf(hasFeedbackAttachment));
state.setAttribute(UPLOAD_ALL_RELEASE_GRADES, Boolean.valueOf(releaseGrades));
// constructor the hashtable for all submission objects
Hashtable submissionTable = new Hashtable();
List submissions = null;
Assignment assignment = getAssignment(aReference, "doUpload_all", state);
if (assignment != null)
{
associateGradebookAssignment = StringUtil.trimToNull(assignment.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
submissions = AssignmentService.getSubmissions(assignment);
if (submissions != null)
{
Iterator sIterator = submissions.iterator();
while (sIterator.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
User[] users = s.getSubmitters();
if (users != null && users.length > 0 && users[0] != null)
{
submissionTable.put(users[0].getEid(), new UploadGradeWrapper(s.getGrade(), s.getSubmittedText(), s.getFeedbackComment(), hasSubmissionAttachment?new Vector():s.getSubmittedAttachments(), hasFeedbackAttachment?new Vector():s.getFeedbackAttachments(), (s.getSubmitted() && s.getTimeSubmitted() != null)?s.getTimeSubmitted().toString():"", s.getFeedbackText()));
}
}
}
}
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = params.getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1");
int max_bytes = 1024 * 1024;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
M_log.warn(this + ":doUpload_all_upload " + e.getMessage());
}
if(fileFromUpload == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded"));
}
else
{
String contentType = fileFromUpload.getContentType();
if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0
|| (!"application/zip".equals(contentType) && !"application/x-zip-compressed".equals(contentType)))
{
// no file
addAlert(state, rb.getString("uploadall.alert.zipFile"));
}
else
{
InputStream fileContentStream = fileFromUpload.getInputStream();
int contentLength = data.getRequest().getContentLength();
if(contentLength >= max_bytes)
{
addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded"));
}
else if(fileContentStream != null)
{
// a flag value for checking whether the zip file is of proper format:
// should have a grades.csv file if there is no user folders
boolean zipHasGradeFile = false;
// and if have any folder structures, those folders should be named after at least one site user (zip file could contain user names who is no longer inside the site)
boolean zipHasFolder = false;
boolean zipHasFolderValidUserId = false;
FileOutputStream tmpFileOut = null;
try
{
File f = File.createTempFile(String.valueOf(System.currentTimeMillis()),"");
tmpFileOut = new FileOutputStream(f);
writeToStream(fileContentStream, tmpFileOut);
tmpFileOut.flush();
tmpFileOut.close();
ZipFile zipFile = new ZipFile(f, "UTF-8");
Enumeration<ZipEntry> zipEntries = zipFile.getEntries();
ZipEntry entry;
while (zipEntries.hasMoreElements())
{
entry = zipEntries.nextElement();
String entryName = entry.getName();
if (!entry.isDirectory() && entryName.indexOf("/.") == -1)
{
if (entryName.endsWith("grades.csv"))
{
// at least the zip file has a grade.csv
zipHasGradeFile = true;
if (hasGradeFile)
{
// read grades.cvs from zip
String result = StringUtil.trimToZero(readIntoString(zipFile.getInputStream(entry)));
String[] lines=null;
if (result.indexOf("\r\n") != -1)
lines = result.split("\r\n");
else if (result.indexOf("\r") != -1)
lines = result.split("\r");
else if (result.indexOf("\n") != -1)
lines = result.split("\n");
if (lines != null )
{
for (int i = 3; i<lines.length; i++)
{
// escape the first three header lines
String[] items = lines[i].split(",");
if (items.length > 4)
{
// has grade information
try
{
User u = UserDirectoryService.getUserByEid(items[1]/*user eid*/);
if (u != null)
{
UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(u.getEid());
if (w != null)
{
String itemString = items[4];
int gradeType = assignment.getContent().getTypeOfGrade();
if (gradeType == Assignment.SCORE_GRADE_TYPE)
{
validPointGrade(state, itemString);
}
else
{
validLetterGrade(state, itemString);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE?scalePointGrade(state, itemString):itemString);
submissionTable.put(u.getEid(), w);
}
}
}
}
catch (Exception e )
{
M_log.warn(this + ":doUpload_all_upload " + e.getMessage());
}
}
}
}
}
}
else
{
// get user eid part
String userEid = "";
if (entryName.indexOf("/") != -1)
{
// there is folder structure inside zip
if (!zipHasFolder) zipHasFolder = true;
// remove the part of zip name
userEid = entryName.substring(entryName.indexOf("/")+1);
// get out the user name part
if (userEid.indexOf("/") != -1)
{
userEid = userEid.substring(0, userEid.indexOf("/"));
}
// get the eid part
if (userEid.indexOf("(") != -1)
{
userEid = userEid.substring(userEid.indexOf("(")+1, userEid.indexOf(")"));
}
userEid=StringUtil.trimToNull(userEid);
}
if (submissionTable.containsKey(userEid))
{
if (!zipHasFolderValidUserId) zipHasFolderValidUserId = true;
if (hasComment && entryName.indexOf("comments") != -1)
{
// read the comments file
String comment = getBodyTextFromZipHtml(zipFile.getInputStream(entry));
if (comment != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
r.setComment(comment);
submissionTable.put(userEid, r);
}
}
if (hasFeedbackText && entryName.indexOf("feedbackText") != -1)
{
// upload the feedback text
String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry));
if (text != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
r.setFeedbackText(text);
submissionTable.put(userEid, r);
}
}
if (hasSubmissionText && entryName.indexOf("_submissionText") != -1)
{
// upload the student submission text
String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry));
if (text != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
r.setText(text);
submissionTable.put(userEid, r);
}
}
if (hasSubmissionAttachment)
{
// upload the submission attachment
String submissionFolder = "/" + rb.getString("download.submission.attachment") + "/";
if ( entryName.indexOf(submissionFolder) != -1)
{
// clear the submission attachment first
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
submissionTable.put(userEid, r);
submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "submission");
}
}
if (hasFeedbackAttachment)
{
// upload the feedback attachment
String submissionFolder = "/" + rb.getString("download.feedback.attachment") + "/";
if ( entryName.indexOf(submissionFolder) != -1)
{
// clear the feedback attachment first
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
submissionTable.put(userEid, r);
submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "feedback");
}
}
// if this is a timestamp file
if (entryName.indexOf("timestamp") != -1)
{
byte[] timeStamp = readIntoBytes(zipFile.getInputStream(entry), entryName, entry.getSize());
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
r.setSubmissionTimestamp(new String(timeStamp));
submissionTable.put(userEid, r);
}
}
}
}
}
}
catch (IOException e)
{
// uploaded file is not a valid archive
addAlert(state, rb.getString("uploadall.alert.zipFile"));
M_log.warn(this + ":doUpload_all_upload " + e.getMessage());
}
finally
{
if (tmpFileOut != null) {
try {
tmpFileOut.close();
} catch (IOException e) {
M_log.warn(this + "doUpload_all: Error closing temp file output stream: " + e.toString());
}
}
if (fileContentStream != null) {
try {
fileContentStream.close();
} catch (IOException e) {
M_log.warn(this + "doUpload_all: Error closing file upload stream: " + e.toString());
}
}
}
if ((!zipHasGradeFile && !zipHasFolder) // generate error when there is no grade file and no folder structure
|| (zipHasFolder && !zipHasFolderValidUserId)) // generate error when there is folder structure but not matching one user id
{
// alert if the zip is of wrong format
addAlert(state, rb.getString("uploadall.alert.wrongZipFormat"));
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// update related submissions
if (assignment != null && submissions != null)
{
Iterator sIterator = submissions.iterator();
while (sIterator.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
User[] users = s.getSubmitters();
if (users != null && users.length > 0 && users[0] != null)
{
String uName = users[0].getEid();
if (submissionTable.containsKey(uName))
{
// update the AssignmetnSubmission record
AssignmentSubmissionEdit sEdit = editSubmission(s.getReference(), "doUpload_all", state);
if (sEdit != null)
{
UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(uName);
// the submission text
if (hasSubmissionText)
{
sEdit.setSubmittedText(w.getText());
}
// the feedback text
if (hasFeedbackText)
{
sEdit.setFeedbackText(w.getFeedbackText());
}
// the submission attachment
if (hasSubmissionAttachment)
{
// update the submission attachments with newly added ones from zip file
List submittedAttachments = sEdit.getSubmittedAttachments();
for (Iterator attachments = w.getSubmissionAttachments().iterator(); attachments.hasNext();)
{
Reference a = (Reference) attachments.next();
if (!submittedAttachments.contains(a))
{
sEdit.addSubmittedAttachment(a);
}
}
}
// the feedback attachment
if (hasFeedbackAttachment)
{
List feedbackAttachments = sEdit.getFeedbackAttachments();
for (Iterator attachments = w.getFeedbackAttachments().iterator(); attachments.hasNext();)
{
// update the feedback attachments with newly added ones from zip file
Reference a = (Reference) attachments.next();
if (!feedbackAttachments.contains(a))
{
sEdit.addFeedbackAttachment(a);
}
}
}
// the feedback comment
if (hasComment)
{
sEdit.setFeedbackComment(w.getComment());
}
// the grade file
if (hasGradeFile)
{
// set grade
String grade = StringUtil.trimToNull(w.getGrade());
sEdit.setGrade(grade);
if (grade != null && !grade.equals(rb.getString("gen.nograd")) && !"ungraded".equals(grade))
sEdit.setGraded(true);
}
// release or not
if (sEdit.getGraded())
{
sEdit.setGradeReleased(releaseGrades);
sEdit.setReturned(releaseGrades);
}
else
{
sEdit.setGradeReleased(false);
sEdit.setReturned(false);
}
if (releaseGrades && sEdit.getGraded())
{
sEdit.setTimeReturned(TimeService.newTime());
}
// if the current submission lacks timestamp while the timestamp exists inside the zip file
if (StringUtil.trimToNull(w.getSubmissionTimeStamp()) != null && sEdit.getTimeSubmitted() == null)
{
sEdit.setTimeSubmitted(TimeService.newTimeGmt(w.getSubmissionTimeStamp()));
sEdit.setSubmitted(true);
}
// for further information
boolean graded = sEdit.getGraded();
String sReference = sEdit.getReference();
// commit
AssignmentService.commitEdit(sEdit);
if (releaseGrades && graded)
{
// update grade in gradebook
if (associateGradebookAssignment != null)
{
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update", -1);
}
}
}
}
}
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// go back to the list of submissions view
cleanUploadAllContext(state);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
}
}
/**
* This is to get the submission or feedback attachment from the upload zip file into the submission object
* @param state
* @param submissionTable
* @param zin
* @param entry
* @param entryName
* @param userEid
* @param submissionOrFeedback
*/
private Hashtable uploadZipAttachments(SessionState state, Hashtable submissionTable, InputStream zin, ZipEntry entry, String entryName, String userEid, String submissionOrFeedback) {
// upload all the files as instructor attachments to the submission for grading purpose
String fName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length());
ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
try
{
// get file extension for detecting content type
// ignore those hidden files
String extension = "";
if(!fName.contains(".") || (fName.contains(".") && fName.indexOf(".") != 0))
{
// add the file as attachment
ResourceProperties properties = m_contentHostingService.newResourceProperties();
properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fName);
String[] parts = fName.split("\\.");
if(parts.length > 1)
{
extension = parts[parts.length - 1];
}
try {
String contentType = ((ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)).getContentType(extension);
ContentResourceEdit attachment = m_contentHostingService.addAttachmentResource(fName);
attachment.setContent(zin);
attachment.setContentType(contentType);
attachment.getPropertiesEdit().addAll(properties);
m_contentHostingService.commitResource(attachment);
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
List attachments = "submission".equals(submissionOrFeedback)?r.getSubmissionAttachments():r.getFeedbackAttachments();
attachments.add(EntityManager.newReference(attachment.getReference()));
if ("submission".equals(submissionOrFeedback))
{
r.setSubmissionAttachments(attachments);
}
else
{
r.setFeedbackAttachments(attachments);
}
submissionTable.put(userEid, r);
}
catch (Exception e)
{
M_log.warn(this + ":doUploadZipAttachments problem commit resource " + e.getMessage());
}
}
}
catch (Exception ee)
{
M_log.warn(this + ":doUploadZipAttachments " + ee.getMessage());
}
return submissionTable;
}
private String getBodyTextFromZipHtml(InputStream zin)
{
String rv = "";
try
{
rv = StringUtil.trimToNull(readIntoString(zin));
}
catch (IOException e)
{
M_log.warn(this + ":getBodyTextFromZipHtml " + e.getMessage());
}
if (rv != null)
{
int start = rv.indexOf("<body>");
int end = rv.indexOf("</body>");
if (start != -1 && end != -1)
{
// get the text in between
rv = rv.substring(start+6, end);
}
}
return rv;
}
private byte[] readIntoBytes(InputStream zin, String fName, long length) throws IOException {
byte[] buffer = new byte[4096];
File f = File.createTempFile("asgnup", "tmp");
FileOutputStream fout = new FileOutputStream(f);
try {
int len;
while ((len = zin.read(buffer)) > 0)
{
fout.write(buffer, 0, len);
}
zin.close();
} finally {
try
{
fout.close(); // The file channel needs to be closed before the deletion.
}
catch (IOException ioException)
{
M_log.warn(this + "readIntoBytes: problem closing FileOutputStream " + ioException.getMessage());
}
}
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
byte[] data = null;
try {
data = new byte[(int)(fc.size())]; // fc.size returns the size of the file which backs the channel
ByteBuffer bb = ByteBuffer.wrap(data);
fc.read(bb);
} finally {
try
{
fc.close(); // The file channel needs to be closed before the deletion.
}
catch (IOException ioException)
{
M_log.warn(this + "readIntoBytes: problem closing FileChannel " + ioException.getMessage());
}
try
{
fis.close(); // The file inputstream needs to be closed before the deletion.
}
catch (IOException ioException)
{
M_log.warn(this + "readIntoBytes: problem closing FileInputStream " + ioException.getMessage());
}
}
//remove the file
f.delete();
return data;
}
private String readIntoString(InputStream zin) throws IOException
{
StringBuilder buffer = new StringBuilder();
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
try
{
size = zin.read(data, 0, data.length);
if (size > 0)
{
buffer.append(new String(data, 0, size));
}
else
{
break;
}
}
catch (IOException e)
{
M_log.warn(this + ":readIntoString " + e.getMessage());
}
}
return buffer.toString();
}
/**
*
* @return
*/
public void doCancel_download_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
cleanUploadAllContext(state);
}
/**
* clean the state variabled used by upload all process
*/
private void cleanUploadAllContext(SessionState state)
{
state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT);
state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT);
state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT);
state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT);
state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE);
state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS);
state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES);
}
/**
* Action is to preparing to go to the download all file
*/
public void doPrep_download_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DOWNLOAD_ALL);
} // doPrep_download_all
/**
* Action is to preparing to go to the upload files
*/
public void doPrep_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_UPLOAD_ALL);
} // doPrep_upload_all
/**
* the UploadGradeWrapper class to be used for the "upload all" feature
*/
public class UploadGradeWrapper
{
/**
* the grade
*/
String m_grade = null;
/**
* the text
*/
String m_text = null;
/**
* the submission attachment list
*/
List m_submissionAttachments = EntityManager.newReferenceList();
/**
* the comment
*/
String m_comment = "";
/**
* the timestamp
*/
String m_timeStamp="";
/**
* the feedback text
*/
String m_feedbackText="";
/**
* the feedback attachment list
*/
List m_feedbackAttachments = EntityManager.newReferenceList();
public UploadGradeWrapper(String grade, String text, String comment, List submissionAttachments, List feedbackAttachments, String timeStamp, String feedbackText)
{
m_grade = grade;
m_text = text;
m_comment = comment;
m_submissionAttachments = submissionAttachments;
m_feedbackAttachments = feedbackAttachments;
m_feedbackText = feedbackText;
m_timeStamp = timeStamp;
}
/**
* Returns grade string
*/
public String getGrade()
{
return m_grade;
}
/**
* Returns the text
*/
public String getText()
{
return m_text;
}
/**
* Returns the comment string
*/
public String getComment()
{
return m_comment;
}
/**
* Returns the submission attachment list
*/
public List getSubmissionAttachments()
{
return m_submissionAttachments;
}
/**
* Returns the feedback attachment list
*/
public List getFeedbackAttachments()
{
return m_feedbackAttachments;
}
/**
* submission timestamp
* @return
*/
public String getSubmissionTimeStamp()
{
return m_timeStamp;
}
/**
* feedback text/incline comment
* @return
*/
public String getFeedbackText()
{
return m_feedbackText;
}
/**
* set the grade string
*/
public void setGrade(String grade)
{
m_grade = grade;
}
/**
* set the text
*/
public void setText(String text)
{
m_text = text;
}
/**
* set the comment string
*/
public void setComment(String comment)
{
m_comment = comment;
}
/**
* set the submission attachment list
*/
public void setSubmissionAttachments(List attachments)
{
m_submissionAttachments = attachments;
}
/**
* set the attachment list
*/
public void setFeedbackAttachments(List attachments)
{
m_feedbackAttachments = attachments;
}
/**
* set the submission timestamp
*/
public void setSubmissionTimestamp(String timeStamp)
{
m_timeStamp = timeStamp;
}
/**
* set the feedback text
*/
public void setFeedbackText(String feedbackText)
{
m_feedbackText = feedbackText;
}
}
private List<DecoratedTaggingProvider> initDecoratedProviders() {
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.taggable.api.TaggingManager");
List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>();
for (TaggingProvider provider : taggingManager.getProviders())
{
providers.add(new DecoratedTaggingProvider(provider));
}
return providers;
}
private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
if (providers == null)
{
providers = initDecoratedProviders();
state.setAttribute(mode + PROVIDER_LIST, providers);
}
context.put("providers", providers);
return providers;
}
private void addActivity(Context context, Assignment assignment)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
context.put("activity", assignmentActivityProducer
.getActivity(assignment));
String placement = ToolManager.getCurrentPlacement().getId();
context.put("iframeId", Validator.escapeJavascript("Main" + placement));
}
private void addItem(Context context, AssignmentSubmission submission, String userId)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
context.put("item", assignmentActivityProducer
.getItem(submission, userId));
}
private ContentReviewService contentReviewService;
public String getReportURL(Long score) {
getContentReviewService();
return contentReviewService.getIconUrlforScore(score);
}
private void getContentReviewService() {
if (contentReviewService == null)
{
contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName());
}
}
/******************* model answer *********/
/**
* add model answer input into state variables
*/
public void doModel_answer(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String text = StringUtil.trimToNull(params.get("modelanswer_text"));
if (text == null)
{
// no text entered for model answer
addAlert(state, rb.getString("modelAnswer.show_to_student.alert.noText"));
}
int showTo = params.getInt("modelanswer_showto");
if (showTo == 0)
{
// no show to criteria specifided for model answer
addAlert(state, rb.getString("modelAnswer.show_to_student.alert.noShowTo"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER, Boolean.TRUE);
state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER_TEXT, text);
state.setAttribute(NEW_ASSIGNMENT_MODEL_SHOW_TO_STUDENT, showTo);
//state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER_ATTACHMENT);
}
}
private void assignment_resubmission_option_into_context(Context context, SessionState state)
{
context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null ? (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) : null;
String allowResubmitTimeString = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME) != null ? (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME) : null;
// the resubmit number
if (allowResubmitNumber != null && !"0".equals(allowResubmitNumber))
{
context.put("value_allowResubmitNumber", Integer.valueOf(allowResubmitNumber));
context.put("resubmitNumber", "-1".equals(allowResubmitNumber) ? rb.getString("allow.resubmit.number.unlimited"): allowResubmitNumber);
// put allow resubmit time information into context
putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
// resubmit close time
Time resubmitCloseTime = null;
if (allowResubmitTimeString != null)
{
resubmitCloseTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString));
}
// put into context
if (resubmitCloseTime != null)
{
context.put("resubmitCloseTime", resubmitCloseTime.toStringLocalFull());
}
}
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
}
private void assignment_resubmission_option_into_state(Assignment a, AssignmentSubmission s, SessionState state)
{
String allowResubmitNumber = null;
String allowResubmitTimeString = null;
if (s != null)
{
// if submission is present, get the resubmission values from submission object first
ResourceProperties sProperties = s.getProperties();
allowResubmitNumber = sProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
allowResubmitTimeString = sProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
else if (a != null)
{
// otherwise, if assignment is present, get the resubmission values from assignment object next
ResourceProperties aProperties = a.getProperties();
allowResubmitNumber = aProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
allowResubmitTimeString = aProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
if (StringUtil.trimToNull(allowResubmitNumber) != null)
{
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber);
}
else
{
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
if (allowResubmitTimeString == null)
{
// default setting
allowResubmitTimeString = String.valueOf(a.getCloseTime().getTime());
}
Time allowResubmitTime = null;
if (allowResubmitTimeString != null)
{
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, allowResubmitTimeString);
// get time object
allowResubmitTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString));
}
else
{
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
if (allowResubmitTime != null)
{
// set up related state variables
putTimePropertiesInState(state, allowResubmitTime, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
}
}
/**
* save the resubmit option for selected users
* @param data
*/
public void doSave_resubmission_option(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// read in user input into state variable
if (StringUtil.trimToNull(params.getString("allowResToggle")) != null)
{
if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// read in allowResubmit params
readAllowResubmitParams(params, state, null);
}
}
else
{
resetAllowResubmitParams(state);
}
String[] userIds = params.getStrings("selectedAllowResubmit");
if (userIds == null || userIds.length == 0)
{
addAlert(state, rb.getString("allowResubmission.nouser"));
}
else
{
for (int i = 0; i < userIds.length; i++)
{
String userId = userIds[i];
try
{
User u = UserDirectoryService.getUser(userId);
String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
AssignmentSubmission submission = getSubmission(assignmentRef, u, "doSave_resubmission_option", state);
if (submission != null)
{
AssignmentSubmissionEdit submissionEdit = editSubmission(submission.getReference(), "doSave_resubmission_option", state);
if (submissionEdit != null)
{
// get resubmit number
ResourcePropertiesEdit pEdit = submissionEdit.getPropertiesEdit();
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null)
{
// get resubmit time
Time closeTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM);
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
}
else
{
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
// save
AssignmentService.commitEdit(submissionEdit);
}
}
}
catch (Exception userException)
{
M_log.warn(this + ":doSave_resubmission_option error getting user with id " + userId + " " + userException.getMessage());
}
}
}
// make sure the options are exposed in UI
state.setAttribute(SHOW_ALLOW_RESUBMISSION, Boolean.TRUE);
}
/**
* upload local file for attachment
* @param data
* @param singleFileUpload
*/
public void doAttachUpload(RunData data, boolean singleFileUpload)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ToolSession toolSession = SessionManager.getCurrentToolSession();
ParameterParser params = data.getParameters ();
String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1");
long max_bytes = 1024L * 1024L;
try
{
max_bytes = Long.parseLong(max_file_size_mb) * 1024L * 1024L;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024L * 1024L;
}
int submissionFileCount = 0;
String submissionFileCountString = params.getString("submissionFileCount");
if (params.getString("submissionFileCount") != null)
{
try
{
submissionFileCount = Integer.valueOf(params.getString("submissionFileCount"));
}
catch (NumberFormatException e)
{
M_log.warn(this + ".doAttachUpload: NumberFormatException " + params.getString("submissionFileCount"));
}
}
// construct the state variable for attachment list
List attachments = state.getAttribute(ATTACHMENTS) != null? (List) state.getAttribute(ATTACHMENTS) : EntityManager.newReferenceList();
for (int i = 0; i<submissionFileCount; i++)
{
FileItem fileitem = null;
try
{
fileitem = params.getFileItem("upload" + i);
}
catch(Exception e)
{
}
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_file_size_mb }));
//addAlert(state, hrb.getString("size") + " " + max_file_size_mb + "MB " + hrb.getString("exceeded2"));
}
else if (singleFileUpload && (fileitem.getFileName() == null || fileitem.getFileName().length() == 0))
{
// only if in the single file upload case, need to warn user to upload a local file
addAlert(state, rb.getString("choosefile7"));
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
InputStream fileContentStream = fileitem.getInputStream();
int contentLength = data.getRequest().getContentLength();
String contentType = fileitem.getContentType();
if(contentLength >= max_bytes)
{
addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_file_size_mb }));
// addAlert(state, hrb.getString("size") + " " + max_file_size_mb + "MB " + hrb.getString("exceeded2"));
}
else if(fileContentStream != null)
{
// we just want the file name part - strip off any drive and path stuff
String name = Validator.getFileName(filename);
String resourceId = Validator.escapeResourceName(name);
// make a set of properties to add for the new resource
ResourcePropertiesEdit props = m_contentHostingService.newResourceProperties();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
props.addProperty(ResourceProperties.PROP_DESCRIPTION, filename);
// make an attachment resource for this URL
try
{
String siteId = ToolManager.getCurrentPlacement().getContext();
// add attachment
enableSecurityAdvisor();
ContentResource attachment = m_contentHostingService.addAttachmentResource(resourceId, siteId, "Assignments", contentType, fileContentStream, props);
disableSecurityAdvisor();
try
{
Reference ref = EntityManager.newReference(m_contentHostingService.getReference(attachment.getId()));
attachments.add(ref);
}
catch(Exception ee)
{
M_log.warn(this + "doAttachUpload cannot find reference for " + attachment.getId() + ee.getMessage());
}
state.setAttribute(ATTACHMENTS, attachments);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(RuntimeException e)
{
if(m_contentHostingService.ID_LENGTH_EXCEPTION.equals(e.getMessage()))
{
// couldn't we just truncate the resource-id instead of rejecting the upload?
addAlert(state, rb.getFormattedMessage("alert.toolong", new String[]{name}));
}
else
{
M_log.debug(this + ".doAttachupload ***** Runtime Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
}
catch(Exception ignore)
{
// other exceptions should be caught earlier
M_log.debug(this + ".doAttachupload ***** Unknown Exception ***** " + ignore.getMessage());
}
}
else
{
addAlert(state, rb.getString("choosefile7"));
}
}
}
} // doAttachupload
/**
* Simply take as much as possible out of 'in', and write it to 'out'. Don't
* close the streams, just transfer the data.
*
* @param in
* The data provider
* @param out
* The data output
* @throws IOException
* Thrown if there is an IOException transfering the data
*/
private void writeToStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[INPUT_BUFFER_SIZE];
try {
while (in.read(buffer) > 0) {
out.write(buffer);
}
} catch (IOException e) {
throw e;
}
}
/**
* remove recent added security advisor
*/
protected void disableSecurityAdvisor()
{
// remove recent added security advisor
SecurityService.popAdvisor();
}
/**
* Establish a security advisor to allow the "embedded" azg work to occur
* with no need for additional security permissions.
*/
protected void enableSecurityAdvisor()
{
// put in a security advisor so we can create citationAdmin site without need
// of further permissions
SecurityService.pushAdvisor(new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
return SecurityAdvice.ALLOWED;
}
});
}
/**
* Categories are represented as Integers. Right now this feature only will
* be active for new assignments, so we'll just always return 0 for the
* unassigned category. In the future we may (or not) want to update this
* to return categories for existing gradebook items.
* @param assignment
* @return
*/
private int getAssignmentCategoryAsInt(Assignment assignment) {
int categoryAsInt;
categoryAsInt = 0; // zero for unassigned
return categoryAsInt;
}
}
| SAK-18237
fix a problem of passing AssignmentContent id instead of reference String, that generated false alert message in the
git-svn-id: d213257099f21e50eb3b4c197ffbeb2264dc0174@75694 66ffb92e-73f9-0310-93c1-f5514f145a0a
| assignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java | SAK-18237 fix a problem of passing AssignmentContent id instead of reference String, that generated false alert message in the | <ide><path>ssignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
<ide> AssignmentEdit aEdit = editAssignment(assignmentId, "doDelete_assignment", state, false);
<ide> if (aEdit != null)
<ide> {
<add> if (state.getAttribute(STATE_MESSAGE) == null)
<add> {
<ide> ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit();
<ide>
<ide> String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
<ide>
<add> if (state.getAttribute(STATE_MESSAGE) == null)
<add> {
<ide> String title = aEdit.getTitle();
<ide>
<ide> // remove related event if there is one
<ide> removeCalendarEvent(state, aEdit, pEdit, title);
<del>
<add> if (state.getAttribute(STATE_MESSAGE) == null)
<add> {
<ide> // remove related announcement if there is one
<ide> removeAnnouncement(state, pEdit);
<del>
<add> if (state.getAttribute(STATE_MESSAGE) == null)
<add> {
<ide> // we use to check "assignment.delete.cascade.submission" setting. But the implementation now is always remove submission objects when the assignment is removed.
<ide> // delete assignment and its submissions altogether
<ide> deleteAssignmentObjects(state, aEdit, true);
<del>
<add> if (state.getAttribute(STATE_MESSAGE) == null)
<add> {
<ide> // remove from Gradebook
<ide> integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null, -1);
<add> }
<add> }
<add> }
<add> }
<add> }
<ide> }
<ide> } // for
<ide>
<ide> {
<ide>
<ide> // remove the assignment content
<del> AssignmentContentEdit acEdit = editAssignmentContent(aContent.getId(), "deleteAssignmentObjects", state, false);
<add> AssignmentContentEdit acEdit = editAssignmentContent(aContent.getReference(), "deleteAssignmentObjects", state, false);
<ide> if (acEdit != null)
<ide> AssignmentService.removeAssignmentContent(acEdit);
<ide> } |
|
Java | apache-2.0 | 6f543e5ba1f42b4340c064e8e9b37181956cf965 | 0 | splunk/splunk-sdk-java,splunk/splunk-sdk-java,splunk/splunk-sdk-java,splunk/splunk-sdk-java,splunk/splunk-sdk-java,splunk/splunk-sdk-java | /*
* Copyright 2011 Splunk, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"): you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.splunk;
import org.junit.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
public class UploadTest extends SDKTestCase {
@Test
public void testOneshot() throws IOException {
String filename = locateSystemLog();
if (System.getenv("TRAVIS_CI") != null) {
File tempfile = File.createTempFile((new Date()).toString(), "");
tempfile.deleteOnExit();
FileWriter f = new FileWriter(tempfile, true);
f.append("some data here");
filename = tempfile.getAbsolutePath();
}
else if (System.getenv("SPLUNK_HOME") != null) {
filename = System.getenv("SPLUNK_HOME") + "/var/log/splunk/splunkd.log";
}
service.getUploads().create(filename);
for (Upload oneshot : service.getUploads().values()) {
oneshot.getBytesIndexed();
oneshot.getOffset();
oneshot.getSize();
oneshot.getSize();
oneshot.getSourcesIndexed();
oneshot.getSpoolTime();
}
}
}
| tests/com/splunk/UploadTest.java | /*
* Copyright 2011 Splunk, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"): you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.splunk;
import org.junit.Test;
public class UploadTest extends SDKTestCase {
@Test
public void testOneshot() throws InterruptedException {
// Slow down for CI to wait for splunkd.log to exist
Thread.sleep(8000);
String filename = locateSystemLog();
if (System.getenv("SPLUNK_HOME") != null) {
filename = System.getenv("SPLUNK_HOME") + "/var/log/splunk/splunkd.log";
}
service.getUploads().create(filename);
for (Upload oneshot : service.getUploads().values()) {
oneshot.getBytesIndexed();
oneshot.getOffset();
oneshot.getSize();
oneshot.getSize();
oneshot.getSourcesIndexed();
oneshot.getSpoolTime();
}
}
}
| fix uploadtest
| tests/com/splunk/UploadTest.java | fix uploadtest | <ide><path>ests/com/splunk/UploadTest.java
<ide>
<ide> import org.junit.Test;
<ide>
<add>import java.io.File;
<add>import java.io.FileWriter;
<add>import java.io.IOException;
<add>import java.util.Date;
<add>
<ide> public class UploadTest extends SDKTestCase {
<ide> @Test
<del> public void testOneshot() throws InterruptedException {
<del> // Slow down for CI to wait for splunkd.log to exist
<del> Thread.sleep(8000);
<add> public void testOneshot() throws IOException {
<add> String filename = locateSystemLog();
<add> if (System.getenv("TRAVIS_CI") != null) {
<add> File tempfile = File.createTempFile((new Date()).toString(), "");
<add> tempfile.deleteOnExit();
<ide>
<del> String filename = locateSystemLog();
<del> if (System.getenv("SPLUNK_HOME") != null) {
<add> FileWriter f = new FileWriter(tempfile, true);
<add> f.append("some data here");
<add>
<add> filename = tempfile.getAbsolutePath();
<add> }
<add> else if (System.getenv("SPLUNK_HOME") != null) {
<ide> filename = System.getenv("SPLUNK_HOME") + "/var/log/splunk/splunkd.log";
<ide> }
<del>
<ide> service.getUploads().create(filename);
<ide>
<ide> for (Upload oneshot : service.getUploads().values()) { |
|
Java | apache-2.0 | ade9d2a6aad835c06713fa2ef3f319b2f890f78e | 0 | XRacoon/robotiumEx,Eva1123/robotium,hypest/robotium,lczgywzyy/robotium,NetEase/robotium,zhic5352/robotium,darker50/robotium,lczgywzyy/robotium,activars/remote-robotium,RobotiumTech/robotium,NetEase/robotium,XRacoon/robotiumEx,pefilekill/robotiumCode,acanta2014/robotium,MattGong/robotium,shibenli/robotium,pefilekill/robotiumCode,shibenli/robotium,SinnerSchraderMobileMirrors/robotium,hypest/robotium,lgs3137/robotium,zhic5352/robotium,darker50/robotium,acanta2014/robotium,luohaoyu/robotium,Eva1123/robotium,lgs3137/robotium,MattGong/robotium,RobotiumTech/robotium,luohaoyu/robotium | package com.jayway.android.robotium.solo;
import android.app.Instrumentation;
import android.view.KeyEvent;
/**
* This class contains press methods. Examples are pressMenuItem(),
* pressSpinnerItem().
*
* @author Renas Reda, [email protected]
*
*/
class Presser{
private final ViewFetcher soloView;
private final Clicker soloClick;
private final Instrumentation inst;
/**
* Constructs this object.
*
* @param soloView the {@link ViewFetcher} instance.
* @param soloClick the {@link Clicker} instance.
* @param inst the {@link Instrumentation} instance.
*/
public Presser(ViewFetcher soloView, Clicker soloClick, Instrumentation inst) {
this.soloView = soloView;
this.soloClick = soloClick;
this.inst = inst;
}
/**
* Method used to press a MenuItem with a certain index. Index 0 is the first item in the
* first row and index 3 is the first item in the second row.
*
* @param index the index of the menu item to be pressed
*
*/
public void pressMenuItem(int index) {
inst.waitForIdleSync();
RobotiumUtils.sleep(500);
try{
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
RobotiumUtils.sleep(300);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_UP);
}catch(Throwable e)
{
e.printStackTrace();
}
if (index < 3) {
for (int i = 0; i < index; i++) {
RobotiumUtils.sleep(300);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT);
}
} else
{
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
for (int i = 3; i < index; i++) {
RobotiumUtils.sleep(300);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT);
}
}
try{
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);
}catch (Throwable e) {
e.printStackTrace();
}
}
/**
* Method used to press on a spinner (drop-down menu) item.
*
* @param spinnerIndex the index of the spinner menu to be used
* @param itemIndex the index of the spinner item to be pressed
*
*/
public void pressSpinnerItem(int spinnerIndex, int itemIndex)
{
inst.waitForIdleSync();
RobotiumUtils.sleep(500);
soloClick.clickOnScreen(soloView.getCurrentSpinners().get(spinnerIndex));
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
for(int i = 0; i < itemIndex; i++)
{
RobotiumUtils.sleep(300);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
}
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);
}
}
| robotium-solo/src/main/java/com/jayway/android/robotium/solo/Presser.java | package com.jayway.android.robotium.solo;
import android.app.Instrumentation;
import android.view.KeyEvent;
/**
* This class contains press methods. Examples are pressMenuItem(),
* pressSpinnerItem().
*
* @author Renas Reda, [email protected]
*
*/
class Presser{
private final ViewFetcher soloView;
private final Clicker soloClick;
private final Instrumentation inst;
/**
* Constructs this object.
*
* @param soloView the {@link ViewFetcher} instance.
* @param soloClick the {@link Clicker} instance.
* @param inst the {@link Instrumentation} instance.
*/
public Presser(ViewFetcher soloView, Clicker soloClick, Instrumentation inst) {
this.soloView = soloView;
this.soloClick = soloClick;
this.inst = inst;
}
/**
* Method used to press a MenuItem with a certain index. Index 0 is the first item in the
* first row and index 3 is the first item in the second row.
*
* @param index the index of the menu item to be pressed
*
*/
public void pressMenuItem(int index) {
inst.waitForIdleSync();
try{
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
RobotiumUtils.sleep(300);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_UP);
}catch(Throwable e)
{
e.printStackTrace();
}
if (index < 3) {
for (int i = 0; i < index; i++) {
RobotiumUtils.sleep(300);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT);
}
} else
{
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
for (int i = 3; i < index; i++) {
RobotiumUtils.sleep(300);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT);
}
}
try{
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);
}catch (Throwable e) {
e.printStackTrace();
}
}
/**
* Method used to press on a spinner (drop-down menu) item.
*
* @param spinnerIndex the index of the spinner menu to be used
* @param itemIndex the index of the spinner item to be pressed
*
*/
public void pressSpinnerItem(int spinnerIndex, int itemIndex)
{
inst.waitForIdleSync();
soloClick.clickOnScreen(soloView.getCurrentSpinners().get(spinnerIndex));
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
for(int i = 0; i < itemIndex; i++)
{
RobotiumUtils.sleep(300);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
}
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);
}
}
| The presser methods some times are to quick in their execution and therefore a small slow down is needed.
| robotium-solo/src/main/java/com/jayway/android/robotium/solo/Presser.java | The presser methods some times are to quick in their execution and therefore a small slow down is needed. | <ide><path>obotium-solo/src/main/java/com/jayway/android/robotium/solo/Presser.java
<ide>
<ide> public void pressMenuItem(int index) {
<ide> inst.waitForIdleSync();
<add> RobotiumUtils.sleep(500);
<ide> try{
<ide> inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
<ide> RobotiumUtils.sleep(300);
<ide> public void pressSpinnerItem(int spinnerIndex, int itemIndex)
<ide> {
<ide> inst.waitForIdleSync();
<add> RobotiumUtils.sleep(500);
<ide> soloClick.clickOnScreen(soloView.getCurrentSpinners().get(spinnerIndex));
<ide> inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
<ide> for(int i = 0; i < itemIndex; i++) |
|
JavaScript | bsd-3-clause | 78a93698ca558f96e0ba45b7dedde264147bb934 | 0 | shankari/e-mission-phone,e-mission/e-mission-phone,shankari/e-mission-phone,e-mission/e-mission-phone,shankari/e-mission-phone,e-mission/e-mission-phone,shankari/e-mission-phone,e-mission/e-mission-phone | 'use strict';
angular.module('emission.survey.external.launch', ['emission.services',
'emission.plugin.logger',
'emission.stats.clientstats'])
.factory('SurveyLaunch', function($http, $window, $ionicPopup, $rootScope,
CommHelper, Logger) {
var surveylaunch = {};
var replace_uuid= function(iab, elementSelector, scriptFile) {
return Promise.all([$http.get(scriptFile),
CommHelper.getUser()])
.then(function([scriptText, userProfile]) {
// alert("finished loading script");
Logger.log(scriptText.data);
var uuid = userProfile.user_id['$uuid']
// I tried to use http://stackoverflow.com/posts/23387583/revisions
// for the idea on how to invoke the function in the script
// file, but the callback function was never invoked. So I edit the
// script file directly and insert the userId.
Logger.log("inserting user id into survey. userId = "+ uuid
+" element selector = "+elementSelector);
var codeTemplate = scriptText.data;
var codeString = codeTemplate.replace("SCRIPT_REPLACE_VALUE", uuid)
.replace("SCRIPT_REPLACE_ELEMENT_SEL", elementSelector);
Logger.log(codeString);
return iab.executeScript({ code: codeString });
});
};
var replace_time = function(iab, tsElementId, fmtTimeElementId, ts, label) {
// we don't need to get the user because we have the timestamp right here
return Promise.all([$http.get("js/survey/time_insert.js")])
.then(function([scriptText]) {
// alert("finished loading script");
Logger.log(scriptText.data);
// I tried to use http://stackoverflow.com/posts/23387583/revisions
// for the idea on how to invoke the function in the script
// file, but the callback function was never invoked. So I edit the
// script file directly and insert the userId.
Logger.log("inserting ts into survey. ts = "+ ts
+" element id = "+tsElementId
+" fmtTime"+moment.unix(ts).format()
+" element id = "+fmtTimeElementId);
var codeTemplate = scriptText.data;
var tsCodeString = codeTemplate.replace("SCRIPT_REPLACE_VALUE", ts)
.replace("SCRIPT_REPLACE_ELEMENT_ID", tsElementId)
.replace(/LABEL/g, label+"Ts");
Logger.log("After ts replace" + tsCodeString);
$cordovaInAppBrowser.executeScript({ code: tsCodeString });
var fmtTimeCodeString = codeTemplate.replace("SCRIPT_REPLACE_VALUE", moment.unix(ts).format())
.replace("SCRIPT_REPLACE_ELEMENT_ID", fmtTimeElementId)
.replace(/LABEL/g, label+"FmtTime");
Logger.log("After fmtTimeCode replace" + tsCodeString);
iab.executeScript({ code: fmtTimeCodeString });
});
};
// BEGIN: startSurveyForCompletedTrip
// Put the launch in one place so that
surveylaunch.options = "location=yes,clearcache=no,toolbar=yes,hideurlbar=yes";
/*
surveylaunch.options = {
location: window.cordova.platformId == 'ios'? 'no' : 'yes',
clearcache: 'no',
toolbar: 'yes',
hideurlbar: 'yes'
};
*/
surveylaunch.startSurveyForCompletedTrip = function (url, uuidElementId,
startTsElementId,
endTsElementId,
startFmtTimeElementId,
endFmtTimeElementId,
startTs,
endTs) {
// THIS LINE FOR inAppBrowser
let iab = $window.cordova.InAppBrowser.open(url, '_blank', surveylaunch.options);
iab.addEventListener("loadstop", function(event) {
console.log("successfully opened page with result "+JSON.stringify(event));
// success
Promise.all([replace_uuid(iab, uuidElementId, "js/survey/uuid_insert.js"),
replace_time(iab, startTsElementId, startFmtTimeElementId, startTs, "Start"),
replace_time(iab, endTsElementId, endFmtTimeElementId, endTs, "End")])
.catch(function(error) { // catch for all promises
$ionicPopup.alert({"template": "Relaunching survey - while replacing uuid, got error "+ JSON.stringify(error)})
.then(function() {
surveylaunch.startSurvey(url, uuidElementId,
startTsElementId, endTsElementId,
startFmtTimeElementId, endTsElementId,
startTs, endTs);
});
});
})
iab.addEventListener('loaderror', function(event) {
Logger.displayError("Unable to launch survey", JSON.stringify(event));
});
iab.addEventListener('loadstart', function(event) {
console.log("started loading, event = "+JSON.stringify(event));
/*
if (event.url == 'https://bic2cal.eecs.berkeley.edu/') {
$cordovaInAppBrowser.close();
}
*/
});
iab.addEventListener('exit', function(event) {
console.log("exiting, event = "+JSON.stringify(event));
// we could potentially restore the close-on-bic2cal functionality above
// if we unregistered here
});
}
// END: startSurveyForCompletedTrip
var startSurveyCommon = function (url, elementSelector, elementSelScriptFile) {
// THIS LINE FOR inAppBrowser
let iab = $window.cordova.InAppBrowser.open(url, '_blank', surveylaunch.options);
iab.addEventListener("loadstop", function(event) {
console.log("successfully opened page with result "+JSON.stringify(event));
// success
replace_uuid(iab, elementSelector, elementSelScriptFile)
.catch(function(error) {
iab.close();
$ionicPopup.alert({"template": "Relaunching survey - while replacing uuid, got error "+ error})
.then(function() {
startSurveyCommon(url,elementSelector, elementSelScriptFile);
});
});
});
iab.addEventListener('loaderror', function(event) {
Logger.displayError("Unable to launch survey", event);
});
iab.addEventListener("loadstart", function(event) {
console.log("started loading, event = "+JSON.stringify(event));
/*
if (event.url == 'https://bic2cal.eecs.berkeley.edu/') {
$cordovaInAppBrowser.close();
}
*/
});
iab.addEventListener('exit', function(event) {
console.log("exiting, event = "+JSON.stringify(event));
// we could potentially restore the close-on-bic2cal functionality above
// if we unregistered here
});
};
surveylaunch.startSurveyWithID = function (url, uuidElementId) {
startSurveyCommon(url, uuidElementId, "js/survey/uuid_insert_id.js");
}
surveylaunch.startSurveyWithXPath = function (url, elementXPath) {
startSurveyCommon(url, elementXPath, "js/survey/uuid_insert_xpath.js");
}
/**
* startSurveyPrefilled start the survey and prefill the UUID field.
* @param {string} url survey url
* @param {{
* uuidSearchParam: string
* returnURLSearchParam: string
* returnURL: string
* autoCloseURL: string
* }} [opts] options
*/
surveylaunch.startSurveyPrefilled = function (url, opts = {}) {
opts = Object.assign({
uuidSearchParam: 'uuid',
returnURLSearchParam: 'return_url',
returnURL: '',
autoCloseURL: undefined,
}, opts);
return CommHelper.getUser().then(function(userProfile) {
// alert("finished loading script");
let uuid = userProfile.user_id['$uuid']
Logger.log("inserting user id into survey. userId = "+ uuid
+" base url = "+url);
const urlObj = new URL(url);
urlObj.searchParams.append(opts.returnURLSearchParam, encodeURIComponent(opts.returnURL));
urlObj.searchParams.append(opts.uuidSearchParam, uuid);
const modifiedURL = urlObj.toString();
Logger.log("modified URL = "+modifiedURL);
let iab = $window.cordova.InAppBrowser.open(modifiedURL, '_blank', surveylaunch.options);
iab.addEventListener('loaderror', function(event) {
Logger.displayError("Unable to launch survey", event);
return Promise.reject();
});
if (opts.autoCloseURL) {
return new Promise((resolve, reject) => {
const autoClose = function(event) {
console.log("started loading, event = " + JSON.stringify(event));
if (opts.autoCloseURL.includes(event.url)) {
iab.removeEventListener('loadstart', autoClose);
iab.close();
return resolve();
}
};
iab.addEventListener('loadstart', autoClose);
});
}
return Promise.resolve();
});
}
surveylaunch.init = function() {
$rootScope.$on('cloud:push:notification', function(event, data) {
ClientStats.addEvent(ClientStats.getStatKeys().NOTIFICATION_OPEN).then(
function() {
console.log("Added "+ClientStats.getStatKeys().NOTIFICATION_OPEN+" event. Data = " + JSON.stringify(data));
});
Logger.log("data = "+JSON.stringify(data));
if (angular.isDefined(data.additionalData) &&
angular.isDefined(data.additionalData.payload) &&
angular.isDefined(data.additionalData.payload.alert_type) &&
data.additionalData.payload.alert_type == "survey") {
var survey_spec = data.additionalData.payload.spec;
if (angular.isDefined(survey_spec) &&
angular.isDefined(survey_spec.url)) {
if (angular.isDefined(survey_spec.uuidElementId)) {
surveylaunch.startSurveyWithID(survey_spec.url, survey_spec.uuidElementId);
} else if (angular.isDefined(survey_spec.uuidXPath)) {
surveylaunch.startSurveyWithXPath(survey_spec.url, survey_spec.uuidXPath);
} else if (angular.isDefined(survey_spec.uuidSearchParam)) {
surveylaunch.startSurveyPrefilled(survey_spec.url, {
uuidSearchParam: survey_spec.uuidSearchParam
});
} else {
$ionicPopup.alert("survey was not specified correctly. spec is "+JSON.stringify(survey_spec));
}
} else {
$ionicPopup.alert("survey was not specified correctly. spec is "+JSON.stringify(survey_spec));
}
}
});
};
surveylaunch.init();
return surveylaunch;
});
| www/js/survey/external/launch.js | 'use strict';
angular.module('emission.survey.external.launch', ['emission.services',
'emission.plugin.logger',
'emission.stats.clientstats'])
.factory('SurveyLaunch', function($http, $window, $ionicPopup, $rootScope,
CommHelper, Logger) {
var surveylaunch = {};
var replace_uuid= function(iab, elementSelector, scriptFile) {
return Promise.all([$http.get(scriptFile),
CommHelper.getUser()])
.then(function([scriptText, userProfile]) {
// alert("finished loading script");
Logger.log(scriptText.data);
var uuid = userProfile.user_id['$uuid']
// I tried to use http://stackoverflow.com/posts/23387583/revisions
// for the idea on how to invoke the function in the script
// file, but the callback function was never invoked. So I edit the
// script file directly and insert the userId.
Logger.log("inserting user id into survey. userId = "+ uuid
+" element selector = "+elementSelector);
var codeTemplate = scriptText.data;
var codeString = codeTemplate.replace("SCRIPT_REPLACE_VALUE", uuid)
.replace("SCRIPT_REPLACE_ELEMENT_SEL", elementSelector);
Logger.log(codeString);
return iab.executeScript({ code: codeString });
});
};
var replace_time = function(iab, tsElementId, fmtTimeElementId, ts, label) {
// we don't need to get the user because we have the timestamp right here
return Promise.all([$http.get("js/survey/time_insert.js")])
.then(function([scriptText]) {
// alert("finished loading script");
Logger.log(scriptText.data);
// I tried to use http://stackoverflow.com/posts/23387583/revisions
// for the idea on how to invoke the function in the script
// file, but the callback function was never invoked. So I edit the
// script file directly and insert the userId.
Logger.log("inserting ts into survey. ts = "+ ts
+" element id = "+tsElementId
+" fmtTime"+moment.unix(ts).format()
+" element id = "+fmtTimeElementId);
var codeTemplate = scriptText.data;
var tsCodeString = codeTemplate.replace("SCRIPT_REPLACE_VALUE", ts)
.replace("SCRIPT_REPLACE_ELEMENT_ID", tsElementId)
.replace(/LABEL/g, label+"Ts");
Logger.log("After ts replace" + tsCodeString);
$cordovaInAppBrowser.executeScript({ code: tsCodeString });
var fmtTimeCodeString = codeTemplate.replace("SCRIPT_REPLACE_VALUE", moment.unix(ts).format())
.replace("SCRIPT_REPLACE_ELEMENT_ID", fmtTimeElementId)
.replace(/LABEL/g, label+"FmtTime");
Logger.log("After fmtTimeCode replace" + tsCodeString);
iab.executeScript({ code: fmtTimeCodeString });
});
};
// BEGIN: startSurveyForCompletedTrip
// Put the launch in one place so that
surveylaunch.options = "location=yes,clearcache=no,toolbar=yes,hideurlbar=yes";
/*
surveylaunch.options = {
location: window.cordova.platformId == 'ios'? 'no' : 'yes',
clearcache: 'no',
toolbar: 'yes',
hideurlbar: 'yes'
};
*/
surveylaunch.startSurveyForCompletedTrip = function (url, uuidElementId,
startTsElementId,
endTsElementId,
startFmtTimeElementId,
endFmtTimeElementId,
startTs,
endTs) {
// THIS LINE FOR inAppBrowser
let iab = $window.cordova.InAppBrowser.open(url, '_blank', surveylaunch.options);
iab.addEventListener("loadstop", function(event) {
console.log("successfully opened page with result "+JSON.stringify(event));
// success
Promise.all([replace_uuid(iab, uuidElementId, "js/survey/uuid_insert.js"),
replace_time(iab, startTsElementId, startFmtTimeElementId, startTs, "Start"),
replace_time(iab, endTsElementId, endFmtTimeElementId, endTs, "End")])
.catch(function(error) { // catch for all promises
$ionicPopup.alert({"template": "Relaunching survey - while replacing uuid, got error "+ JSON.stringify(error)})
.then(function() {
surveylaunch.startSurvey(url, uuidElementId,
startTsElementId, endTsElementId,
startFmtTimeElementId, endTsElementId,
startTs, endTs);
});
});
})
iab.addEventListener('loaderror', function(event) {
Logger.displayError("Unable to launch survey", JSON.stringify(event));
});
iab.addEventListener('loadstart', function(event) {
console.log("started loading, event = "+JSON.stringify(event));
/*
if (event.url == 'https://bic2cal.eecs.berkeley.edu/') {
$cordovaInAppBrowser.close();
}
*/
});
iab.addEventListener('exit', function(event) {
console.log("exiting, event = "+JSON.stringify(event));
// we could potentially restore the close-on-bic2cal functionality above
// if we unregistered here
});
}
// END: startSurveyForCompletedTrip
var startSurveyCommon = function (url, elementSelector, elementSelScriptFile) {
// THIS LINE FOR inAppBrowser
let iab = $window.cordova.InAppBrowser.open(url, '_blank', surveylaunch.options);
iab.addEventListener("loadstop", function(event) {
console.log("successfully opened page with result "+JSON.stringify(event));
// success
replace_uuid(iab, elementSelector, elementSelScriptFile)
.catch(function(error) {
iab.close();
$ionicPopup.alert({"template": "Relaunching survey - while replacing uuid, got error "+ error})
.then(function() {
startSurveyCommon(url,elementSelector, elementSelScriptFile);
});
});
});
iab.addEventListener('loaderror', function(event) {
Logger.displayError("Unable to launch survey", event);
});
iab.addEventListener("loadstart", function(event) {
console.log("started loading, event = "+JSON.stringify(event));
/*
if (event.url == 'https://bic2cal.eecs.berkeley.edu/') {
$cordovaInAppBrowser.close();
}
*/
});
iab.addEventListener('exit', function(event) {
console.log("exiting, event = "+JSON.stringify(event));
// we could potentially restore the close-on-bic2cal functionality above
// if we unregistered here
});
};
surveylaunch.startSurveyWithID = function (url, uuidElementId) {
startSurveyCommon(url, uuidElementId, "js/survey/uuid_insert_id.js");
}
surveylaunch.startSurveyWithXPath = function (url, elementXPath) {
startSurveyCommon(url, elementXPath, "js/survey/uuid_insert_xpath.js");
}
/**
* startSurveyPrefilled start the survey and prefill the UUID field.
* @param {string} url survey url
* @param {{
* uuidSearchParam: string
* returnURLSearchParam: string
* returnURL: string
* autoCloseURL: string
* }} [opts] options
*/
surveylaunch.startSurveyPrefilled = function (url, opts = {}) {
opts = Object.assign({
uuidSearchParam: 'uuid',
returnURLSearchParam: 'return_url',
returnURL: '',
autoCloseURL: undefined,
}, opts);
return CommHelper.getUser().then(function(userProfile) {
// alert("finished loading script");
let uuid = userProfile.user_id['$uuid']
Logger.log("inserting user id into survey. userId = "+ uuid
+" base url = "+url);
const urlObj = new URL(url);
urlObj.searchParams.append(opts.returnURLSearchParam, encodeURIComponent(opts.returnURL));
urlObj.searchParams.append(opts.uuidSearchParam, uuid);
const modifiedURL = urlObj.toString();
Logger.log("modified URL = "+modifiedURL);
let iab = $window.cordova.InAppBrowser.open(modifiedURL, '_blank', surveylaunch.options);
iab.addEventListener('loaderror', function(event) {
Logger.displayError("Unable to launch survey", event);
return Promise.reject();
});
if (opts.autoCloseURL) {
return new Promise((resolve, reject) => {
const autoClose = function(event) {
console.log("started loading, event = " + JSON.stringify(event));
if (opts.autoCloseURL.includes(event.url)) {
iab.removeEventListener('loadstart', autoClose);
iab.close();
return resolve();
}
};
iab.addEventListener('loadstart', autoClose);
});
}
return Promise.resolve();
});
}
surveylaunch.init = function() {
$rootScope.$on('cloud:push:notification', function(event, data) {
ClientStats.addEvent(ClientStats.getStatKeys().NOTIFICATION_OPEN).then(
function() {
console.log("Added "+ClientStats.getStatKeys().NOTIFICATION_OPEN+" event. Data = " JSON.stringify(data));
});
Logger.log("data = "+JSON.stringify(data));
if (angular.isDefined(data.additionalData) &&
angular.isDefined(data.additionalData.payload) &&
angular.isDefined(data.additionalData.payload.alert_type) &&
data.additionalData.payload.alert_type == "survey") {
var survey_spec = data.additionalData.payload.spec;
if (angular.isDefined(survey_spec) &&
angular.isDefined(survey_spec.url)) {
if (angular.isDefined(survey_spec.uuidElementId)) {
surveylaunch.startSurveyWithID(survey_spec.url, survey_spec.uuidElementId);
} else if (angular.isDefined(survey_spec.uuidXPath)) {
surveylaunch.startSurveyWithXPath(survey_spec.url, survey_spec.uuidXPath);
} else if (angular.isDefined(survey_spec.uuidSearchParam)) {
surveylaunch.startSurveyPrefilled(survey_spec.url, {
uuidSearchParam: survey_spec.uuidSearchParam
});
} else {
$ionicPopup.alert("survey was not specified correctly. spec is "+JSON.stringify(survey_spec));
}
} else {
$ionicPopup.alert("survey was not specified correctly. spec is "+JSON.stringify(survey_spec));
}
}
});
};
surveylaunch.init();
return surveylaunch;
});
| Fix formatting error from previous commit
Previous commit was the cherry-picked
5cd55dd62fd6fd37423e79663adbe946083e1622
| www/js/survey/external/launch.js | Fix formatting error from previous commit | <ide><path>ww/js/survey/external/launch.js
<ide> $rootScope.$on('cloud:push:notification', function(event, data) {
<ide> ClientStats.addEvent(ClientStats.getStatKeys().NOTIFICATION_OPEN).then(
<ide> function() {
<del> console.log("Added "+ClientStats.getStatKeys().NOTIFICATION_OPEN+" event. Data = " JSON.stringify(data));
<add> console.log("Added "+ClientStats.getStatKeys().NOTIFICATION_OPEN+" event. Data = " + JSON.stringify(data));
<ide> });
<ide> Logger.log("data = "+JSON.stringify(data));
<ide> if (angular.isDefined(data.additionalData) && |
|
Java | apache-2.0 | 4af60bc7b3145ef27763af18d7d1298618d88bb3 | 0 | baldimir/optaplanner,gsheldon/optaplanner,bernardator/optaplanner,baldimir/optaplanner,netinept/Court-Scheduler,snurkabill/optaplanner,codeaudit/optaplanner,kunallimaye/optaplanner,oskopek/optaplanner,tkobayas/optaplanner,snurkabill/optaplanner,tkobayas/optaplanner,glamperi/optaplanner,droolsjbpm/optaplanner,netinept/Court-Scheduler,bernardator/optaplanner,oskopek/optaplanner,baldimir/optaplanner,gsheldon/optaplanner,tomasdavidorg/optaplanner,kunallimaye/optaplanner,baldimir/optaplanner,oskopek/optaplanner,tkobayas/optaplanner,elsam/drools-planner-old,netinept/Court-Scheduler,glamperi/optaplanner,droolsjbpm/optaplanner,kunallimaye/optaplanner,gsheldon/optaplanner,gsheldon/optaplanner,oskopek/optaplanner,tkobayas/optaplanner,eshen1991/optaplanner,DieterDePaepe/optaplanner,droolsjbpm/optaplanner,bernardator/optaplanner,codeaudit/optaplanner,tomasdavidorg/optaplanner,tomasdavidorg/optaplanner,codeaudit/optaplanner,DieterDePaepe/optaplanner,eshen1991/optaplanner,snurkabill/optaplanner,glamperi/optaplanner,eshen1991/optaplanner,droolsjbpm/optaplanner,elsam/drools-planner-old,elsam/drools-planner-old | /*
* Copyright 2010 JBoss 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.drools.planner.examples.cloudbalancing.swingui;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.GroupLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.apache.commons.lang.ObjectUtils;
import org.drools.FactHandle;
import org.drools.WorkingMemory;
import org.drools.planner.core.solution.Solution;
import org.drools.planner.core.solver.PlanningFactChange;
import org.drools.planner.examples.cloudbalancing.domain.CloudAssignment;
import org.drools.planner.examples.cloudbalancing.domain.CloudBalance;
import org.drools.planner.examples.cloudbalancing.domain.CloudComputer;
import org.drools.planner.examples.cloudbalancing.solver.move.CloudComputerChangeMove;
import org.drools.planner.examples.common.swingui.SolutionPanel;
/**
* TODO this code is highly unoptimized
*/
public class CloudBalancingPanel extends SolutionPanel {
public static final Color[] PROCESS_COLORS = {
Color.GREEN, Color.YELLOW, Color.BLUE, Color.RED, Color.CYAN, Color.ORANGE, Color.MAGENTA
};
private JPanel computersPanel;
private CloudComputerPanel unassignedPanel;
private Map<CloudComputer, CloudComputerPanel> cloudComputerToPanelMap;
private Map<CloudAssignment, CloudComputerPanel> cloudAssignmentToPanelMap;
public CloudBalancingPanel() {
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
JPanel headerPanel = createHeaderPanel();
JPanel computersPanel = createComputersPanel();
layout.setHorizontalGroup(layout.createParallelGroup()
.addComponent(headerPanel).addComponent(computersPanel));
layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(headerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE)
.addComponent(computersPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE));
}
private JPanel createHeaderPanel() {
JPanel headerPanel = new JPanel(new GridLayout(0, 5));
JLabel emptyLabel = new JLabel("");
headerPanel.add(emptyLabel);
JLabel cpuPowerLabel = new JLabel("CPU power");
headerPanel.add(cpuPowerLabel);
JLabel memoryLabel = new JLabel("Memory");
headerPanel.add(memoryLabel);
JLabel networkBandwidthLabel = new JLabel("Network bandwidth");
headerPanel.add(networkBandwidthLabel);
JLabel costLabel = new JLabel("Cost");
headerPanel.add(costLabel);
return headerPanel;
}
private JPanel createComputersPanel() {
computersPanel = new JPanel(new GridLayout(0, 1));
unassignedPanel = new CloudComputerPanel(this, null);
computersPanel.add(unassignedPanel);
cloudComputerToPanelMap = new LinkedHashMap<CloudComputer, CloudComputerPanel>();
cloudComputerToPanelMap.put(null, unassignedPanel);
cloudAssignmentToPanelMap = new LinkedHashMap<CloudAssignment, CloudComputerPanel>();
return computersPanel;
}
private CloudBalance getCloudBalance() {
return (CloudBalance) solutionBusiness.getSolution();
}
public void resetPanel(Solution solution) {
for (CloudComputerPanel cloudComputerCloudComputerPanel : cloudComputerToPanelMap.values()) {
if (cloudComputerCloudComputerPanel.getCloudComputer() != null) {
computersPanel.remove(cloudComputerCloudComputerPanel);
}
}
cloudComputerToPanelMap.clear();
cloudComputerToPanelMap.put(null, unassignedPanel);
cloudAssignmentToPanelMap.clear();
unassignedPanel.clearCloudAssignments();
updatePanel(solution);
}
@Override
public void updatePanel(Solution solution) {
CloudBalance cloudBalance = (CloudBalance) solution;
Set<CloudComputer> deadCloudComputerSet = new LinkedHashSet<CloudComputer>(cloudComputerToPanelMap.keySet());
deadCloudComputerSet.remove(null);
for (CloudComputer cloudComputer : ((CloudBalance) solution).getCloudComputerList()) {
deadCloudComputerSet.remove(cloudComputer);
CloudComputerPanel cloudComputerPanel = cloudComputerToPanelMap.get(cloudComputer);
if (cloudComputerPanel == null) {
cloudComputerPanel = new CloudComputerPanel(this, cloudComputer);
computersPanel.add(cloudComputerPanel);
cloudComputerToPanelMap.put(cloudComputer, cloudComputerPanel);
}
}
Set<CloudAssignment> deadCloudAssignmentSet = new LinkedHashSet<CloudAssignment>(
cloudAssignmentToPanelMap.keySet());
for (CloudAssignment cloudAssignment : cloudBalance.getCloudAssignmentList()) {
deadCloudAssignmentSet.remove(cloudAssignment);
CloudComputerPanel cloudComputerPanel = cloudAssignmentToPanelMap.get(cloudAssignment);
CloudComputer cloudComputer = cloudAssignment.getCloudComputer();
if (cloudComputerPanel != null
&& !ObjectUtils.equals(cloudComputerPanel.getCloudComputer(), cloudComputer)) {
cloudAssignmentToPanelMap.remove(cloudAssignment);
cloudComputerPanel.removeCloudAssignment(cloudAssignment);
cloudComputerPanel = null;
}
if (cloudComputerPanel == null) {
cloudComputerPanel = cloudComputerToPanelMap.get(cloudComputer);
cloudComputerPanel.addCloudAssignment(cloudAssignment);
cloudAssignmentToPanelMap.put(cloudAssignment, cloudComputerPanel);
}
}
for (CloudAssignment deadCloudAssignment : deadCloudAssignmentSet) {
CloudComputerPanel deadCloudComputerPanel = cloudAssignmentToPanelMap.remove(deadCloudAssignment);
deadCloudComputerPanel.removeCloudAssignment(deadCloudAssignment);
}
for (CloudComputer deadCloudComputer : deadCloudComputerSet) {
CloudComputerPanel deadCloudComputerPanel = cloudComputerToPanelMap.remove(deadCloudComputer);
computersPanel.remove(deadCloudComputerPanel);
}
}
public void deleteComputer(final CloudComputer cloudComputer) {
solutionBusiness.doPlanningFactChange(new PlanningFactChange() {
public void doChange(Solution solution, WorkingMemory workingMemory) {
CloudBalance cloudBalance = (CloudBalance) solution;
for (CloudAssignment cloudAssignment : cloudBalance.getCloudAssignmentList()) {
if (ObjectUtils.equals(cloudAssignment.getCloudComputer(), cloudComputer)) {
FactHandle cloudAssignmentHandle = workingMemory.getFactHandle(cloudAssignment);
cloudAssignment.setCloudComputer(null);
workingMemory.retract(cloudAssignmentHandle);
}
}
for (Iterator<CloudComputer> it = cloudBalance.getCloudComputerList().iterator(); it.hasNext(); ) {
CloudComputer workingCloudComputer = it.next();
if (ObjectUtils.equals(workingCloudComputer, cloudComputer)) {
FactHandle cloudComputerHandle = workingMemory.getFactHandle(workingCloudComputer);
workingMemory.retract(cloudComputerHandle);
it.remove(); // remove from list
break;
}
}
}
});
updatePanel(solutionBusiness.getSolution());
}
private class CloudAssignmentAction extends AbstractAction {
private CloudAssignment cloudAssignment;
public CloudAssignmentAction(CloudAssignment cloudAssignment) {
super("=>");
this.cloudAssignment = cloudAssignment;
}
public void actionPerformed(ActionEvent e) {
List<CloudComputer> cloudComputerList = getCloudBalance().getCloudComputerList();
JComboBox cloudComputerListField = new JComboBox(cloudComputerList.toArray());
cloudComputerListField.setSelectedItem(cloudAssignment.getCloudComputer());
int result = JOptionPane.showConfirmDialog(CloudBalancingPanel.this.getRootPane(), cloudComputerListField,
"Select cloud computer", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
CloudComputer toCloudComputer = (CloudComputer) cloudComputerListField.getSelectedItem();
solutionBusiness.doMove(new CloudComputerChangeMove(cloudAssignment, toCloudComputer));
solverAndPersistenceFrame.resetScreen();
}
}
}
}
| drools-planner-examples/src/main/java/org/drools/planner/examples/cloudbalancing/swingui/CloudBalancingPanel.java | /*
* Copyright 2010 JBoss 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.drools.planner.examples.cloudbalancing.swingui;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.GroupLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.apache.commons.lang.ObjectUtils;
import org.drools.FactHandle;
import org.drools.WorkingMemory;
import org.drools.planner.core.solution.Solution;
import org.drools.planner.core.solver.PlanningFactChange;
import org.drools.planner.examples.cloudbalancing.domain.CloudAssignment;
import org.drools.planner.examples.cloudbalancing.domain.CloudBalance;
import org.drools.planner.examples.cloudbalancing.domain.CloudComputer;
import org.drools.planner.examples.cloudbalancing.solver.move.CloudComputerChangeMove;
import org.drools.planner.examples.common.swingui.SolutionPanel;
/**
* TODO this code is highly unoptimized
*/
public class CloudBalancingPanel extends SolutionPanel {
public static final Color[] PROCESS_COLORS = {
Color.GREEN, Color.YELLOW, Color.BLUE, Color.RED, Color.CYAN, Color.ORANGE, Color.MAGENTA
};
private JPanel computersPanel;
private CloudComputerPanel unassignedPanel;
private Map<CloudComputer, CloudComputerPanel> cloudComputerToPanelMap;
private Map<CloudAssignment, CloudComputerPanel> cloudAssignmentToPanelMap;
public CloudBalancingPanel() {
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
JPanel headerPanel = createHeaderPanel();
JPanel computersPanel = createComputersPanel();
layout.setHorizontalGroup(layout.createParallelGroup()
.addComponent(headerPanel).addComponent(computersPanel));
layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(headerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE)
.addComponent(computersPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE));
}
private JPanel createHeaderPanel() {
JPanel headerPanel = new JPanel(new GridLayout(0, 5));
JLabel emptyLabel = new JLabel("");
headerPanel.add(emptyLabel);
JLabel cpuPowerLabel = new JLabel("CPU power");
headerPanel.add(cpuPowerLabel);
JLabel memoryLabel = new JLabel("Memory");
headerPanel.add(memoryLabel);
JLabel networkBandwidthLabel = new JLabel("Network bandwidth");
headerPanel.add(networkBandwidthLabel);
JLabel costLabel = new JLabel("Cost");
headerPanel.add(costLabel);
return headerPanel;
}
private JPanel createComputersPanel() {
computersPanel = new JPanel(new GridLayout(0, 1));
unassignedPanel = new CloudComputerPanel(this, null);
computersPanel.add(unassignedPanel);
cloudComputerToPanelMap = new LinkedHashMap<CloudComputer, CloudComputerPanel>();
cloudComputerToPanelMap.put(null, unassignedPanel);
cloudAssignmentToPanelMap = new LinkedHashMap<CloudAssignment, CloudComputerPanel>();
return computersPanel;
}
private CloudBalance getCloudBalance() {
return (CloudBalance) solutionBusiness.getSolution();
}
public void resetPanel(Solution solution) {
for (CloudComputerPanel cloudComputerCloudComputerPanel : cloudComputerToPanelMap.values()) {
if (cloudComputerCloudComputerPanel.getCloudComputer() != null) {
computersPanel.remove(cloudComputerCloudComputerPanel);
}
}
cloudComputerToPanelMap.clear();
cloudComputerToPanelMap.put(null, unassignedPanel);
cloudAssignmentToPanelMap.clear();
unassignedPanel.clearCloudAssignments();
updatePanel(solution);
}
@Override
public void updatePanel(Solution solution) {
CloudBalance cloudBalance = (CloudBalance) solution;
Set<CloudComputer> deadCloudComputerSet = new LinkedHashSet<CloudComputer>(cloudComputerToPanelMap.keySet());
deadCloudComputerSet.remove(null);
for (CloudComputer cloudComputer : ((CloudBalance) solution).getCloudComputerList()) {
deadCloudComputerSet.remove(cloudComputer);
CloudComputerPanel cloudComputerPanel = cloudComputerToPanelMap.get(cloudComputer);
if (cloudComputerPanel == null) {
cloudComputerPanel = new CloudComputerPanel(this, cloudComputer);
computersPanel.add(cloudComputerPanel);
cloudComputerToPanelMap.put(cloudComputer, cloudComputerPanel);
}
}
Set<CloudAssignment> deadCloudAssignmentSet = new LinkedHashSet<CloudAssignment>(
cloudAssignmentToPanelMap.keySet());
for (CloudAssignment cloudAssignment : cloudBalance.getCloudAssignmentList()) {
deadCloudAssignmentSet.remove(cloudAssignment);
CloudComputerPanel cloudComputerPanel = cloudAssignmentToPanelMap.get(cloudAssignment);
CloudComputer cloudComputer = cloudAssignment.getCloudComputer();
if (cloudComputerPanel != null
&& !ObjectUtils.equals(cloudComputerPanel.getCloudComputer(), cloudComputer)) {
cloudAssignmentToPanelMap.remove(cloudAssignment);
cloudComputerPanel.removeCloudAssignment(cloudAssignment);
cloudComputerPanel = null;
}
if (cloudComputerPanel == null) {
cloudComputerPanel = cloudComputerToPanelMap.get(cloudComputer);
cloudComputerPanel.addCloudAssignment(cloudAssignment);
cloudAssignmentToPanelMap.put(cloudAssignment, cloudComputerPanel);
}
}
for (CloudAssignment deadCloudAssignment : deadCloudAssignmentSet) {
CloudComputerPanel deadCloudComputerPanel = cloudAssignmentToPanelMap.remove(deadCloudAssignment);
deadCloudComputerPanel.removeCloudAssignment(deadCloudAssignment);
}
for (CloudComputer deadCloudComputer : deadCloudComputerSet) {
CloudComputerPanel deadCloudComputerPanel = cloudComputerToPanelMap.remove(deadCloudComputer);
computersPanel.remove(deadCloudComputerPanel);
}
}
public void deleteComputer(final CloudComputer cloudComputer) {
solutionBusiness.doPlanningFactChange(new PlanningFactChange() {
public void doChange(Solution solution, WorkingMemory workingMemory) {
CloudBalance cloudBalance = (CloudBalance) solution;
for (CloudAssignment cloudAssignment : cloudBalance.getCloudAssignmentList()) {
if (ObjectUtils.equals(cloudAssignment.getCloudComputer(), cloudComputer)) {
FactHandle cloudAssignmentHandle = workingMemory.getFactHandle(cloudAssignment);
cloudAssignment.setCloudComputer(null);
workingMemory.update(cloudAssignmentHandle, cloudAssignment);
}
}
for (Iterator<CloudComputer> it = cloudBalance.getCloudComputerList().iterator(); it.hasNext(); ) {
CloudComputer workingCloudComputer = it.next();
if (ObjectUtils.equals(workingCloudComputer, cloudComputer)) {
FactHandle cloudComputerHandle = workingMemory.getFactHandle(workingCloudComputer);
workingMemory.retract(cloudComputerHandle);
it.remove(); // remove from list
break;
}
}
}
});
updatePanel(solutionBusiness.getSolution());
}
private class CloudAssignmentAction extends AbstractAction {
private CloudAssignment cloudAssignment;
public CloudAssignmentAction(CloudAssignment cloudAssignment) {
super("=>");
this.cloudAssignment = cloudAssignment;
}
public void actionPerformed(ActionEvent e) {
List<CloudComputer> cloudComputerList = getCloudBalance().getCloudComputerList();
JComboBox cloudComputerListField = new JComboBox(cloudComputerList.toArray());
cloudComputerListField.setSelectedItem(cloudAssignment.getCloudComputer());
int result = JOptionPane.showConfirmDialog(CloudBalancingPanel.this.getRootPane(), cloudComputerListField,
"Select cloud computer", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
CloudComputer toCloudComputer = (CloudComputer) cloudComputerListField.getSelectedItem();
solutionBusiness.doMove(new CloudComputerChangeMove(cloudAssignment, toCloudComputer));
solverAndPersistenceFrame.resetScreen();
}
}
}
}
| fix PlanningFactChange
| drools-planner-examples/src/main/java/org/drools/planner/examples/cloudbalancing/swingui/CloudBalancingPanel.java | fix PlanningFactChange | <ide><path>rools-planner-examples/src/main/java/org/drools/planner/examples/cloudbalancing/swingui/CloudBalancingPanel.java
<ide> if (ObjectUtils.equals(cloudAssignment.getCloudComputer(), cloudComputer)) {
<ide> FactHandle cloudAssignmentHandle = workingMemory.getFactHandle(cloudAssignment);
<ide> cloudAssignment.setCloudComputer(null);
<del> workingMemory.update(cloudAssignmentHandle, cloudAssignment);
<add> workingMemory.retract(cloudAssignmentHandle);
<ide> }
<ide> }
<ide> for (Iterator<CloudComputer> it = cloudBalance.getCloudComputerList().iterator(); it.hasNext(); ) { |
|
Java | apache-2.0 | c074b94ea5cf8ba73e5741f7cf555db7fa998131 | 0 | vignesh-iopex/mortar,georgelin422/mortar,xfumihiro/mortar,hejunbinlan/mortar,brunobowden/mortar,square/mortar,venkatesh3007/mortar,Anusha-M/mortar,SpenceAcc/mortar,takn/mortar,DmitriyZaitsev/mortar | package mortar.dagger1support;
import android.app.Activity;
import android.content.Context;
import dagger.ObjectGraph;
import java.util.Collection;
import mortar.MortarScope;
import mortar.bundler.BundleServiceRunner;
/**
* Provides utility methods for using Mortar with Dagger 1.
*/
public class ObjectGraphService {
public static final String SERVICE_NAME = ObjectGraphService.class.getName();
/**
* Create a new {@link ObjectGraph} based on the given module. The new graph will extend
* the graph found in the parent scope (via {@link ObjectGraph#plus}), if there is one.
*/
public static ObjectGraph create(MortarScope parent, Object... daggerModules) {
ObjectGraph parentGraph = getObjectGraph(parent);
return parentGraph == null ? ObjectGraph.create(daggerModules)
: parentGraph.plus(daggerModules);
}
public static ObjectGraph getObjectGraph(Context context) {
return (ObjectGraph) context.getSystemService(ObjectGraphService.SERVICE_NAME);
}
public static ObjectGraph getObjectGraph(MortarScope scope) {
return scope.getService(ObjectGraphService.SERVICE_NAME);
}
/**
* A convenience wrapper for {@link ObjectGraphService#getObjectGraph} to simplify dynamic
* injection, typically for {@link Activity} and {@link android.view.View} instances that must be
* instantiated by Android.
*/
public static void inject(Context context, Object object) {
getObjectGraph(context).inject(object);
}
/**
* A convenience wrapper for {@link ObjectGraphService#getObjectGraph} to simplify dynamic
* injection, typically for {@link Activity} and {@link android.view.View} instances that must be
* instantiated by Android.
*/
public static void inject(MortarScope scope, Object object) {
getObjectGraph(scope).inject(object);
}
private static ObjectGraph createSubgraphBlueprintStyle(ObjectGraph parentGraph,
Object daggerModule) {
ObjectGraph newGraph;
if (daggerModule == null) {
newGraph = parentGraph.plus();
} else if (daggerModule instanceof Collection) {
Collection c = (Collection) daggerModule;
newGraph = parentGraph.plus(c.toArray(new Object[c.size()]));
} else {
newGraph = parentGraph.plus(daggerModule);
}
return newGraph;
}
/**
* Returns the existing {@link MortarScope} scope for the given {@link Activity}, or
* uses the {@link Blueprint} to create one if none is found. The scope will provide
* {@link mortar.bundler.BundleService} and {@link BundleServiceRunner}.
* <p/>
* It is expected that this method will be called from {@link Activity#onCreate}. Calling
* it at other times may lead to surprises.
*
* @see MortarScope.Builder#withService(String, Object)
* @deprecated This method is provided to ease migration from earlier releases, which
* coupled Dagger and Activity integration. Instead build new scopes with {@link
* MortarScope#buildChild(String)}, and bind {@link ObjectGraphService} and
* {@link BundleServiceRunner} instances to them.
*/
@Deprecated public static MortarScope requireActivityScope(MortarScope parentScope,
Blueprint blueprint) {
String childName = blueprint.getMortarScopeName();
MortarScope child = parentScope.findChild(childName);
if (child == null) {
ObjectGraph parentGraph = parentScope.getService(ObjectGraphService.SERVICE_NAME);
Object daggerModule = blueprint.getDaggerModule();
Object childGraph = createSubgraphBlueprintStyle(parentGraph, daggerModule);
child = parentScope.buildChild(childName)
.withService(ObjectGraphService.SERVICE_NAME, childGraph)
.withService(BundleServiceRunner.SERVICE_NAME, new BundleServiceRunner())
.build();
}
return child;
}
/**
* Returns the existing child whose name matches the given {@link Blueprint}'s
* {@link Blueprint#getMortarScopeName()} value. If there is none, a new child is created
* based on {@link Blueprint#getDaggerModule()}. Note that
* {@link Blueprint#getDaggerModule()} is not called otherwise.
*
* @throws IllegalStateException if this scope has been destroyed
* @see MortarScope.Builder#withService(String, Object)
* @deprecated This method is provided to ease migration from earlier releases, which
* required Dagger integration. Instead build new scopes with {@link
* MortarScope#buildChild(String)}, and bind {@link ObjectGraphService} instances to them.
*/
@Deprecated public static MortarScope requireChild(MortarScope parentScope, Blueprint blueprint) {
String childName = blueprint.getMortarScopeName();
MortarScope child = parentScope.findChild(childName);
if (child == null) {
ObjectGraph parentGraph = parentScope.getService(ObjectGraphService.SERVICE_NAME);
Object daggerModule = blueprint.getDaggerModule();
Object childGraph = createSubgraphBlueprintStyle(parentGraph, daggerModule);
child = parentScope.buildChild(childName)
.withService(ObjectGraphService.SERVICE_NAME, childGraph)
.build();
}
return child;
}
}
| dagger1support/src/main/java/mortar/dagger1support/ObjectGraphService.java | package mortar.dagger1support;
import android.app.Activity;
import android.content.Context;
import dagger.ObjectGraph;
import java.util.Collection;
import mortar.MortarScope;
import mortar.bundler.BundleServiceRunner;
/**
* Provides utility methods for using Mortar with Dagger 1.
*/
public class ObjectGraphService {
public static final String SERVICE_NAME = ObjectGraphService.class.getName();
/**
* Create a new {@link ObjectGraph} based on the given module. The new graph will extend
* the graph found in the parent scope (via {@link ObjectGraph#plus}), if there is one.
*/
public static ObjectGraph create(MortarScope parent, Object... daggerModules) {
ObjectGraph parentGraph = getObjectGraph(parent);
return parentGraph == null ? ObjectGraph.create(daggerModules)
: parentGraph.plus(daggerModules);
}
public static ObjectGraph getObjectGraph(Context context) {
return (ObjectGraph) context.getSystemService(ObjectGraphService.SERVICE_NAME);
}
public static ObjectGraph getObjectGraph(MortarScope scope) {
return scope.getService(ObjectGraphService.SERVICE_NAME);
}
/**
* A convenience wrapper for {@link ObjectGraphService#getObjectGraph} to simplify dynamic
* injection, typically for {@link Activity} and {@link android.view.View} instances that must be
* instantiated by Android.
*/
public static void inject(Context context, Object object) {
getObjectGraph(context).inject(object);
}
private static ObjectGraph createSubgraphBlueprintStyle(ObjectGraph parentGraph,
Object daggerModule) {
ObjectGraph newGraph;
if (daggerModule == null) {
newGraph = parentGraph.plus();
} else if (daggerModule instanceof Collection) {
Collection c = (Collection) daggerModule;
newGraph = parentGraph.plus(c.toArray(new Object[c.size()]));
} else {
newGraph = parentGraph.plus(daggerModule);
}
return newGraph;
}
/**
* Returns the existing {@link MortarScope} scope for the given {@link Activity}, or
* uses the {@link Blueprint} to create one if none is found. The scope will provide
* {@link mortar.bundler.BundleService} and {@link BundleServiceRunner}.
* <p/>
* It is expected that this method will be called from {@link Activity#onCreate}. Calling
* it at other times may lead to surprises.
*
* @see MortarScope.Builder#withService(String, Object)
* @deprecated This method is provided to ease migration from earlier releases, which
* coupled Dagger and Activity integration. Instead build new scopes with {@link
* MortarScope#buildChild(String)}, and bind {@link ObjectGraphService} and
* {@link BundleServiceRunner} instances to them.
*/
@Deprecated public static MortarScope requireActivityScope(MortarScope parentScope,
Blueprint blueprint) {
String childName = blueprint.getMortarScopeName();
MortarScope child = parentScope.findChild(childName);
if (child == null) {
ObjectGraph parentGraph = parentScope.getService(ObjectGraphService.SERVICE_NAME);
Object daggerModule = blueprint.getDaggerModule();
Object childGraph = createSubgraphBlueprintStyle(parentGraph, daggerModule);
child = parentScope.buildChild(childName)
.withService(ObjectGraphService.SERVICE_NAME, childGraph)
.withService(BundleServiceRunner.SERVICE_NAME, new BundleServiceRunner())
.build();
}
return child;
}
/**
* Returns the existing child whose name matches the given {@link Blueprint}'s
* {@link Blueprint#getMortarScopeName()} value. If there is none, a new child is created
* based on {@link Blueprint#getDaggerModule()}. Note that
* {@link Blueprint#getDaggerModule()} is not called otherwise.
*
* @throws IllegalStateException if this scope has been destroyed
* @see MortarScope.Builder#withService(String, Object)
* @deprecated This method is provided to ease migration from earlier releases, which
* required Dagger integration. Instead build new scopes with {@link
* MortarScope#buildChild(String)}, and bind {@link ObjectGraphService} instances to them.
*/
@Deprecated public static MortarScope requireChild(MortarScope parentScope, Blueprint blueprint) {
String childName = blueprint.getMortarScopeName();
MortarScope child = parentScope.findChild(childName);
if (child == null) {
ObjectGraph parentGraph = parentScope.getService(ObjectGraphService.SERVICE_NAME);
Object daggerModule = blueprint.getDaggerModule();
Object childGraph = createSubgraphBlueprintStyle(parentGraph, daggerModule);
child = parentScope.buildChild(childName)
.withService(ObjectGraphService.SERVICE_NAME, childGraph)
.build();
}
return child;
}
}
| ObjectGraphService#inject(Scope, Object)
| dagger1support/src/main/java/mortar/dagger1support/ObjectGraphService.java | ObjectGraphService#inject(Scope, Object) | <ide><path>agger1support/src/main/java/mortar/dagger1support/ObjectGraphService.java
<ide> */
<ide> public static void inject(Context context, Object object) {
<ide> getObjectGraph(context).inject(object);
<add> }
<add>
<add> /**
<add> * A convenience wrapper for {@link ObjectGraphService#getObjectGraph} to simplify dynamic
<add> * injection, typically for {@link Activity} and {@link android.view.View} instances that must be
<add> * instantiated by Android.
<add> */
<add> public static void inject(MortarScope scope, Object object) {
<add> getObjectGraph(scope).inject(object);
<ide> }
<ide>
<ide> private static ObjectGraph createSubgraphBlueprintStyle(ObjectGraph parentGraph, |
|
Java | apache-2.0 | 48808170ce64d4c0d98c413dbac230b392fdf374 | 0 | cpitman/spring-social-auth0,spring-projects/spring-social-github,pkdevbox/spring-social-github,pkdevbox/spring-social-github,spring-projects/spring-social-github,cpitman/spring-social-auth0 | /*
* Copyright 2011 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.springframework.social.github;
import org.springframework.social.oauth2.AbstractOAuth2ServiceProvider;
import org.springframework.social.oauth2.OAuth2Template;
public class GitHubServiceProvider extends AbstractOAuth2ServiceProvider<GitHubApi> {
public GitHubServiceProvider(String clientId, String clientSecret) {
super(new OAuth2Template(clientId, clientSecret, "https://github.com/login/oauth/authorize}", "https://github.com/login/oauth/access_token"));
}
public GitHubApi getServiceApi(String accessToken) {
return new GitHubTemplate(accessToken);
}
}
| spring-social-github/src/main/java/org/springframework/social/github/GitHubServiceProvider.java | /*
* Copyright 2011 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.springframework.social.github;
import org.springframework.social.oauth2.AbstractOAuth2ServiceProvider;
import org.springframework.social.oauth2.OAuth2Template;
public class GitHubServiceProvider extends AbstractOAuth2ServiceProvider<GitHubApi> {
public GitHubServiceProvider(String clientId, String clientSecret) {
super(new OAuth2Template(clientId, clientSecret,
"https://github.com/login/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&scope={scope}",
"https://github.com/login/oauth/access_token"));
}
public GitHubApi getServiceApi(String accessToken) {
return new GitHubTemplate(accessToken);
}
}
| polish of oauth clients based on spec research
| spring-social-github/src/main/java/org/springframework/social/github/GitHubServiceProvider.java | polish of oauth clients based on spec research | <ide><path>pring-social-github/src/main/java/org/springframework/social/github/GitHubServiceProvider.java
<ide> public class GitHubServiceProvider extends AbstractOAuth2ServiceProvider<GitHubApi> {
<ide>
<ide> public GitHubServiceProvider(String clientId, String clientSecret) {
<del> super(new OAuth2Template(clientId, clientSecret,
<del> "https://github.com/login/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&scope={scope}",
<del> "https://github.com/login/oauth/access_token"));
<add> super(new OAuth2Template(clientId, clientSecret, "https://github.com/login/oauth/authorize}", "https://github.com/login/oauth/access_token"));
<ide> }
<ide>
<ide> public GitHubApi getServiceApi(String accessToken) { |
|
JavaScript | mit | 568e67d1cfb11e374a782e11a773fb2ac1385489 | 0 | jmjuanes/utily | //Check if an element exists inside the array
module.exports.has = function(array, item)
{
//Return if the element exists
return array.indexOf(item) !== -1;
};
//Return a range of values
module.exports.range = function(start, end, step)
{
//Check the start value
if(typeof start !== 'number'){ return []; }
//Check the end value
if(typeof end !== 'number'){ return []; }
//Check the step value
if(typeof step !== 'number'){ step = 1; }
//Get the range length
var len = Math.floor((end - start) / step) + 1;
//Build the range array elements
return Array(len).fill().map(function(el, idx){return start + (idx * step); });
};
//Remove an element of the array
module.exports.remove = function(array, item)
{
//Get the index of the item
var index = array.indexOf(item);
//Check the index
if(index !== -1)
{
//Remove the item from the array
array.splice(index, 1);
}
//Return the array
return array;
};
| lib/array.js | //Check if an element exists inside the array
module.exports.has = function(array, item)
{
//Return if the element exists
return array.indexOf(item) !== -1;
};
//Remove an element of the array
module.exports.remove = function(array, item)
{
//Get the index of the item
var index = array.indexOf(item);
//Check the index
if(index !== -1)
{
//Remove the item from the array
array.splice(index, 1);
}
//Return the array
return array;
};
| lib/array.js: added array.range method
| lib/array.js | lib/array.js: added array.range method | <ide><path>ib/array.js
<ide> {
<ide> //Return if the element exists
<ide> return array.indexOf(item) !== -1;
<add>};
<add>
<add>
<add>//Return a range of values
<add>module.exports.range = function(start, end, step)
<add>{
<add> //Check the start value
<add> if(typeof start !== 'number'){ return []; }
<add>
<add> //Check the end value
<add> if(typeof end !== 'number'){ return []; }
<add>
<add> //Check the step value
<add> if(typeof step !== 'number'){ step = 1; }
<add>
<add> //Get the range length
<add> var len = Math.floor((end - start) / step) + 1;
<add>
<add> //Build the range array elements
<add> return Array(len).fill().map(function(el, idx){return start + (idx * step); });
<ide> };
<ide>
<ide> //Remove an element of the array |
|
Java | apache-2.0 | 82058a3111242314425764f93fb81fd5e00d9530 | 0 | rewayaat/rewayaat,rewayaat/rewayaat,rewayaat/rewayaat,rewayaat/rewayaat | package com.rewayaat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
/**
* Main entrypoint to rewayaat app.
*/
@EnableCaching
@SpringBootApplication(scanBasePackages = {"com.rewayaat.config", "com.rewayaat.controllers",
"com.rewayaat.service"})
public class RewayaatApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(RewayaatApplication.class);
public static void main(String[] args) {
SpringApplication.run(RewayaatApplication.class, args);
}
} | src/main/java/com/rewayaat/RewayaatApplication.java | package com.rewayaat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
/**
* Main entrypoint to rewayaat app.
*/
@EnableCaching
@SpringBootApplication(scanBasePackages = {"com.rewayaat.config", "com.rewayaat.controllers"})
public class RewayaatApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(RewayaatApplication.class);
public static void main(String[] args) {
SpringApplication.run(RewayaatApplication.class, args);
}
} | Update spring base packages scan list
| src/main/java/com/rewayaat/RewayaatApplication.java | Update spring base packages scan list | <ide><path>rc/main/java/com/rewayaat/RewayaatApplication.java
<ide> * Main entrypoint to rewayaat app.
<ide> */
<ide> @EnableCaching
<del>@SpringBootApplication(scanBasePackages = {"com.rewayaat.config", "com.rewayaat.controllers"})
<add>@SpringBootApplication(scanBasePackages = {"com.rewayaat.config", "com.rewayaat.controllers",
<add> "com.rewayaat.service"})
<ide> public class RewayaatApplication {
<ide>
<ide> private static final Logger LOGGER = LoggerFactory.getLogger(RewayaatApplication.class); |
|
JavaScript | mit | 9c76417c2522b31483a9d52481419580a49ef2d6 | 0 | bolt/bolt,cdowdy/bolt,GawainLynch/bolt,electrolinux/bolt,Intendit/bolt,electrolinux/bolt,Intendit/bolt,Intendit/bolt,joshuan/bolt,Raistlfiren/bolt,Raistlfiren/bolt,lenvanessen/bolt,electrolinux/bolt,rarila/bolt,romulo1984/bolt,CarsonF/bolt,romulo1984/bolt,HonzaMikula/masivnipostele,nikgo/bolt,bolt/bolt,HonzaMikula/masivnipostele,GawainLynch/bolt,nikgo/bolt,rarila/bolt,cdowdy/bolt,CarsonF/bolt,lenvanessen/bolt,electrolinux/bolt,nikgo/bolt,GawainLynch/bolt,CarsonF/bolt,bolt/bolt,nikgo/bolt,HonzaMikula/masivnipostele,joshuan/bolt,GawainLynch/bolt,cdowdy/bolt,Raistlfiren/bolt,lenvanessen/bolt,Raistlfiren/bolt,romulo1984/bolt,lenvanessen/bolt,romulo1984/bolt,CarsonF/bolt,cdowdy/bolt,Intendit/bolt,bolt/bolt,joshuan/bolt,joshuan/bolt,rarila/bolt,rarila/bolt,HonzaMikula/masivnipostele | /**
* Set up live editor stuff
*
* @mixin
* @namespace Bolt.liveeditor
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
* @param {Object} window - Global window object.
* @param {Object|undefined} ckeditor - CKEDITOR global or undefined.
*/
(function (bolt, $, window, ckeditor) {
'use strict';
/**
* Bolt.liveEditor mixin container.
*
* @private
* @type {Object}
*/
var liveEditor = {};
var editableTypes = [
'text',
'html',
'textarea'
];
/**
* Removes events bound to live editor.
*
* @private
* @function removeEvents
*/
var removeEvents = null;
/**
* Initializes the mixin.
*
* @static
* @function init
* @memberof Bolt.liveEditor
*
* @param {BindData} data - Editcontent configuration data
*/
liveEditor.init = function(data) {
liveEditor.slug = data.singularSlug;
if (Modernizr.contenteditable) {
$('#sidebar-live-editor-button, #live-editor-button').bind('click', liveEditor.start);
$('.close-live-editor').bind('click', liveEditor.stop);
} else {
// If we don't have the features we need
// Don't let this get used
$('.live-editor, #sidebar-live-editor-button, #live-editor-button').remove();
}
};
/**
* Starts the live editor.
*
* @private
*
* @static
* @function start
* @memberof Bolt.liveEditor
*/
liveEditor.start = function () {
// Validate form first
var valid = bolt.validation.run($('#editcontent')[0]);
if (!valid) {
return;
}
// Add Events
var preventClick = function (e) {
e.preventDefault();
};
var iframeReady = function () {
var iframe = $('#live-editor-iframe')[0],
win = iframe.contentWindow || iframe,
doc = win.document,
jq = $(doc);
jq.on('click', 'a', preventClick);
var cke = bolt.ckeditor.initcke(win.CKEDITOR),
editorConfig = cke.editorConfig;
cke.editorConfig = function (config) {
editorConfig.bind(this)(config);
// Remove the source code viewer
for (var i in config.toolbar) {
if (config.toolbar[i].name === 'tools') {
var sourceIdx = config.toolbar[i].items.indexOf('Source');
if (sourceIdx > -1) {
delete config.toolbar[i].items[sourceIdx];
}
}
}
};
cke.disableAutoInline = false;
jq.find('[data-bolt-field]').each(function() {
// Find form field
var field = $('#editcontent *[name=' + liveEditor.escapejQuery($(this).data('bolt-field')) + ']'),
fieldType = field.closest('[data-bolt-fieldset]').data('bolt-fieldset');
$(this).addClass('bolt-editable');
if (!$(this).data('no-edit') && editableTypes.indexOf(fieldType) !== -1) {
$(this).attr('contenteditable', true);
if (fieldType === 'html') {
cke.inline(this, {
allowedContent: ''
});
} else {
$(this).on('paste', function(e) {
var content;
e.preventDefault();
if (e.originalEvent.clipboardData) {
content = e.originalEvent.clipboardData.getData('text/plain');
doc.execCommand('insertText', false, content);
} else if (win.clipboardData) {
content = win.clipboardData.getData('Text');
if (win.getSelection) {
win.getSelection().getRangeAt(0).insertNode(doc.createTextNode(content));
}
}
});
if (fieldType === 'textarea') {
$(this).on('keypress', function (e) {
if (e.which === 13) {
e.preventDefault();
doc.execCommand('insertHTML', false, '<br><br>');
}
});
} else {
$(this).on('keypress', function (e) {
return e.which !== 13;
}).on('focus blur', function () {
$(this).html($(this).text());
});
}
}
}
});
};
$('#live-editor-iframe').on('load', iframeReady);
bolt.liveEditor.active = true;
$('body').addClass('live-editor-active');
$('#navpage-primary .navbar-header a').on('click', preventClick);
var newAction = bolt.conf('paths.root') + 'preview/' + liveEditor.slug;
$('#editcontent *[name=_live-editor-preview]').val('yes');
$('#editcontent').attr('action', newAction).attr('target', 'live-editor-iframe').submit();
$('#editcontent').attr('action', '').attr('target', '_self');
$('#editcontent *[name=_live-editor-preview]').val('');
removeEvents = function () {
$('#live-editor-iframe').off('load', iframeReady);
$('#navpage-primary .navbar-header a').off('click', preventClick);
};
};
/**
* Stops the live editor.
*
* @private
*
* @static
* @function stop
* @memberof Bolt.liveEditor
*/
liveEditor.stop = function () {
var iframe = $('#live-editor-iframe')[0],
win = iframe.contentWindow || iframe,
doc = win.document,
jq = $(doc);
jq.find('[data-bolt-field]').each(function () {
// Find form field
var fieldName = $(this).data('bolt-field'),
field = $('#editcontent [name=' + liveEditor.escapejQuery(fieldName) + ']'),
fieldType = field.closest('[data-bolt-fieldset]').data('bolt-fieldset'),
fieldValue = '';
if (fieldType === 'html') {
fieldValue = $(this).html();
var fieldId = field.attr('id');
if (ckeditor.instances.hasOwnProperty(fieldId)) {
ckeditor.instances[fieldId].setData(fieldValue);
}
} else {
fieldValue = liveEditor.cleanText($(this), fieldType);
}
field.val(fieldValue);
});
$(iframe).attr('src', '');
bolt.liveEditor.active = false;
$('body').removeClass('live-editor-active');
removeEvents();
};
/**
* Clean contenteditable values for text fields
*
* @public
*
* @function cleanText
* @memberof Bolt.liveEditor
*
* @param {Object} element - jQuery element to clean
* @param {String} fieldType - type of field to clean (text, textarea)
* @return {String} Value for editcontent input fields
*/
liveEditor.cleanText = function(element, fieldType) {
// Preserve newlines and spacing for textarea fields
if (fieldType === 'textarea') {
element.html(element.html().replace(/ /g, ' ').replace(/\s?<br.*?>\s?/g, '\n'));
}
return element.text();
};
/**
* Escape jQuery selectors
*
* @public
*
* @static
* @function escapejQuery
* @memberof Bolt.liveEditor
*
* @param {String} selector - Selector to escape
*/
liveEditor.escapejQuery = function (selector) {
return selector.replace(/(:|\.|\[|\]|,)/g, "\\$1");
};
/**
* Whether the editor is running or not
*
* @public
* @type {Boolean}
*/
liveEditor.active = false;
/**
* Contenttype slug for the editor
*
* @private
* @type {string}
*/
liveEditor.slug = null;
bolt.liveEditor = liveEditor;
})(Bolt || {}, jQuery, window, typeof CKEDITOR !== 'undefined' ? CKEDITOR : undefined);
| app/src/js/modules/liveeditor.js | /**
* Set up live editor stuff
*
* @mixin
* @namespace Bolt.liveeditor
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
* @param {Object} window - Global window object.
* @param {Object|undefined} ckeditor - CKEDITOR global or undefined.
*/
(function (bolt, $, window, ckeditor) {
'use strict';
/**
* Bolt.liveEditor mixin container.
*
* @private
* @type {Object}
*/
var liveEditor = {};
var editableTypes = [
'text',
'html',
'textarea'
];
/**
* Initializes the mixin.
*
* @static
* @function init
* @memberof Bolt.liveEditor
*
* @param {BindData} data - Editcontent configuration data
*/
liveEditor.init = function(data) {
liveEditor.slug = data.singularSlug;
if (Modernizr.contenteditable) {
$('#sidebar-live-editor-button, #live-editor-button').bind('click', liveEditor.start);
$('.close-live-editor').bind('click', liveEditor.stop);
} else {
// If we don't have the features we need
// Don't let this get used
$('.live-editor, #sidebar-live-editor-button, #live-editor-button').remove();
}
};
/**
* Starts the live editor.
*
* @private
*
* @static
* @function start
* @memberof Bolt.liveEditor
*/
liveEditor.start = function () {
// Validate form first
var valid = bolt.validation.run($('#editcontent')[0]);
if (!valid) {
return;
}
// Add Events
var preventClick = function (e) {
e.preventDefault();
};
var iframeReady = function () {
var iframe = $('#live-editor-iframe')[0],
win = iframe.contentWindow || iframe,
doc = win.document,
jq = $(doc);
jq.on('click', 'a', preventClick);
var cke = bolt.ckeditor.initcke(win.CKEDITOR),
editorConfig = cke.editorConfig;
cke.editorConfig = function (config) {
editorConfig.bind(this)(config);
// Remove the source code viewer
for (var i in config.toolbar) {
if (config.toolbar[i].name === 'tools') {
var sourceIdx = config.toolbar[i].items.indexOf('Source');
if (sourceIdx > -1) {
delete config.toolbar[i].items[sourceIdx];
}
}
}
};
cke.disableAutoInline = false;
jq.find('[data-bolt-field]').each(function() {
// Find form field
var field = $('#editcontent *[name=' + liveEditor.escapejQuery($(this).data('bolt-field')) + ']'),
fieldType = field.closest('[data-bolt-fieldset]').data('bolt-fieldset');
$(this).addClass('bolt-editable');
if (!$(this).data('no-edit') && editableTypes.indexOf(fieldType) !== -1) {
$(this).attr('contenteditable', true);
if (fieldType === 'html') {
cke.inline(this, {
allowedContent: ''
});
} else {
$(this).on('paste', function(e) {
var content;
e.preventDefault();
if (e.originalEvent.clipboardData) {
content = e.originalEvent.clipboardData.getData('text/plain');
doc.execCommand('insertText', false, content);
} else if (win.clipboardData) {
content = win.clipboardData.getData('Text');
if (win.getSelection) {
win.getSelection().getRangeAt(0).insertNode(doc.createTextNode(content));
}
}
});
if (fieldType === 'textarea') {
$(this).on('keypress', function (e) {
if (e.which === 13) {
e.preventDefault();
doc.execCommand('insertHTML', false, '<br><br>');
}
});
} else {
$(this).on('keypress', function (e) {
return e.which !== 13;
}).on('focus blur', function () {
$(this).html($(this).text());
});
}
}
}
});
};
$('#live-editor-iframe').on('load', iframeReady);
bolt.liveEditor.active = true;
$('body').addClass('live-editor-active');
$('#navpage-primary .navbar-header a').on('click', preventClick);
var newAction = bolt.conf('paths.root') + 'preview/' + liveEditor.slug;
$('#editcontent *[name=_live-editor-preview]').val('yes');
$('#editcontent').attr('action', newAction).attr('target', 'live-editor-iframe').submit();
$('#editcontent').attr('action', '').attr('target', '_self');
$('#editcontent *[name=_live-editor-preview]').val('');
liveEditor.removeEvents = function () {
$('#live-editor-iframe').off('load', iframeReady);
$('#navpage-primary .navbar-header a').off('click', preventClick);
};
};
/**
* Stops the live editor.
*
* @private
*
* @static
* @function stop
* @memberof Bolt.liveEditor
*/
liveEditor.stop = function () {
var iframe = $('#live-editor-iframe')[0],
win = iframe.contentWindow || iframe,
doc = win.document,
jq = $(doc);
jq.find('[data-bolt-field]').each(function () {
// Find form field
var fieldName = $(this).data('bolt-field'),
field = $('#editcontent [name=' + liveEditor.escapejQuery(fieldName) + ']'),
fieldType = field.closest('[data-bolt-fieldset]').data('bolt-fieldset'),
fieldValue = '';
if (fieldType === 'html') {
fieldValue = $(this).html();
var fieldId = field.attr('id');
if (ckeditor.instances.hasOwnProperty(fieldId)) {
ckeditor.instances[fieldId].setData(fieldValue);
}
} else {
fieldValue = liveEditor.cleanText($(this), fieldType);
}
field.val(fieldValue);
});
$(iframe).attr('src', '');
bolt.liveEditor.active = false;
$('body').removeClass('live-editor-active');
liveEditor.removeEvents();
};
/**
* Clean contenteditable values for text fields
*
* @public
*
* @function cleanText
* @memberof Bolt.liveEditor
*
* @param {Object} element - jQuery element to clean
* @param {String} fieldType - type of field to clean (text, textarea)
* @return {String} Value for editcontent input fields
*/
liveEditor.cleanText = function(element, fieldType) {
// Preserve newlines and spacing for textarea fields
if (fieldType === 'textarea') {
element.html(element.html().replace(/ /g, ' ').replace(/\s?<br.*?>\s?/g, '\n'));
}
return element.text();
};
/**
* Escape jQuery selectors
*
* @public
*
* @static
* @function escapejQuery
* @memberof Bolt.liveEditor
*
* @param {String} selector - Selector to escape
*/
liveEditor.escapejQuery = function (selector) {
return selector.replace(/(:|\.|\[|\]|,)/g, "\\$1");
};
/**
* Whether the editor is running or not
*
* @public
* @type {Boolean}
*/
liveEditor.active = false;
/**
* Contenttype slug for the editor
*
* @private
* @type {string}
*/
liveEditor.slug = null;
/**
* Removes events bound to live editor
*
* @private
* @function removeEvents
*/
liveEditor.removeEvents = null;
bolt.liveEditor = liveEditor;
})(Bolt || {}, jQuery, window, typeof CKEDITOR !== 'undefined' ? CKEDITOR : undefined);
| Make removeEvents() really private | app/src/js/modules/liveeditor.js | Make removeEvents() really private | <ide><path>pp/src/js/modules/liveeditor.js
<ide> 'html',
<ide> 'textarea'
<ide> ];
<add>
<add> /**
<add> * Removes events bound to live editor.
<add> *
<add> * @private
<add> * @function removeEvents
<add> */
<add> var removeEvents = null;
<ide>
<ide> /**
<ide> * Initializes the mixin.
<ide> $('#editcontent').attr('action', '').attr('target', '_self');
<ide> $('#editcontent *[name=_live-editor-preview]').val('');
<ide>
<del> liveEditor.removeEvents = function () {
<add> removeEvents = function () {
<ide> $('#live-editor-iframe').off('load', iframeReady);
<ide> $('#navpage-primary .navbar-header a').off('click', preventClick);
<ide> };
<ide> bolt.liveEditor.active = false;
<ide> $('body').removeClass('live-editor-active');
<ide>
<del> liveEditor.removeEvents();
<add> removeEvents();
<ide> };
<ide>
<ide> /**
<ide> */
<ide> liveEditor.slug = null;
<ide>
<del> /**
<del> * Removes events bound to live editor
<del> *
<del> * @private
<del> * @function removeEvents
<del> */
<del> liveEditor.removeEvents = null;
<del>
<ide> bolt.liveEditor = liveEditor;
<ide> })(Bolt || {}, jQuery, window, typeof CKEDITOR !== 'undefined' ? CKEDITOR : undefined); |
|
Java | mit | 5c02de2f4a4b68e194c3305f56b8796ca8c1c7dd | 0 | loxal/FreeEthereum,loxal/ethereumj,loxal/FreeEthereum,loxal/FreeEthereum | package org.ethereum.solidity;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.ethereum.util.ByteUtil;
import org.ethereum.vm.DataWord;
import org.spongycastle.util.encoders.Hex;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class SolidityType {
protected String name;
public SolidityType(String name) {
this.name = name;
}
/**
* The type name as it was specified in the interface description
*/
public String getName() {
return name;
}
/**
* The canonical type name (used for the method signature creation)
* E.g. 'int' - canonical 'int256'
*/
@JsonValue
public String getCanonicalName() {
return getName();
}
@JsonCreator
public static SolidityType getType(String typeName) {
if (typeName.contains("[")) return ArrayType.getType(typeName);
if ("bool".equals(typeName)) return new BoolType();
if (typeName.startsWith("int") || typeName.startsWith("uint")) return new IntType(typeName);
if ("address".equals(typeName)) return new AddressType();
if ("string".equals(typeName)) return new StringType();
if ("bytes".equals(typeName)) return new BytesType();
if (typeName.startsWith("bytes")) return new Bytes32Type(typeName);
throw new RuntimeException("Unknown type: " + typeName);
}
/**
* Encodes the value according to specific type rules
*
* @param value
*/
public abstract byte[] encode(Object value);
public abstract Object decode(byte[] encoded, int offset);
public Object decode(byte[] encoded) {
return decode(encoded, 0);
}
/**
* @return fixed size in bytes. For the dynamic types returns IntType.getFixedSize()
* which is effectively the int offset to dynamic data
*/
public int getFixedSize() {
return 32;
}
public boolean isDynamicType() {
return false;
}
@Override
public String toString() {
return getName();
}
public static abstract class ArrayType extends SolidityType {
public static ArrayType getType(String typeName) {
int idx1 = typeName.indexOf("[");
int idx2 = typeName.indexOf("]", idx1);
if (idx1 + 1 == idx2) {
return new DynamicArrayType(typeName);
} else {
return new StaticArrayType(typeName);
}
}
SolidityType elementType;
public ArrayType(String name) {
super(name);
int idx = name.indexOf("[");
String st = name.substring(0, idx);
int idx2 = name.indexOf("]", idx);
String subDim = idx2 + 1 == name.length() ? "" : name.substring(idx2 + 1);
elementType = SolidityType.getType(st + subDim);
}
@Override
public byte[] encode(Object value) {
if (value.getClass().isArray()) {
List<Object> elems = new ArrayList<>();
for (int i = 0; i < Array.getLength(value); i++) {
elems.add(Array.get(value, i));
}
return encodeList(elems);
} else if (value instanceof List) {
return encodeList((List) value);
} else {
throw new RuntimeException("List value expected for type " + getName());
}
}
public SolidityType getElementType() {
return elementType;
}
public abstract byte[] encodeList(List l);
}
public static class StaticArrayType extends ArrayType {
int size;
public StaticArrayType(String name) {
super(name);
int idx1 = name.indexOf("[");
int idx2 = name.indexOf("]", idx1);
String dim = name.substring(idx1 + 1, idx2);
size = Integer.parseInt(dim);
}
@Override
public String getCanonicalName() {
return elementType.getCanonicalName() + "[" + size + "]";
}
@Override
public byte[] encodeList(List l) {
if (l.size() != size) throw new RuntimeException("List size (" + l.size() + ") != " + size + " for type " + getName());
byte[][] elems = new byte[size][];
for (int i = 0; i < l.size(); i++) {
elems[i] = elementType.encode(l.get(i));
}
return ByteUtil.merge(elems);
}
@Override
public Object[] decode(byte[] encoded, int offset) {
Object[] result = new Object[size];
for (int i = 0; i < size; i++) {
result[i] = elementType.decode(encoded, offset + i * elementType.getFixedSize());
}
return result;
}
@Override
public int getFixedSize() {
// return negative if elementType is dynamic
return elementType.getFixedSize() * size;
}
}
public static class DynamicArrayType extends ArrayType {
public DynamicArrayType(String name) {
super(name);
}
@Override
public String getCanonicalName() {
return elementType.getCanonicalName() + "[]";
}
@Override
public byte[] encodeList(List l) {
byte[][] elems;
if (elementType.isDynamicType()) {
elems = new byte[l.size() * 2 + 1][];
elems[0] = IntType.encodeInt(l.size());
int offset = l.size() * 32;
for (int i = 0; i < l.size(); i++) {
elems[i + 1] = IntType.encodeInt(offset);
byte[] encoded = elementType.encode(l.get(i));
elems[l.size() + i + 1] = encoded;
offset += 32 * ((encoded.length - 1) / 32 + 1);
}
} else {
elems = new byte[l.size() + 1][];
elems[0] = IntType.encodeInt(l.size());
for (int i = 0; i < l.size(); i++) {
elems[i + 1] = elementType.encode(l.get(i));
}
}
return ByteUtil.merge(elems);
}
@Override
public Object decode(byte[] encoded, int origOffset) {
int len = IntType.decodeInt(encoded, origOffset).intValue();
origOffset += 32;
int offset = origOffset;
Object[] ret = new Object[len];
for (int i = 0; i < len; i++) {
if (elementType.isDynamicType()) {
ret[i] = elementType.decode(encoded, origOffset + IntType.decodeInt(encoded, offset).intValue());
} else {
ret[i] = elementType.decode(encoded, offset);
}
offset += elementType.getFixedSize();
}
return ret;
}
@Override
public boolean isDynamicType() {
return true;
}
}
public static class BytesType extends SolidityType {
protected BytesType(String name) {
super(name);
}
public BytesType() {
super("bytes");
}
@Override
public byte[] encode(Object value) {
if (!(value instanceof byte[])) throw new RuntimeException("byte[] value expected for type 'bytes'");
byte[] bb = (byte[]) value;
byte[] ret = new byte[((bb.length - 1) / 32 + 1) * 32]; // padding 32 bytes
System.arraycopy(bb, 0, ret, 0, bb.length);
return ByteUtil.merge(IntType.encodeInt(bb.length), ret);
}
@Override
public Object decode(byte[] encoded, int offset) {
int len = IntType.decodeInt(encoded, offset).intValue();
if (len == 0) return new byte[0];
offset += 32;
return Arrays.copyOfRange(encoded, offset, offset + len);
}
@Override
public boolean isDynamicType() {
return true;
}
}
public static class StringType extends BytesType {
public StringType() {
super("string");
}
@Override
public byte[] encode(Object value) {
if (!(value instanceof String)) throw new RuntimeException("String value expected for type 'string'");
return super.encode(((String)value).getBytes(StandardCharsets.UTF_8));
}
@Override
public Object decode(byte[] encoded, int offset) {
return new String((byte[]) super.decode(encoded, offset), StandardCharsets.UTF_8);
}
}
public static class Bytes32Type extends SolidityType {
public Bytes32Type(String s) {
super(s);
}
@Override
public byte[] encode(Object value) {
if (value instanceof Number) {
BigInteger bigInt = new BigInteger(value.toString());
return IntType.encodeInt(bigInt);
} else if (value instanceof String) {
byte[] ret = new byte[32];
byte[] bytes = ((String) value).getBytes(StandardCharsets.UTF_8);
System.arraycopy(bytes, 0, ret, 0, bytes.length);
return ret;
} else if (value instanceof byte[]) {
byte[] bytes = (byte[]) value;
byte[] ret = new byte[32];
System.arraycopy(bytes, 0, ret, 32 - bytes.length, bytes.length);
return ret;
}
throw new RuntimeException("Can't encode java type " + value.getClass() + " to bytes32");
}
@Override
public Object decode(byte[] encoded, int offset) {
return Arrays.copyOfRange(encoded, offset, offset + getFixedSize());
}
}
public static class AddressType extends IntType {
public AddressType() {
super("address");
}
@Override
public byte[] encode(Object value) {
if (value instanceof String && !((String)value).startsWith("0x")) {
// address is supposed to be always in hex
value = "0x" + value;
}
byte[] addr = super.encode(value);
for (int i = 0; i < 12; i++) {
if (addr[i] != 0) {
throw new RuntimeException("Invalid address (should be 20 bytes length): " + Hex.toHexString(addr));
}
}
return addr;
}
@Override
public Object decode(byte[] encoded, int offset) {
BigInteger bi = (BigInteger) super.decode(encoded, offset);
return ByteUtil.bigIntegerToBytes(bi, 20);
}
}
public static class IntType extends SolidityType {
public IntType(String name) {
super(name);
}
@Override
public String getCanonicalName() {
if (getName().equals("int")) return "int256";
if (getName().equals("uint")) return "uint256";
return super.getCanonicalName();
}
@Override
public byte[] encode(Object value) {
BigInteger bigInt;
if (value instanceof String) {
String s = ((String)value).toLowerCase().trim();
int radix = 10;
if (s.startsWith("0x")) {
s = s.substring(2);
radix = 16;
} else if (s.contains("a") || s.contains("b") || s.contains("c") ||
s.contains("d") || s.contains("e") || s.contains("f")) {
radix = 16;
}
bigInt = new BigInteger(s, radix);
} else if (value instanceof BigInteger) {
bigInt = (BigInteger) value;
} else if (value instanceof Number) {
bigInt = new BigInteger(value.toString());
} else if (value instanceof byte[]) {
bigInt = ByteUtil.bytesToBigInteger((byte[]) value);
} else {
throw new RuntimeException("Invalid value for type '" + this + "': " + value + " (" + value.getClass() + ")");
}
return encodeInt(bigInt);
}
@Override
public Object decode(byte[] encoded, int offset) {
return decodeInt(encoded, offset);
}
public static BigInteger decodeInt(byte[] encoded, int offset) {
return new BigInteger(Arrays.copyOfRange(encoded, offset, offset + 32));
}
public static byte[] encodeInt(int i) {
return encodeInt(new BigInteger("" + i));
}
public static byte[] encodeInt(BigInteger bigInt) {
return ByteUtil.bigIntegerToBytesSigned(bigInt, 32);
}
}
public static class BoolType extends IntType {
public BoolType() {
super("bool");
}
@Override
public byte[] encode(Object value) {
if (!(value instanceof Boolean)) throw new RuntimeException("Wrong value for bool type: " + value);
return super.encode(value == Boolean.TRUE ? 1 : 0);
}
@Override
public Object decode(byte[] encoded, int offset) {
return Boolean.valueOf(((Number) super.decode(encoded, offset)).intValue() != 0);
}
}
}
| ethereumj-core/src/main/java/org/ethereum/solidity/SolidityType.java | package org.ethereum.solidity;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.ethereum.util.ByteUtil;
import org.ethereum.vm.DataWord;
import org.spongycastle.util.encoders.Hex;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class SolidityType {
protected String name;
public SolidityType(String name) {
this.name = name;
}
/**
* The type name as it was specified in the interface description
*/
public String getName() {
return name;
}
/**
* The canonical type name (used for the method signature creation)
* E.g. 'int' - canonical 'int256'
*/
@JsonValue
public String getCanonicalName() {
return getName();
}
@JsonCreator
public static SolidityType getType(String typeName) {
if (typeName.contains("[")) return ArrayType.getType(typeName);
if ("bool".equals(typeName)) return new BoolType();
if (typeName.startsWith("int") || typeName.startsWith("uint")) return new IntType(typeName);
if ("address".equals(typeName)) return new AddressType();
if ("string".equals(typeName)) return new StringType();
if ("bytes".equals(typeName)) return new BytesType();
if (typeName.startsWith("bytes")) return new Bytes32Type(typeName);
throw new RuntimeException("Unknown type: " + typeName);
}
/**
* Encodes the value according to specific type rules
*
* @param value
*/
public abstract byte[] encode(Object value);
public abstract Object decode(byte[] encoded, int offset);
public Object decode(byte[] encoded) {
return decode(encoded, 0);
}
/**
* @return fixed size in bytes. For the dynamic types returns IntType.getFixedSize()
* which is effectively the int offset to dynamic data
*/
public int getFixedSize() {
return 32;
}
public boolean isDynamicType() {
return false;
}
@Override
public String toString() {
return getName();
}
public static abstract class ArrayType extends SolidityType {
public static ArrayType getType(String typeName) {
int idx1 = typeName.indexOf("[");
int idx2 = typeName.indexOf("]", idx1);
if (idx1 + 1 == idx2) {
return new DynamicArrayType(typeName);
} else {
return new StaticArrayType(typeName);
}
}
SolidityType elementType;
public ArrayType(String name) {
super(name);
int idx = name.indexOf("[");
String st = name.substring(0, idx);
int idx2 = name.indexOf("]", idx);
String subDim = idx2 + 1 == name.length() ? "" : name.substring(idx2 + 1);
elementType = SolidityType.getType(st + subDim);
}
@Override
public byte[] encode(Object value) {
if (value.getClass().isArray()) {
List<Object> elems = new ArrayList<>();
for (int i = 0; i < Array.getLength(value); i++) {
elems.add(Array.get(value, i));
}
return encodeList(elems);
} else if (value instanceof List) {
return encodeList((List) value);
} else {
throw new RuntimeException("List value expected for type " + getName());
}
}
public SolidityType getElementType() {
return elementType;
}
public abstract byte[] encodeList(List l);
}
public static class StaticArrayType extends ArrayType {
int size;
public StaticArrayType(String name) {
super(name);
int idx1 = name.indexOf("[");
int idx2 = name.indexOf("]", idx1);
String dim = name.substring(idx1 + 1, idx2);
size = Integer.parseInt(dim);
}
@Override
public String getCanonicalName() {
return elementType.getCanonicalName() + "[" + size + "]";
}
@Override
public byte[] encodeList(List l) {
if (l.size() != size) throw new RuntimeException("List size (" + l.size() + ") != " + size + " for type " + getName());
byte[][] elems = new byte[size][];
for (int i = 0; i < l.size(); i++) {
elems[i] = elementType.encode(l.get(i));
}
return ByteUtil.merge(elems);
}
@Override
public Object[] decode(byte[] encoded, int offset) {
Object[] result = new Object[size];
for (int i = 0; i < size; i++) {
result[i] = elementType.decode(encoded, offset + i * elementType.getFixedSize());
}
return result;
}
@Override
public int getFixedSize() {
// return negative if elementType is dynamic
return elementType.getFixedSize() * size;
}
}
public static class DynamicArrayType extends ArrayType {
public DynamicArrayType(String name) {
super(name);
}
@Override
public String getCanonicalName() {
return elementType.getCanonicalName() + "[]";
}
@Override
public byte[] encodeList(List l) {
byte[][] elems;
if (elementType.isDynamicType()) {
elems = new byte[l.size() * 2 + 1][];
elems[0] = IntType.encodeInt(l.size());
int offset = l.size() * 32;
for (int i = 0; i < l.size(); i++) {
elems[i + 1] = IntType.encodeInt(offset);
byte[] encoded = elementType.encode(l.get(i));
elems[l.size() + i + 1] = encoded;
offset += 32 * ((encoded.length - 1) / 32 + 1);
}
} else {
elems = new byte[l.size() + 1][];
elems[0] = IntType.encodeInt(l.size());
for (int i = 0; i < l.size(); i++) {
elems[i + 1] = elementType.encode(l.get(i));
}
}
return ByteUtil.merge(elems);
}
@Override
public Object decode(byte[] encoded, int origOffset) {
int len = IntType.decodeInt(encoded, origOffset).intValue();
origOffset += 32;
int offset = origOffset;
Object[] ret = new Object[len];
for (int i = 0; i < len; i++) {
if (elementType.isDynamicType()) {
ret[i] = elementType.decode(encoded, origOffset + IntType.decodeInt(encoded, offset).intValue());
} else {
ret[i] = elementType.decode(encoded, offset);
}
offset += elementType.getFixedSize();
}
return ret;
}
@Override
public boolean isDynamicType() {
return true;
}
}
public static class BytesType extends SolidityType {
protected BytesType(String name) {
super(name);
}
public BytesType() {
super("bytes");
}
@Override
public byte[] encode(Object value) {
if (!(value instanceof byte[])) throw new RuntimeException("byte[] value expected for type 'bytes'");
byte[] bb = (byte[]) value;
byte[] ret = new byte[((bb.length - 1) / 32 + 1) * 32]; // padding 32 bytes
System.arraycopy(bb, 0, ret, 0, bb.length);
return ByteUtil.merge(IntType.encodeInt(bb.length), ret);
}
@Override
public Object decode(byte[] encoded, int offset) {
int len = IntType.decodeInt(encoded, offset).intValue();
if (len == 0) return new byte[0];
offset += 32;
return Arrays.copyOfRange(encoded, offset, offset + len);
}
@Override
public boolean isDynamicType() {
return true;
}
}
public static class StringType extends BytesType {
public StringType() {
super("string");
}
@Override
public byte[] encode(Object value) {
if (!(value instanceof String)) throw new RuntimeException("String value expected for type 'string'");
return super.encode(((String)value).getBytes(StandardCharsets.UTF_8));
}
@Override
public Object decode(byte[] encoded, int offset) {
return new String((byte[]) super.decode(encoded, offset), StandardCharsets.UTF_8);
}
}
public static class Bytes32Type extends SolidityType {
public Bytes32Type(String s) {
super(s);
}
@Override
public byte[] encode(Object value) {
if (value instanceof Number) {
BigInteger bigInt = new BigInteger(value.toString());
return IntType.encodeInt(bigInt);
} else if (value instanceof String) {
byte[] ret = new byte[32];
byte[] bytes = ((String) value).getBytes(StandardCharsets.UTF_8);
System.arraycopy(bytes, 0, ret, 0, bytes.length);
return ret;
}
return new byte[0];
}
@Override
public Object decode(byte[] encoded, int offset) {
return Arrays.copyOfRange(encoded, offset, offset + getFixedSize());
}
}
public static class AddressType extends IntType {
public AddressType() {
super("address");
}
@Override
public byte[] encode(Object value) {
if (value instanceof String && !((String)value).startsWith("0x")) {
// address is supposed to be always in hex
value = "0x" + value;
}
byte[] addr = super.encode(value);
for (int i = 0; i < 12; i++) {
if (addr[i] != 0) {
throw new RuntimeException("Invalid address (should be 20 bytes length): " + Hex.toHexString(addr));
}
}
return addr;
}
@Override
public Object decode(byte[] encoded, int offset) {
BigInteger bi = (BigInteger) super.decode(encoded, offset);
return ByteUtil.bigIntegerToBytes(bi, 20);
}
}
public static class IntType extends SolidityType {
public IntType(String name) {
super(name);
}
@Override
public String getCanonicalName() {
if (getName().equals("int")) return "int256";
if (getName().equals("uint")) return "uint256";
return super.getCanonicalName();
}
@Override
public byte[] encode(Object value) {
BigInteger bigInt;
if (value instanceof String) {
String s = ((String)value).toLowerCase().trim();
int radix = 10;
if (s.startsWith("0x")) {
s = s.substring(2);
radix = 16;
} else if (s.contains("a") || s.contains("b") || s.contains("c") ||
s.contains("d") || s.contains("e") || s.contains("f")) {
radix = 16;
}
bigInt = new BigInteger(s, radix);
} else if (value instanceof BigInteger) {
bigInt = (BigInteger) value;
} else if (value instanceof Number) {
bigInt = new BigInteger(value.toString());
} else if (value instanceof byte[]) {
bigInt = ByteUtil.bytesToBigInteger((byte[]) value);
} else {
throw new RuntimeException("Invalid value for type '" + this + "': " + value + " (" + value.getClass() + ")");
}
return encodeInt(bigInt);
}
@Override
public Object decode(byte[] encoded, int offset) {
return decodeInt(encoded, offset);
}
public static BigInteger decodeInt(byte[] encoded, int offset) {
return new BigInteger(Arrays.copyOfRange(encoded, offset, offset + 32));
}
public static byte[] encodeInt(int i) {
return encodeInt(new BigInteger("" + i));
}
public static byte[] encodeInt(BigInteger bigInt) {
return ByteUtil.bigIntegerToBytesSigned(bigInt, 32);
}
}
public static class BoolType extends IntType {
public BoolType() {
super("bool");
}
@Override
public byte[] encode(Object value) {
if (!(value instanceof Boolean)) throw new RuntimeException("Wrong value for bool type: " + value);
return super.encode(value == Boolean.TRUE ? 1 : 0);
}
@Override
public Object decode(byte[] encoded, int offset) {
return Boolean.valueOf(((Number) super.decode(encoded, offset)).intValue() != 0);
}
}
}
| Convert byte[] -> bytes32 and fail on unknown classes instead of silently encode to byte[0]
| ethereumj-core/src/main/java/org/ethereum/solidity/SolidityType.java | Convert byte[] -> bytes32 and fail on unknown classes instead of silently encode to byte[0] | <ide><path>thereumj-core/src/main/java/org/ethereum/solidity/SolidityType.java
<ide> byte[] bytes = ((String) value).getBytes(StandardCharsets.UTF_8);
<ide> System.arraycopy(bytes, 0, ret, 0, bytes.length);
<ide> return ret;
<del> }
<del>
<del> return new byte[0];
<add> } else if (value instanceof byte[]) {
<add> byte[] bytes = (byte[]) value;
<add> byte[] ret = new byte[32];
<add> System.arraycopy(bytes, 0, ret, 32 - bytes.length, bytes.length);
<add> return ret;
<add> }
<add>
<add> throw new RuntimeException("Can't encode java type " + value.getClass() + " to bytes32");
<ide> }
<ide>
<ide> @Override |
|
JavaScript | isc | 77c385e8eb8f619a00bbcc53e5dd6da9949ba6aa | 0 | WeAreGenki/wag-ui | 'use strict'; // eslint-disable-line
// eslint-disable-next-line import/no-extraneous-dependencies
const uiPostcssPreset = require('@wearegenki/postcss-config');
module.exports = {
uiPostcssPreset,
};
| packages/ui/index.js | 'use strict'; // eslint-disable-line
const uiPostcssPreset = require('@wearegenki/postcss-config');
module.exports = {
uiPostcssPreset,
};
| Ignore lint error
| packages/ui/index.js | Ignore lint error | <ide><path>ackages/ui/index.js
<ide> 'use strict'; // eslint-disable-line
<ide>
<add>// eslint-disable-next-line import/no-extraneous-dependencies
<ide> const uiPostcssPreset = require('@wearegenki/postcss-config');
<ide>
<ide> module.exports = { |
|
Java | apache-2.0 | 478d15154a3c9b9d32cc0cf20235aa1c10e852b6 | 0 | jimmccusker/callimachus,3-Round-Stones/callimachus,edwardsph/callimachus,Thellmann/callimachus,jimmccusker/callimachus,Thellmann/callimachus,Thellmann/callimachus,jimmccusker/callimachus,3-Round-Stones/callimachus,edwardsph/callimachus,Thellmann/callimachus,3-Round-Stones/callimachus,Thellmann/callimachus,Thellmann/callimachus,3-Round-Stones/callimachus,jimmccusker/callimachus,jimmccusker/callimachus,3-Round-Stones/callimachus,edwardsph/callimachus,3-Round-Stones/callimachus,edwardsph/callimachus,jimmccusker/callimachus,edwardsph/callimachus,edwardsph/callimachus | /*
* Portions Copyright (c) 2011-13 3 Round Stones Inc., Some Rights Reserved
* Portions Copyright (c) 2009-10 Zepheira LLC, Some Rights Reserved
* Portions Copyright (c) 2010-11 Talis Inc, Some 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 org.callimachusproject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Arrays;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.management.QueryExp;
import org.callimachusproject.cli.Command;
import org.callimachusproject.cli.CommandSet;
import org.callimachusproject.concurrent.ManagedExecutors;
import org.callimachusproject.concurrent.ManagedThreadPool;
import org.callimachusproject.concurrent.ManagedThreadPoolListener;
import org.callimachusproject.management.CalliKeyStore;
import org.callimachusproject.management.CalliServer;
import org.callimachusproject.management.CalliServer.ServerListener;
import org.callimachusproject.management.JVMSummary;
import org.callimachusproject.management.LogEmitter;
import org.callimachusproject.repository.CalliRepository;
import org.callimachusproject.server.WebServer;
import org.callimachusproject.util.CallimachusConf;
import org.callimachusproject.util.CallimachusPolicy;
import org.callimachusproject.util.SystemProperties;
import org.openrdf.repository.manager.LocalRepositoryManager;
import org.openrdf.repository.manager.RepositoryProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Command line tool for launching the server.
*
* @author James Leigh
*
*/
public class Server {
public static final String NAME = Version.getInstance().getVersion();
private static final CommandSet commands = new CommandSet(NAME);
static {
commands.require("c", "conf")
.arg("file")
.desc("The local etc/callimachus.conf file to read settings from");
commands.option("b", "basedir").arg("directory")
.desc("Base directory used for local storage");
commands.option("trust").desc(
"Allow all server code to read, write, and execute all files and directories "
+ "according to the file system's ACL");
commands.option("pid").arg("file")
.desc("File to store current process id");
commands.option("q", "quiet").desc(
"Don't print status messages to standard output.");
commands.option("h", "help").desc("Print help (this message) and exit");
commands.option("v", "version").desc(
"Print version information and exit");
}
public static void main(String[] args) {
try {
Command line = commands.parse(args);
if (line.has("pid")) {
RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
String pid = bean.getName().replaceAll("@.*", "");
File file = new File(line.get("pid"));
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
try {
writer.append(pid);
} finally {
writer.close();
}
file.deleteOnExit();
}
final Server node = new Server();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try {
node.stop();
node.destroy();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}));
node.init(args);
node.start();
node.await();
} catch (Throwable e) {
while (e.getCause() != null) {
e = e.getCause();
}
System.err.println("Arguments: " + Arrays.toString(args));
System.err.println(e.toString());
e.printStackTrace(System.err);
System.exit(1);
}
}
private final Logger logger = LoggerFactory.getLogger(Server.class);
private CalliServer node;
public void init(String[] args) {
try {
Command line = commands.parse(args);
if (line.isParseError()) {
line.printParseError();
System.exit(2);
return;
} else if (line.has("help")) {
line.printHelp();
System.exit(0);
return;
} else if (line.has("version")) {
line.printCommandName();
System.exit(0);
return;
} else if (line.has("quiet")) {
try {
logStdout();
} catch (SecurityException e) {
// ignore
}
}
File baseDir = new File(".");
if (line.has("basedir")) {
baseDir = new File(line.get("basedir"));
}
File confFile = new File("etc/callimachus.conf");
if (line.has("conf")) {
confFile = new File(line.get("conf"));
}
File backupDir = new File("backups");
if (line.has("backups")) {
backupDir = new File(line.get("backups"));
}
ManagedExecutors.getInstance().addListener(
new ManagedThreadPoolListener() {
public void threadPoolStarted(String name,
ManagedThreadPool pool) {
registerMBean(name, pool, ManagedThreadPool.class);
}
public void threadPoolTerminated(String name) {
unregisterMBean(name, ManagedThreadPool.class);
}
});
CallimachusConf conf = new CallimachusConf(confFile);
LocalRepositoryManager manager = RepositoryProvider.getRepositoryManager(baseDir);
node = new CalliServer(conf, manager, new ServerListener() {
public void repositoryInitialized(String repositoryID,
CalliRepository repository) {
unregisterMBean(repositoryID, CalliRepository.class);
registerMBean(repositoryID, repository, CalliRepository.class);
}
public void repositoryShutDown(String repositoryID) {
unregisterMBean(repositoryID, CalliRepository.class);
}
public void webServiceStarted(WebServer server) {
registerMBean(server, WebServer.class);
}
public void webServiceStopping(WebServer server) {
unregisterMBean(WebServer.class);
}
});
registerMBean(node, CalliServer.class);
registerMBean(new JVMSummary(), JVMSummary.class);
registerMBean(new LogEmitter(), LogEmitter.class);
File etc = new File(baseDir, "etc");
registerMBean(new CalliKeyStore(etc), CalliKeyStore.class);
if (!line.has("trust")) {
File[] writable = { confFile, backupDir,
SystemProperties.getMailPropertiesFile(),
SystemProperties.getLoggingPropertiesFile(),
new File(baseDir, "repositories") };
CallimachusPolicy.apply(new String[0], writable);
}
node.init();
} catch (Throwable e) {
while (e.getCause() != null) {
e = e.getCause();
}
System.err.println("Arguments: " + Arrays.toString(args));
System.err.println(e.toString());
e.printStackTrace(System.err);
System.exit(1);
}
}
public void start() throws Exception {
node.start();
}
public void await() throws InterruptedException {
synchronized (node) {
while (node.isRunning()) {
node.wait();
}
}
}
public void stop() throws Exception {
if (node != null) {
node.stop();
}
}
public void destroy() throws Exception {
try {
node.destroy();
} finally {
unregisterMBean(CalliServer.class);
unregisterMBean(JVMSummary.class);
unregisterMBean(LogEmitter.class);
unregisterMBean(CalliKeyStore.class);
ManagedExecutors.getInstance().cleanup();
}
}
<T> void registerMBean(T bean, Class<T> beanClass) {
registerMBean(null, bean, beanClass);
}
void unregisterMBean(Class<?> beanClass) {
unregisterMBean(null, beanClass);
}
<T> void registerMBean(String name, T bean, Class<T> beanClass) {
try {
ObjectName oname = getMBeanName(name, beanClass);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(bean, oname);
} catch (Exception e) {
logger.error(e.toString(), e);
}
}
void unregisterMBean(String name, Class<?> beanClass) {
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
if (name == null) {
ObjectName oname = new ObjectName("*:type=" + beanClass.getSimpleName() + ",*");
for (Class<?> mx : beanClass.getInterfaces()) {
if (mx.getName().endsWith("Bean")) {
QueryExp instanceOf = Query.isInstanceOf(Query.value(beanClass.getName()));
for (ObjectName on : mbs.queryNames(oname, instanceOf)) {
mbs.unregisterMBean(on);
}
}
}
} else if (mbs.isRegistered(getMBeanName(name, beanClass))) {
mbs.unregisterMBean(getMBeanName(name, beanClass));
}
} catch (Exception e) {
// ignore
}
}
private ObjectName getMBeanName(String name, Class<?> beanClass)
throws MalformedObjectNameException {
String pkg = Server.class.getPackage().getName();
String simple = beanClass.getSimpleName();
StringBuilder sb = new StringBuilder();
sb.append(pkg).append(":type=").append(simple);
if (name != null) {
sb.append(",name=").append(name);
}
return new ObjectName(sb.toString());
}
private void logStdout() {
System.setOut(new PrintStream(new OutputStream() {
private int ret = "\r".getBytes()[0];
private int newline = "\n".getBytes()[0];
private Logger logger = LoggerFactory.getLogger("stdout");
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public synchronized void write(int b) throws IOException {
if (b == ret || b == newline) {
if (buffer.size() > 0) {
logger.info(buffer.toString());
buffer.reset();
}
} else {
buffer.write(b);
}
}
}, true));
System.setErr(new PrintStream(new OutputStream() {
private int ret = "\r".getBytes()[0];
private int newline = "\n".getBytes()[0];
private Logger logger = LoggerFactory.getLogger("stderr");
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public synchronized void write(int b) throws IOException {
if (b == ret || b == newline) {
if (buffer.size() > 0) {
logger.warn(buffer.toString());
buffer.reset();
}
} else {
buffer.write(b);
}
}
}, true));
}
}
| src/org/callimachusproject/Server.java | /*
* Portions Copyright (c) 2011-13 3 Round Stones Inc., Some Rights Reserved
* Portions Copyright (c) 2009-10 Zepheira LLC, Some Rights Reserved
* Portions Copyright (c) 2010-11 Talis Inc, Some 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 org.callimachusproject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Arrays;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.management.QueryExp;
import org.callimachusproject.cli.Command;
import org.callimachusproject.cli.CommandSet;
import org.callimachusproject.concurrent.ManagedExecutors;
import org.callimachusproject.concurrent.ManagedThreadPool;
import org.callimachusproject.concurrent.ManagedThreadPoolListener;
import org.callimachusproject.management.CalliKeyStore;
import org.callimachusproject.management.CalliServer;
import org.callimachusproject.management.CalliServer.ServerListener;
import org.callimachusproject.management.JVMSummary;
import org.callimachusproject.management.LogEmitter;
import org.callimachusproject.repository.CalliRepository;
import org.callimachusproject.server.WebServer;
import org.callimachusproject.util.CallimachusConf;
import org.callimachusproject.util.CallimachusPolicy;
import org.callimachusproject.util.SystemProperties;
import org.openrdf.repository.manager.LocalRepositoryManager;
import org.openrdf.repository.manager.RepositoryProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Command line tool for launching the server.
*
* @author James Leigh
*
*/
public class Server {
public static final String NAME = Version.getInstance().getVersion();
private static final CommandSet commands = new CommandSet(NAME);
static {
commands.require("c", "conf")
.arg("file")
.desc("The local etc/callimachus.conf file to read settings from");
commands.option("b", "basedir").arg("directory")
.desc("Base directory used for local storage");
commands.option("trust").desc(
"Allow all server code to read, write, and execute all files and directories "
+ "according to the file system's ACL");
commands.option("pid").arg("file")
.desc("File to store current process id");
commands.option("q", "quiet").desc(
"Don't print status messages to standard output.");
commands.option("h", "help").desc("Print help (this message) and exit");
commands.option("v", "version").desc(
"Print version information and exit");
}
public static void main(String[] args) {
try {
Command line = commands.parse(args);
if (line.has("pid")) {
RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
String pid = bean.getName().replaceAll("@.*", "");
File file = new File(line.get("pid"));
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
try {
writer.append(pid);
} finally {
writer.close();
}
file.deleteOnExit();
}
final Server node = new Server();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try {
node.stop();
node.destroy();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}));
node.init(args);
node.start();
node.await();
} catch (Throwable e) {
while (e.getCause() != null) {
e = e.getCause();
}
System.err.println("Arguments: " + Arrays.toString(args));
System.err.println(e.toString());
e.printStackTrace(System.err);
System.exit(1);
}
}
private final Logger logger = LoggerFactory.getLogger(Server.class);
private CalliServer node;
public void init(String[] args) {
try {
Command line = commands.parse(args);
if (line.isParseError()) {
line.printParseError();
System.exit(2);
return;
} else if (line.has("help")) {
line.printHelp();
System.exit(0);
return;
} else if (line.has("version")) {
line.printCommandName();
System.exit(0);
return;
} else if (line.has("quiet")) {
try {
logStdout();
} catch (SecurityException e) {
// ignore
}
}
File baseDir = new File(".");
if (line.has("basedir")) {
baseDir = new File(line.get("basedir"));
}
File confFile = new File("etc/callimachus.conf");
if (line.has("conf")) {
confFile = new File(line.get("conf"));
}
File backupDir = new File("backups");
if (line.has("backups")) {
backupDir = new File(line.get("backups"));
}
ManagedExecutors.getInstance().addListener(
new ManagedThreadPoolListener() {
public void threadPoolStarted(String name,
ManagedThreadPool pool) {
registerMBean(name, pool, ManagedThreadPool.class);
}
public void threadPoolTerminated(String name) {
unregisterMBean(name, ManagedThreadPool.class);
}
});
CallimachusConf conf = new CallimachusConf(confFile);
LocalRepositoryManager manager = RepositoryProvider.getRepositoryManager(baseDir);
node = new CalliServer(conf, manager, new ServerListener() {
public void repositoryInitialized(String repositoryID,
CalliRepository repository) {
unregisterMBean(repositoryID, CalliRepository.class);
registerMBean(repositoryID, repository, CalliRepository.class);
}
public void repositoryShutDown(String repositoryID) {
unregisterMBean(repositoryID, CalliRepository.class);
}
public void webServiceStarted(WebServer server) {
registerMBean(server, WebServer.class);
}
public void webServiceStopping(WebServer server) {
unregisterMBean(WebServer.class);
}
});
registerMBean(node, CalliServer.class);
registerMBean(new JVMSummary(), JVMSummary.class);
registerMBean(new LogEmitter(), LogEmitter.class);
File etc = new File(baseDir, "etc");
registerMBean(new CalliKeyStore(etc), CalliKeyStore.class);
if (!line.has("trust")) {
File[] writable = { confFile, backupDir,
SystemProperties.getMailPropertiesFile(),
SystemProperties.getLoggingPropertiesFile(),
new File(baseDir, "repositories") };
CallimachusPolicy.apply(new String[0], writable);
}
node.init();
} catch (Throwable e) {
while (e.getCause() != null) {
e = e.getCause();
}
System.err.println("Arguments: " + Arrays.toString(args));
System.err.println(e.toString());
e.printStackTrace(System.err);
System.exit(1);
}
}
public void start() throws Exception {
node.start();
}
public void await() throws InterruptedException {
synchronized (node) {
while (node.isRunning()) {
node.wait();
}
}
}
public void stop() throws Exception {
node.stop();
}
public void destroy() throws Exception {
try {
node.destroy();
} finally {
unregisterMBean(CalliServer.class);
unregisterMBean(JVMSummary.class);
unregisterMBean(LogEmitter.class);
unregisterMBean(CalliKeyStore.class);
ManagedExecutors.getInstance().cleanup();
}
}
<T> void registerMBean(T bean, Class<T> beanClass) {
registerMBean(null, bean, beanClass);
}
void unregisterMBean(Class<?> beanClass) {
unregisterMBean(null, beanClass);
}
<T> void registerMBean(String name, T bean, Class<T> beanClass) {
try {
ObjectName oname = getMBeanName(name, beanClass);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(bean, oname);
} catch (Exception e) {
logger.error(e.toString(), e);
}
}
void unregisterMBean(String name, Class<?> beanClass) {
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
if (name == null) {
ObjectName oname = new ObjectName("*:type=" + beanClass.getSimpleName() + ",*");
for (Class<?> mx : beanClass.getInterfaces()) {
if (mx.getName().endsWith("Bean")) {
QueryExp instanceOf = Query.isInstanceOf(Query.value(beanClass.getName()));
for (ObjectName on : mbs.queryNames(oname, instanceOf)) {
mbs.unregisterMBean(on);
}
}
}
} else if (mbs.isRegistered(getMBeanName(name, beanClass))) {
mbs.unregisterMBean(getMBeanName(name, beanClass));
}
} catch (Exception e) {
// ignore
}
}
private ObjectName getMBeanName(String name, Class<?> beanClass)
throws MalformedObjectNameException {
String pkg = Server.class.getPackage().getName();
String simple = beanClass.getSimpleName();
StringBuilder sb = new StringBuilder();
sb.append(pkg).append(":type=").append(simple);
if (name != null) {
sb.append(",name=").append(name);
}
return new ObjectName(sb.toString());
}
private void logStdout() {
System.setOut(new PrintStream(new OutputStream() {
private int ret = "\r".getBytes()[0];
private int newline = "\n".getBytes()[0];
private Logger logger = LoggerFactory.getLogger("stdout");
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public synchronized void write(int b) throws IOException {
if (b == ret || b == newline) {
if (buffer.size() > 0) {
logger.info(buffer.toString());
buffer.reset();
}
} else {
buffer.write(b);
}
}
}, true));
System.setErr(new PrintStream(new OutputStream() {
private int ret = "\r".getBytes()[0];
private int newline = "\n".getBytes()[0];
private Logger logger = LoggerFactory.getLogger("stderr");
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public synchronized void write(int b) throws IOException {
if (b == ret || b == newline) {
if (buffer.size() > 0) {
logger.warn(buffer.toString());
buffer.reset();
}
} else {
buffer.write(b);
}
}
}, true));
}
}
| NPE check on invalid commandlines options
| src/org/callimachusproject/Server.java | NPE check on invalid commandlines options | <ide><path>rc/org/callimachusproject/Server.java
<ide> }
<ide>
<ide> public void stop() throws Exception {
<del> node.stop();
<add> if (node != null) {
<add> node.stop();
<add> }
<ide> }
<ide>
<ide> public void destroy() throws Exception { |
|
Java | apache-2.0 | a7d84dff1475fe95c75d2f33ce8aa7e4f4387be7 | 0 | EBIvariation/eva-ws,EBIvariation/eva,EBIvariation/eva-ws | /*
* European Variation Archive (EVA) - Open-access database of all types of genetic
* variation data from all species
*
* Copyright 2016 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.eva.lib.repository;
import org.opencb.biodata.models.feature.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import uk.ac.ebi.eva.commons.models.metadata.VariantEntity;
import uk.ac.ebi.eva.lib.filter.VariantEntityRepositoryFilter;
import java.util.ArrayList;
import java.util.List;
/**
* Concrete implementation of the VariantEntityRepository interface (relationship inferred by Spring),
* due to a custom DBObject to VariantEntity conversion
*
* <p>It also implements the VariantEntityRepositoryCustom interface,
* to provide an explicit implementation of the region query, using a margin for efficiency.
*/
public class VariantEntityRepositoryImpl implements VariantEntityRepositoryCustom {
private MongoTemplate mongoTemplate;
protected static Logger logger = LoggerFactory.getLogger(VariantEntityRepositoryImpl.class);
private final int MARGIN = 5000;
@Autowired
public VariantEntityRepositoryImpl(MongoDbFactory mongoDbFactory, MappingMongoConverter mappingMongoConverter) {
mongoTemplate = new MongoTemplate(mongoDbFactory, mappingMongoConverter);
}
@Override
public List<VariantEntity> findByIdsAndComplexFilters(String id, List<VariantEntityRepositoryFilter> filters,
List<String> exclude, Pageable pageable) {
Query query = new Query(Criteria.where("ids").is(id));
return findByComplexFiltersHelper(query, filters, exclude, pageable);
}
@Override
public Long countByIdsAndComplexFilters(String id, List<VariantEntityRepositoryFilter> filters) {
Criteria criteria = Criteria.where("ids").is(id);
return countByComplexFiltersHelper(criteria, filters);
}
@Override
public List<VariantEntity> findByGenesAndComplexFilters(List<String> geneIds,
List<VariantEntityRepositoryFilter> filters,
List<String> exclude, Pageable pageable) {
Query query = new Query(Criteria.where("annot.xrefs.id").in(geneIds));
return findByComplexFiltersHelper(query, filters, exclude, pageable);
}
@Override
public Long countByGenesAndComplexFilters(List<String> geneIds, List<VariantEntityRepositoryFilter> filters) {
Criteria criteria = Criteria.where("annot.xrefs.id").in(geneIds);
return countByComplexFiltersHelper(criteria, filters);
}
@Override
public List<VariantEntity> findByRegionsAndComplexFilters(List<Region> regions,
List<VariantEntityRepositoryFilter> filters,
List<String> exclude, Pageable pageable) {
Query query = new Query();
Criteria criteria = getRegionsCriteria(regions);
query.addCriteria(criteria);
return findByComplexFiltersHelper(query, filters, exclude, pageable);
}
@Override
public Long countByRegionsAndComplexFilters(List<Region> regions, List<VariantEntityRepositoryFilter> filters) {
Criteria criteria = getRegionsCriteria(regions);
return countByComplexFiltersHelper(criteria, filters);
}
@Override
public List<String> findDistinctChromosomes() {
return (List<String>) mongoTemplate.getCollection(mongoTemplate.getCollectionName(VariantEntity.class))
.distinct("chr");
}
private List<VariantEntity> findByComplexFiltersHelper(Query query, List<VariantEntityRepositoryFilter> filters,
List<String> exclude, Pageable pageable) {
addFilterCriteriaToQuery(query, filters);
ArrayList<String> sortProperties = new ArrayList<String>();
sortProperties.add("chr");
sortProperties.add("start");
query.with(new Sort(Sort.Direction.ASC, sortProperties));
Pageable pageable1 = (pageable != null) ? pageable : new PageRequest(0, 10);
query.with(pageable1);
if (exclude != null && !exclude.isEmpty()) {
exclude.forEach(e -> query.fields().exclude(e));
}
return mongoTemplate.find(query, VariantEntity.class);
}
private void addFilterCriteriaToQuery(Query query, List<VariantEntityRepositoryFilter> filters) {
if (filters.size() > 0){
List<Criteria> criteriaList = getFiltersCriteria(filters);
for (Criteria criteria : criteriaList) {
query.addCriteria(criteria);
}
}
}
private long countByComplexFiltersHelper(Criteria existingCriteria, List<VariantEntityRepositoryFilter> filters) {
List<Criteria> criteriaList = getFiltersCriteria(filters);
criteriaList.add(existingCriteria);
Criteria criteria = new Criteria().andOperator(criteriaList.toArray(new Criteria[criteriaList.size()]));
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.group().count().as("count")
);
AggregationResults<VariantAggregationCount> aggregationResults =
mongoTemplate.aggregate(aggregation, VariantEntity.class, VariantAggregationCount.class);
return aggregationResults.getMappedResults().size() > 0
? aggregationResults.getMappedResults().get(0).getCount() : 0;
}
private class VariantAggregationCount {
private long count;
public long getCount() {
return count;
}
}
private List<Criteria> getFiltersCriteria(List<VariantEntityRepositoryFilter> filters) {
List<Criteria> criteriaList = new ArrayList<>();
for (VariantEntityRepositoryFilter filter : filters) {
criteriaList.add(filter.getCriteria());
}
return criteriaList;
}
private Criteria getRegionsCriteria(List<Region> regions) {
List<Criteria> orRegionCriteria = new ArrayList<>();
regions.forEach(region -> orRegionCriteria.add(
Criteria.where("chr").is(region.getChromosome())
.and("start").lte(region.getEnd()).gt(region.getStart() - MARGIN)
.and("end").gte(region.getStart()).lt(region.getEnd() + MARGIN)));
return new Criteria().orOperator(orRegionCriteria.toArray(new Criteria[orRegionCriteria.size()]));
}
}
| eva-lib/src/main/java/uk/ac/ebi/eva/lib/repository/VariantEntityRepositoryImpl.java | /*
* European Variation Archive (EVA) - Open-access database of all types of genetic
* variation data from all species
*
* Copyright 2016 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.eva.lib.repository;
import org.opencb.biodata.models.feature.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import uk.ac.ebi.eva.commons.models.metadata.VariantEntity;
import uk.ac.ebi.eva.lib.filter.VariantEntityRepositoryFilter;
import java.util.ArrayList;
import java.util.List;
/**
* Concrete implementation of the VariantEntityRepository interface (relationship inferred by Spring),
* due to a custom DBObject to VariantEntity conversion
*
* <p>It also implements the VariantEntityRepositoryCustom interface,
* to provide an explicit implementation of the region query, using a margin for efficiency.
*/
public class VariantEntityRepositoryImpl implements VariantEntityRepositoryCustom {
private MongoTemplate mongoTemplate;
protected static Logger logger = LoggerFactory.getLogger(VariantEntityRepositoryImpl.class);
private final int MARGIN = 5000;
@Autowired
public VariantEntityRepositoryImpl(MongoDbFactory mongoDbFactory, MappingMongoConverter mappingMongoConverter) {
mongoTemplate = new MongoTemplate(mongoDbFactory, mappingMongoConverter);
}
@Override
public List<VariantEntity> findByIdsAndComplexFilters(String id, List<VariantEntityRepositoryFilter> filters,
List<String> exclude, Pageable pageable) {
Query query = new Query(Criteria.where("ids").is(id));
return findByComplexFiltersHelper(query, filters, exclude, pageable);
}
@Override
public Long countByIdsAndComplexFilters(String id, List<VariantEntityRepositoryFilter> filters) {
Criteria criteria = Criteria.where("ids").is(id);
return countByComplexFiltersHelper(criteria, filters);
}
@Override
public List<VariantEntity> findByGenesAndComplexFilters(List<String> geneIds,
List<VariantEntityRepositoryFilter> filters,
List<String> exclude, Pageable pageable) {
Query query = new Query(Criteria.where("annot.xrefs.id").in(geneIds));
return findByComplexFiltersHelper(query, filters, exclude, pageable);
}
@Override
public Long countByGenesAndComplexFilters(List<String> geneIds, List<VariantEntityRepositoryFilter> filters) {
Criteria criteria = Criteria.where("annot.xrefs.id").in(geneIds);
return countByComplexFiltersHelper(criteria, filters);
}
@Override
public List<VariantEntity> findByRegionsAndComplexFilters(List<Region> regions,
List<VariantEntityRepositoryFilter> filters,
List<String> exclude, Pageable pageable) {
Query query = new Query();
Criteria criteria = getRegionsCriteria(regions);
query.addCriteria(criteria);
return findByComplexFiltersHelper(query, filters, exclude, pageable);
}
@Override
public Long countByRegionsAndComplexFilters(List<Region> regions, List<VariantEntityRepositoryFilter> filters) {
Criteria criteria = getRegionsCriteria(regions);
return countByComplexFiltersHelper(criteria, filters);
}
@Override
public List<String> findDistinctChromosomes() {
return (List<String>) mongoTemplate.getCollection(mongoTemplate.getCollectionName(VariantEntity.class))
.distinct("chr");
}
private List<VariantEntity> findByComplexFiltersHelper(Query query, List<VariantEntityRepositoryFilter> filters,
List<String> exclude, Pageable pageable) {
addFilterCriteriaToQuery(query, filters);
ArrayList<String> sortProperties = new ArrayList<String>();
sortProperties.add("chr");
sortProperties.add("start");
query.with(new Sort(Sort.Direction.ASC, sortProperties));
Pageable pageable1 = (pageable != null) ? pageable : new PageRequest(0, 10);
query.with(pageable1);
if (exclude != null && !exclude.isEmpty()) {
exclude.forEach(e -> query.fields().exclude(e));
}
return mongoTemplate.find(query, VariantEntity.class);
}
private void addFilterCriteriaToQuery(Query query, List<VariantEntityRepositoryFilter> filters) {
if (filters.size() > 0){
List<Criteria> criteriaList = getFiltersCriteria(filters);
for (Criteria criteria : criteriaList) {
query.addCriteria(criteria);
}
}
}
private long countByComplexFiltersHelper(Criteria existingCriteria, List<VariantEntityRepositoryFilter> filters) {
List<Criteria> criteriaList = getFiltersCriteria(filters);
if (existingCriteria != null) {
criteriaList.add(existingCriteria);
}
Criteria criteria = new Criteria().andOperator(criteriaList.toArray(new Criteria[criteriaList.size()]));
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.group().count().as("count")
);
AggregationResults<VariantAggregationCount> aggregationResults =
mongoTemplate.aggregate(aggregation, VariantEntity.class, VariantAggregationCount.class);
return aggregationResults.getMappedResults().size() > 0
? aggregationResults.getMappedResults().get(0).getCount() : 0;
}
private class VariantAggregationCount {
private long count;
public long getCount() {
return count;
}
}
private List<Criteria> getFiltersCriteria(List<VariantEntityRepositoryFilter> filters) {
List<Criteria> criteriaList = new ArrayList<>();
for (VariantEntityRepositoryFilter filter : filters) {
criteriaList.add(filter.getCriteria());
}
return criteriaList;
}
private Criteria getRegionsCriteria(List<Region> regions) {
List<Criteria> orRegionCriteria = new ArrayList<>();
regions.forEach(region -> orRegionCriteria.add(
Criteria.where("chr").is(region.getChromosome())
.and("start").lte(region.getEnd()).gt(region.getStart() - MARGIN)
.and("end").gte(region.getStart()).lt(region.getEnd() + MARGIN)));
return new Criteria().orOperator(orRegionCriteria.toArray(new Criteria[orRegionCriteria.size()]));
}
}
| Removed not null check, shouldn't be null
| eva-lib/src/main/java/uk/ac/ebi/eva/lib/repository/VariantEntityRepositoryImpl.java | Removed not null check, shouldn't be null | <ide><path>va-lib/src/main/java/uk/ac/ebi/eva/lib/repository/VariantEntityRepositoryImpl.java
<ide>
<ide> private long countByComplexFiltersHelper(Criteria existingCriteria, List<VariantEntityRepositoryFilter> filters) {
<ide> List<Criteria> criteriaList = getFiltersCriteria(filters);
<del> if (existingCriteria != null) {
<del> criteriaList.add(existingCriteria);
<del> }
<add> criteriaList.add(existingCriteria);
<ide> Criteria criteria = new Criteria().andOperator(criteriaList.toArray(new Criteria[criteriaList.size()]));
<ide>
<ide> Aggregation aggregation = Aggregation.newAggregation( |
|
Java | apache-2.0 | 58108a3a0b83e7f6e1a3a3863ff5a026b4adb14e | 0 | kool79/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,asedunov/intellij-community,caot/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,kool79/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ftomassetti/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,FHannes/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,semonte/intellij-community,fitermay/intellij-community,slisson/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,caot/intellij-community,hurricup/intellij-community,fnouama/intellij-community,amith01994/intellij-community,kdwink/intellij-community,blademainer/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,kdwink/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,signed/intellij-community,asedunov/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,semonte/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,dslomov/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,fnouama/intellij-community,izonder/intellij-community,allotria/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,caot/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,semonte/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,retomerz/intellij-community,amith01994/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,fitermay/intellij-community,da1z/intellij-community,fitermay/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,jagguli/intellij-community,kool79/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,fitermay/intellij-community,kool79/intellij-community,da1z/intellij-community,kdwink/intellij-community,clumsy/intellij-community,da1z/intellij-community,fnouama/intellij-community,izonder/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,signed/intellij-community,da1z/intellij-community,signed/intellij-community,caot/intellij-community,youdonghai/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,clumsy/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,signed/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,slisson/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,apixandru/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,suncycheng/intellij-community,semonte/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,kool79/intellij-community,kdwink/intellij-community,da1z/intellij-community,ahb0327/intellij-community,supersven/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,kool79/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,semonte/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,caot/intellij-community,slisson/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,caot/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,izonder/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vladmm/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,supersven/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,vladmm/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,amith01994/intellij-community,jagguli/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,ibinti/intellij-community,asedunov/intellij-community,amith01994/intellij-community,allotria/intellij-community,orekyuu/intellij-community,slisson/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,allotria/intellij-community,kool79/intellij-community,tmpgit/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,allotria/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,semonte/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,michaelgallacher/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,retomerz/intellij-community,blademainer/intellij-community,xfournet/intellij-community,dslomov/intellij-community,slisson/intellij-community,semonte/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,supersven/intellij-community,kdwink/intellij-community,jagguli/intellij-community,blademainer/intellij-community,asedunov/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,kool79/intellij-community,FHannes/intellij-community,retomerz/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,kool79/intellij-community,izonder/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,apixandru/intellij-community,supersven/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,amith01994/intellij-community,fitermay/intellij-community,ibinti/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,semonte/intellij-community,da1z/intellij-community,slisson/intellij-community,asedunov/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,kool79/intellij-community,orekyuu/intellij-community,caot/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,allotria/intellij-community,xfournet/intellij-community,clumsy/intellij-community,samthor/intellij-community,dslomov/intellij-community,clumsy/intellij-community,slisson/intellij-community,blademainer/intellij-community,asedunov/intellij-community,signed/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,samthor/intellij-community,xfournet/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,izonder/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,semonte/intellij-community,youdonghai/intellij-community,supersven/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,allotria/intellij-community,slisson/intellij-community,vladmm/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,ibinti/intellij-community,semonte/intellij-community,izonder/intellij-community,xfournet/intellij-community,fnouama/intellij-community,samthor/intellij-community,allotria/intellij-community,suncycheng/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,samthor/intellij-community,signed/intellij-community,jagguli/intellij-community,xfournet/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,allotria/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,da1z/intellij-community,ibinti/intellij-community,caot/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,retomerz/intellij-community | package com.intellij.lang.properties.xml;
import com.intellij.lang.properties.IProperty;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.pom.PomRenameableTarget;
import com.intellij.pom.references.PomService;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiInvalidElementAccessException;
import com.intellij.psi.PsiTarget;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
/**
* @author Dmitry Avdeev
* Date: 7/26/11
*/
public class XmlProperty implements IProperty, PomRenameableTarget, PsiTarget {
@NotNull
private final XmlTag myTag;
private final XmlPropertiesFileImpl myPropertiesFile;
public XmlProperty(@NotNull XmlTag tag, XmlPropertiesFileImpl xmlPropertiesFile) {
myTag = tag;
myPropertiesFile = xmlPropertiesFile;
}
@Override
public String getName() {
return myTag.getAttributeValue("key");
}
@Override
public boolean isWritable() {
return myTag.isWritable();
}
@Override
public PsiElement setName(@NotNull String name) {
return myTag.setAttribute("key", name);
}
@Override
public String getKey() {
return getName();
}
@Override
public String getValue() {
return myTag.getValue().getText();
}
@Override
public String getUnescapedValue() {
return getValue();
}
@Override
public String getUnescapedKey() {
return getKey();
}
@Override
public void setValue(@NonNls @NotNull String value) throws IncorrectOperationException {
myTag.getValue().setText(value);
}
@Override
public PropertiesFile getPropertiesFile() throws PsiInvalidElementAccessException {
return myPropertiesFile;
}
@Override
public String getDocCommentText() {
return null;
}
@NotNull
@Override
public PsiElement getPsiElement() {
return PomService.convertToPsi(this);
}
@Override
public void navigate(boolean requestFocus) {
}
@Override
public boolean canNavigate() {
return true;
}
@Override
public boolean canNavigateToSource() {
return true;
}
@Override
public Icon getIcon(int flags) {
return PlatformIcons.PROPERTY_ICON;
}
@Override
public boolean isValid() {
return myTag.isValid();
}
@NotNull
@Override
public PsiElement getNavigationElement() {
return myTag;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
XmlProperty property = (XmlProperty)o;
if (!myTag.equals(property.myTag)) return false;
return true;
}
@Override
public int hashCode() {
return myTag.hashCode();
}
}
| plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/xml/XmlProperty.java | package com.intellij.lang.properties.xml;
import com.intellij.lang.properties.IProperty;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.pom.PomRenameableTarget;
import com.intellij.pom.references.PomService;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiInvalidElementAccessException;
import com.intellij.psi.PsiTarget;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
/**
* @author Dmitry Avdeev
* Date: 7/26/11
*/
public class XmlProperty implements IProperty, PomRenameableTarget, PsiTarget {
@NotNull
private final XmlTag myTag;
private final XmlPropertiesFileImpl myPropertiesFile;
public XmlProperty(@NotNull XmlTag tag, XmlPropertiesFileImpl xmlPropertiesFile) {
myTag = tag;
myPropertiesFile = xmlPropertiesFile;
}
@Override
public String getName() {
return myTag.getAttributeValue("key");
}
@Override
public boolean isWritable() {
return myTag.isWritable();
}
@Override
public PsiElement setName(@NotNull String name) {
return myTag.setAttribute("key", name);
}
@Override
public String getKey() {
return getName();
}
@Override
public String getValue() {
return myTag.getValue().getText();
}
@Override
public String getUnescapedValue() {
return getValue();
}
@Override
public String getUnescapedKey() {
return getKey();
}
@Override
public void setValue(@NonNls @NotNull String value) throws IncorrectOperationException {
myTag.getValue().setText(value);
}
@Override
public PropertiesFile getPropertiesFile() throws PsiInvalidElementAccessException {
return myPropertiesFile;
}
@Override
public String getDocCommentText() {
return null;
}
@NotNull
@Override
public PsiElement getPsiElement() {
return PomService.convertToPsi(this);
}
@Override
public void navigate(boolean requestFocus) {
}
@Override
public boolean canNavigate() {
return true;
}
@Override
public boolean canNavigateToSource() {
return true;
}
@Override
public Icon getIcon(int flags) {
return PlatformIcons.PROPERTY_ICON;
}
@Override
public boolean isValid() {
return myTag.isValid();
}
@NotNull
@Override
public PsiElement getNavigationElement() {
return myTag;
}
}
| XmlProperty.equals depends on underlying tag
| plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/xml/XmlProperty.java | XmlProperty.equals depends on underlying tag | <ide><path>lugins/properties/properties-psi-impl/src/com/intellij/lang/properties/xml/XmlProperty.java
<ide> public PsiElement getNavigationElement() {
<ide> return myTag;
<ide> }
<add>
<add> @Override
<add> public boolean equals(Object o) {
<add> if (this == o) return true;
<add> if (o == null || getClass() != o.getClass()) return false;
<add>
<add> XmlProperty property = (XmlProperty)o;
<add>
<add> if (!myTag.equals(property.myTag)) return false;
<add>
<add> return true;
<add> }
<add>
<add> @Override
<add> public int hashCode() {
<add> return myTag.hashCode();
<add> }
<ide> } |
|
Java | apache-2.0 | 78390a9cb3fdb99e243e6aa95daf7435a19b1d3f | 0 | phanindra1212/gaevfs,tberthel/gaevfs,phanindra1212/gaevfs,tberthel/gaevfs | package com.newatlanta.appengine.junit.locks;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.ApiProxy.Delegate;
import com.newatlanta.appengine.junit.LocalServiceTestCase;
import com.newatlanta.appengine.junit.TestEnvironment;
import com.newatlanta.appengine.locks.ExclusiveLock;
public class ExclusiveLockTestCase extends LocalServiceTestCase {
private ExclusiveLock lock;
@Override
public void setUp() throws Exception {
super.setUp();
lock = new ExclusiveLock( "junit.exclusive.lock" );
}
@Test
public void testTryLock() {
Thread lockThread = createLockThread( Long.MAX_VALUE );
assertFalse( lock.tryLock() );
try {
lock.unlock();
fail( "expected IllegalStateException: lock.unlock()" );
} catch ( IllegalStateException e ) {
}
lockThread.interrupt(); // release the lock
try {
Thread.sleep( 100 ); // give lockThread a chance to run
} catch ( InterruptedException e ) {
}
assertEquals( 0, lock.getOwnerHashCode() );
for ( int i = 0; i < 10; i++ ) {
assertTrue( lock.tryLock() );
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
for ( int i = 0; i < 9; i++ ) {
lock.unlock();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
lock.unlock();
assertEquals( 0, lock.getOwnerHashCode() );
}
@Test
public void testLock() {
createLockThread( 2000 );
for ( int i = 0; i < 10; i++ ) {
lock.lock();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
for ( int i = 0; i < 9; i++ ) {
lock.unlock();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
lock.unlock();
assertEquals( 0, lock.getOwnerHashCode() );
}
@Test
public void testLockInterruptibly() {
createLockThread( 2000 );
try {
for ( int i = 0; i < 10; i++ ) {
lock.lockInterruptibly();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
for ( int i = 0; i < 9; i++ ) {
lock.unlock();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
lock.unlock();
assertEquals( 0, lock.getOwnerHashCode() );
} catch ( InterruptedException e ) {
fail( e.toString() );
}
}
@Test
public void testTryLockLongTimeUnit() {
Thread lockThread = createLockThread( Long.MAX_VALUE );
assertFalse( lock.tryLock( 200, TimeUnit.MILLISECONDS ) );
lockThread.interrupt(); // release the lock
try {
Thread.sleep( 100 ); // give lockThread a chance to run
} catch ( InterruptedException e ) {
}
assertEquals( 0, lock.getOwnerHashCode() );
createLockThread( 1000 );
assertTrue( lock.tryLock( 2, TimeUnit.SECONDS ) );
lock.unlock();
assertEquals( 0, lock.getOwnerHashCode() );
}
private Thread createLockThread( long sleepTime ) {
Thread lockThread = new LockThread( ApiProxy.getDelegate(), sleepTime );
lockThread.start();
try {
Thread.sleep( 200 ); // give lockThread a chance to run
} catch ( InterruptedException e ) {
}
assertTrue( lockThread.isAlive() );
assertEquals( lockThread.hashCode(), lock.getOwnerHashCode() );
return lockThread;
}
/**
* Acquires the lock via the lock() method, sleeps for the specified time or
* until interrupted, then releases the lock.
*/
private class LockThread extends Thread {
@SuppressWarnings("unchecked")
private Delegate delegate;
private long sleepTime;
@SuppressWarnings("unchecked")
private LockThread( Delegate delegate, long sleepTime ) {
super( "LockThread" );
this.delegate = delegate;
this.sleepTime = sleepTime;
}
public void run() {
ApiProxy.setEnvironmentForCurrentThread( new TestEnvironment() );
ApiProxy.setDelegate( delegate );
lock.lock();
try {
sleep( sleepTime );
} catch ( InterruptedException e ) {
} finally {
lock.unlock();
}
}
}
} | test/src/com/newatlanta/appengine/junit/locks/ExclusiveLockTestCase.java | package com.newatlanta.appengine.junit.locks;
import org.junit.Test;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.ApiProxy.Delegate;
import com.newatlanta.appengine.junit.LocalServiceTestCase;
import com.newatlanta.appengine.junit.TestEnvironment;
import com.newatlanta.appengine.locks.ExclusiveLock;
public class ExclusiveLockTestCase extends LocalServiceTestCase {
private ExclusiveLock lock;
@Override
public void setUp() throws Exception {
super.setUp();
lock = new ExclusiveLock( "junit.exclusive.lock" );
}
@Test
public void testTryLock() {
Thread lockThread = createLockThread( Long.MAX_VALUE );
assertFalse( lock.tryLock() );
try {
lock.unlock();
fail( "expected IllegalStateException: lock.unlock()" );
} catch ( IllegalStateException e ) {
}
lockThread.interrupt(); // release the lock
try {
Thread.sleep( 100 ); // give lockThread a chance to run
} catch ( InterruptedException e ) {
}
assertEquals( 0, lock.getOwnerHashCode() );
for ( int i = 0; i < 10; i++ ) {
assertTrue( lock.tryLock() );
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
for ( int i = 0; i < 9; i++ ) {
lock.unlock();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
lock.unlock();
assertEquals( 0, lock.getOwnerHashCode() );
}
@Test
public void testLock() {
createLockThread( 2000 );
for ( int i = 0; i < 10; i++ ) {
lock.lock();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
for ( int i = 0; i < 9; i++ ) {
lock.unlock();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
lock.unlock();
assertEquals( 0, lock.getOwnerHashCode() );
}
@Test
public void testLockInterruptibly() {
createLockThread( 2000 );
try {
for ( int i = 0; i < 10; i++ ) {
lock.lockInterruptibly();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
for ( int i = 0; i < 9; i++ ) {
lock.unlock();
assertEquals( Thread.currentThread().hashCode(), lock.getOwnerHashCode() );
}
lock.unlock();
assertEquals( 0, lock.getOwnerHashCode() );
} catch ( InterruptedException e ) {
fail( e.toString() );
}
}
// @Test
// public void testTryLockLongTimeUnit() {
// fail( "Not yet implemented" );
// }
private Thread createLockThread( long sleepTime ) {
Thread lockThread = new LockThread( ApiProxy.getDelegate(), sleepTime );
lockThread.start();
try {
Thread.sleep( 100 ); // give lockThread a chance to run
} catch ( InterruptedException e ) {
}
assertTrue( lockThread.isAlive() );
assertEquals( lockThread.hashCode(), lock.getOwnerHashCode() );
return lockThread;
}
/**
* Acquires the lock via the lock() method, sleeps for the specified time or
* until interrupted, then releases the lock.
*/
private class LockThread extends Thread {
@SuppressWarnings("unchecked")
private Delegate delegate;
private long sleepTime;
@SuppressWarnings("unchecked")
private LockThread( Delegate delegate, long sleepTime ) {
super( "LockThread" );
this.delegate = delegate;
this.sleepTime = sleepTime;
}
public void run() {
ApiProxy.setEnvironmentForCurrentThread( new TestEnvironment() );
ApiProxy.setDelegate( delegate );
lock.lock();
try {
sleep( sleepTime );
} catch ( InterruptedException e ) {
} finally {
lock.unlock();
}
}
}
} | more junit tests | test/src/com/newatlanta/appengine/junit/locks/ExclusiveLockTestCase.java | more junit tests | <ide><path>est/src/com/newatlanta/appengine/junit/locks/ExclusiveLockTestCase.java
<ide> package com.newatlanta.appengine.junit.locks;
<add>
<add>import java.util.concurrent.TimeUnit;
<ide>
<ide> import org.junit.Test;
<ide>
<ide> }
<ide> }
<ide>
<del> // @Test
<del> // public void testTryLockLongTimeUnit() {
<del> // fail( "Not yet implemented" );
<del> // }
<add> @Test
<add> public void testTryLockLongTimeUnit() {
<add> Thread lockThread = createLockThread( Long.MAX_VALUE );
<add> assertFalse( lock.tryLock( 200, TimeUnit.MILLISECONDS ) );
<add> lockThread.interrupt(); // release the lock
<add> try {
<add> Thread.sleep( 100 ); // give lockThread a chance to run
<add> } catch ( InterruptedException e ) {
<add> }
<add> assertEquals( 0, lock.getOwnerHashCode() );
<add> createLockThread( 1000 );
<add> assertTrue( lock.tryLock( 2, TimeUnit.SECONDS ) );
<add> lock.unlock();
<add> assertEquals( 0, lock.getOwnerHashCode() );
<add> }
<ide>
<ide> private Thread createLockThread( long sleepTime ) {
<ide> Thread lockThread = new LockThread( ApiProxy.getDelegate(), sleepTime );
<ide> lockThread.start();
<ide> try {
<del> Thread.sleep( 100 ); // give lockThread a chance to run
<add> Thread.sleep( 200 ); // give lockThread a chance to run
<ide> } catch ( InterruptedException e ) {
<ide> }
<ide> assertTrue( lockThread.isAlive() ); |
|
Java | bsd-3-clause | accfde90a1babff985b21f6eab4188c726fe911e | 0 | Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo | package org.caleydo.core.view.opengl.canvas.storagebased;
import static org.caleydo.core.view.opengl.canvas.storagebased.HeatMapRenderStyle.SELECTION_Z;
import static org.caleydo.core.view.opengl.renderstyle.GeneralRenderStyle.MOUSE_OVER_COLOR;
import static org.caleydo.core.view.opengl.renderstyle.GeneralRenderStyle.SELECTED_COLOR;
import gleem.linalg.Vec3f;
import java.awt.Point;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Set;
import javax.media.opengl.GL;
import org.caleydo.core.command.ECommandType;
import org.caleydo.core.command.view.opengl.CmdCreateGLEventListener;
import org.caleydo.core.data.collection.storage.EDataRepresentation;
import org.caleydo.core.data.mapping.EIDType;
import org.caleydo.core.data.selection.ESelectionCommandType;
import org.caleydo.core.data.selection.ESelectionType;
import org.caleydo.core.data.selection.Group;
import org.caleydo.core.data.selection.GroupList;
import org.caleydo.core.data.selection.IGroupList;
import org.caleydo.core.data.selection.IVirtualArray;
import org.caleydo.core.data.selection.SelectedElementRep;
import org.caleydo.core.data.selection.SelectionCommand;
import org.caleydo.core.data.selection.SelectionManager;
import org.caleydo.core.data.selection.delta.ISelectionDelta;
import org.caleydo.core.data.selection.delta.IVirtualArrayDelta;
import org.caleydo.core.data.selection.delta.SelectionDelta;
import org.caleydo.core.data.selection.delta.VADeltaItem;
import org.caleydo.core.data.selection.delta.VirtualArrayDelta;
import org.caleydo.core.manager.event.view.group.InterchangeGroupsEvent;
import org.caleydo.core.manager.event.view.group.MergeGroupsEvent;
import org.caleydo.core.manager.event.view.storagebased.UpdateViewEvent;
import org.caleydo.core.manager.general.GeneralManager;
import org.caleydo.core.manager.id.EManagedObjectType;
import org.caleydo.core.manager.picking.EPickingMode;
import org.caleydo.core.manager.picking.EPickingType;
import org.caleydo.core.manager.picking.Pick;
import org.caleydo.core.serialize.ASerializedView;
import org.caleydo.core.util.mapping.color.ColorMapping;
import org.caleydo.core.util.mapping.color.ColorMappingManager;
import org.caleydo.core.util.mapping.color.EColorMappingType;
import org.caleydo.core.util.preferences.PreferenceConstants;
import org.caleydo.core.view.opengl.camera.EProjectionMode;
import org.caleydo.core.view.opengl.camera.IViewFrustum;
import org.caleydo.core.view.opengl.canvas.AGLEventListener;
import org.caleydo.core.view.opengl.canvas.EDetailLevel;
import org.caleydo.core.view.opengl.canvas.GLCaleydoCanvas;
import org.caleydo.core.view.opengl.canvas.listener.UpdateViewListener;
import org.caleydo.core.view.opengl.canvas.remote.IGLCanvasRemoteRendering;
import org.caleydo.core.view.opengl.canvas.remote.listener.GroupInterChangingActionListener;
import org.caleydo.core.view.opengl.canvas.remote.listener.GroupMergingActionListener;
import org.caleydo.core.view.opengl.canvas.remote.receiver.IGroupsInterChangingActionReceiver;
import org.caleydo.core.view.opengl.canvas.remote.receiver.IGroupsMergingActionReceiver;
import org.caleydo.core.view.opengl.canvas.storagebased.listener.GLHierarchicalHeatMapKeyListener;
import org.caleydo.core.view.opengl.mouse.GLMouseListener;
import org.caleydo.core.view.opengl.util.GLCoordinateUtils;
import org.caleydo.core.view.opengl.util.overlay.contextmenu.container.GroupContextMenuItemContainer;
import org.caleydo.core.view.opengl.util.overlay.infoarea.GLInfoAreaManager;
import org.caleydo.core.view.opengl.util.texture.EIconTextures;
import com.sun.opengl.util.BufferUtil;
import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureCoords;
import com.sun.opengl.util.texture.TextureData;
import com.sun.opengl.util.texture.TextureIO;
/**
* Rendering the GLHierarchicalHeatMap with remote rendering support.
*
* @author Bernhard Schlegl
* @author Marc Streit
* @author Alexander Lex
*/
public class GLHierarchicalHeatMap
extends AStorageBasedView
implements IGroupsMergingActionReceiver, IGroupsInterChangingActionReceiver {
private final static float GAP_LEVEL1_2 = 0.6f;
private final static float GAP_LEVEL2_3 = 0.6f;
// private final static float MAX_NUM_SAMPLES = 8f;
private final static int MIN_SAMPLES_PER_TEXTURE = 200;
private final static int MAX_SAMPLES_PER_TEXTURE = 400;
private final static int MIN_SAMPLES_PER_HEATMAP = 14;
private final static int MAX_SAMPLES_PER_HEATMAP = 100;
private final static int MIN_SAMPLES_SKIP_LEVEL_1 = 200;
private final static int MIN_SAMPLES_SKIP_LEVEL_2 = 40;
private int iNumberOfElements = 0;
private int iSamplesPerTexture = 0;
private int iSamplesLevel2;
private int iSamplesPerHeatmap = 0;
private ColorMapping colorMapper;
private EIDType eFieldDataType = EIDType.EXPRESSION_INDEX;
private EIDType eExperimentDataType = EIDType.EXPERIMENT_INDEX;
// array of textures for holding the data samples
private int iNrTextures = 0;
private ArrayList<Texture> AlTextures = new ArrayList<Texture>();
private ArrayList<Integer> iAlNumberSamples = new ArrayList<Integer>();
private Point pickingPointLevel2 = null;
private int iPickedSampleLevel2 = 0;
private int iFirstSampleLevel2 = 0;
private int iLastSampleLevel2 = 0;
private Point pickingPointLevel1 = null;
private int iPickedSampleLevel1 = 0;
private int iFirstSampleLevel1 = 0;
private int iLastSampleLevel1 = 0;
private boolean bRenderCaption;
private float fAnimationScale = 1.0f;
// embedded heat map
private GLHeatMap glHeatMapView;
private boolean bIsHeatmapInFocus = false;
private float fWidthEHM = 0;
// embedded dendrogram
private GLDendrogram glDendrogramView;
private boolean bRedrawTextures = false;
// if only a small number (< 100) of genes is in the data set, level_1 (overViewBar) should not be
// rendered
private boolean bSkipLevel1 = false;
// if only a small number (< 30) of genes is in the data set, level_2 (textures) should not be rendered
private boolean bSkipLevel2 = false;
// dragging stuff level 2
private boolean bIsDraggingActiveLevel2 = false;
private boolean bIsDraggingWholeBlockLevel2 = false;
private boolean bDisableCursorDraggingLevel2 = false;
private boolean bDisableBlockDraggingLevel2 = false;
private int iDraggedCursorLevel2 = 0;
private float fPosCursorFirstElementLevel2 = 0;
private float fPosCursorLastElementLevel2 = 0;
// dragging stuff level 1
private boolean bIsDraggingActiveLevel1 = false;
private boolean bIsDraggingWholeBlockLevel1 = false;
private boolean bDisableCursorDraggingLevel1 = false;
private boolean bDisableBlockDraggingLevel1 = false;
private int iDraggedCursorLevel1 = 0;
private float fPosCursorFirstElementLevel1 = 0;
private float fPosCursorLastElementLevel1 = 0;
// clustering/grouping stuff
private boolean bSplitGroupExp = false;
private boolean bSplitGroupGene = false;
private int iGroupToSplit = 0;
private Point DraggingPoint = null;
// drag&drop stuff for clusters/groups
private boolean bDragDropExpGroup = false;
private boolean bDragDropGeneGroup = false;
private int iExpGroupToDrag = -1;
private int iGeneGroupToDrag = -1;
private GroupMergingActionListener groupMergingActionListener;
private GroupInterChangingActionListener groupInterChangingActionListener;
private UpdateViewListener updateViewListener;
private org.eclipse.swt.graphics.Point upperLeftScreenPos = new org.eclipse.swt.graphics.Point(0, 0);
/**
* Constructor.
*
* @param glCanvas
* @param sLabel
* @param viewFrustum
*/
public GLHierarchicalHeatMap(GLCaleydoCanvas glCanvas, final String sLabel, final IViewFrustum viewFrustum) {
super(glCanvas, sLabel, viewFrustum);
viewType = EManagedObjectType.GL_HIER_HEAT_MAP;
ArrayList<ESelectionType> alSelectionTypes = new ArrayList<ESelectionType>();
alSelectionTypes.add(ESelectionType.NORMAL);
alSelectionTypes.add(ESelectionType.MOUSE_OVER);
alSelectionTypes.add(ESelectionType.SELECTION);
contentSelectionManager = new SelectionManager.Builder(EIDType.EXPRESSION_INDEX).build();
storageSelectionManager = new SelectionManager.Builder(EIDType.EXPERIMENT_INDEX).build();
colorMapper = ColorMappingManager.get().getColorMapping(EColorMappingType.GENE_EXPRESSION);
glKeyListener = new GLHierarchicalHeatMapKeyListener(this);
createHeatMap();
createDendrogram();
}
/**
* Function used in keyListener to forward upDownselection to EHM
*
* @return embedded heat map
*/
public GLHeatMap getEmbeddedHeatMap() {
return glHeatMapView;
}
@Override
public void init(GL gl) {
glHeatMapView.initRemote(gl, this, glMouseListener, null, null);
glDendrogramView.initRemote(gl, this, glMouseListener, null, null);
initTextures(gl);
// activateGroupHandling();
}
/**
* Function responsible for initialization of hierarchy levels. Depending on the amount of samples in the
* data set 2 or 3 levels are used.
*/
private void initHierarchy() {
if (set == null)
return;
iNumberOfElements = contentVA.size();
if (iNumberOfElements < MIN_SAMPLES_SKIP_LEVEL_2) {
bSkipLevel1 = true;
bSkipLevel2 = true;
iSamplesPerHeatmap = iNumberOfElements;
iAlNumberSamples.clear();
iAlNumberSamples.add(iNumberOfElements);
}
else if (iNumberOfElements < MIN_SAMPLES_SKIP_LEVEL_1) {
bSkipLevel1 = true;
bSkipLevel2 = false;
iSamplesPerTexture = iNumberOfElements;
iSamplesLevel2 = iNumberOfElements;
iSamplesPerHeatmap = (int) Math.floor(iSamplesPerTexture / 3);
}
else {
bSkipLevel1 = false;
bSkipLevel2 = false;
iSamplesPerTexture = (int) Math.floor(iNumberOfElements / 5);
if (iSamplesPerTexture > 250)
iSamplesPerTexture = 250;
iSamplesLevel2 = iSamplesPerTexture;
iSamplesPerHeatmap = (int) Math.floor(iSamplesPerTexture / 3);
}
if (iSamplesPerHeatmap > MAX_SAMPLES_PER_HEATMAP)
iSamplesPerTexture = 100;
if (iSamplesPerHeatmap < MIN_SAMPLES_PER_HEATMAP)
iSamplesPerHeatmap = MIN_SAMPLES_PER_HEATMAP;
}
@Override
public void initLocal(GL gl) {
bRenderStorageHorizontally = false;
// Register keyboard listener to GL canvas
GeneralManager.get().getGUIBridge().getDisplay().asyncExec(new Runnable() {
public void run() {
parentGLCanvas.getParentComposite().addKeyListener(glKeyListener);
}
});
iGLDisplayListIndexLocal = gl.glGenLists(1);
iGLDisplayListToCall = iGLDisplayListIndexLocal;
init(gl);
}
@Override
public void initRemote(GL gl, final AGLEventListener glParentView, GLMouseListener glMouseListener,
IGLCanvasRemoteRendering remoteRenderingGLCanvas, GLInfoAreaManager infoAreaManager) {
this.remoteRenderingGLView = remoteRenderingGLCanvas;
// Register keyboard listener to GL canvas
glParentView.getParentGLCanvas().getParentComposite().getDisplay().asyncExec(new Runnable() {
public void run() {
glParentView.getParentGLCanvas().getParentComposite().addKeyListener(glKeyListener);
}
});
bRenderStorageHorizontally = false;
this.glMouseListener = glMouseListener;
iGLDisplayListIndexRemote = gl.glGenLists(1);
iGLDisplayListToCall = iGLDisplayListIndexRemote;
init(gl);
}
/**
* If no selected elements are in the current texture, the function switches the texture
*/
private void setTexture() {
boolean bSetCurrentTexture = true;
// if (AlSelection.size() > 0) {
// for (HeatMapSelection selection : AlSelection) {
//
// if (selection.getTexture() == iSelectorBar && selection.getPos() >= iFirstSampleLevel2
// && selection.getPos() <= iLastSampleLevel2 || selection.getTexture() == iSelectorBar - 1
// && selection.getPos() >= iFirstSampleLevel2 && selection.getPos() <= iLastSampleLevel2) {
// bSetCurrentTexture = false;
// break;
// }
// }
// if (bSetCurrentTexture) {
// iSelectorBar = AlSelection.get(0).getTexture() + 1;
// if (iSelectorBar == iNrSelBar) {
// iSelectorBar--;
// }
// initPosCursorLevel2();
// }
// }
}
private void initPosCursorLevel1() {
int iNumberSample = iNumberOfElements;
if (bSkipLevel1)
iSamplesLevel2 = iNumberSample;
if (iSamplesLevel2 % 2 == 0) {
iFirstSampleLevel1 = iPickedSampleLevel1 - (int) Math.floor(iSamplesLevel2 / 2) + 1;
iLastSampleLevel1 = iPickedSampleLevel1 + (int) Math.floor(iSamplesLevel2 / 2);
}
else {
iFirstSampleLevel1 = iPickedSampleLevel1 - (int) Math.ceil(iSamplesLevel2 / 2);
iLastSampleLevel1 = iPickedSampleLevel1 + (int) Math.floor(iSamplesLevel2 / 2);
}
if (iPickedSampleLevel1 < iSamplesLevel2 / 2) {
iPickedSampleLevel1 = (int) Math.floor(iSamplesLevel2 / 2);
iFirstSampleLevel1 = 0;
iLastSampleLevel1 = iSamplesLevel2 - 1;
}
else if (iPickedSampleLevel1 > iNumberSample - 1 - iSamplesLevel2 / 2) {
iPickedSampleLevel1 = (int) Math.ceil(iNumberSample - iSamplesLevel2 / 2);
iLastSampleLevel1 = iNumberSample - 1;
iFirstSampleLevel1 = iNumberSample - iSamplesLevel2;
}
}
/**
* Init (reset) the positions of cursors used for highlighting selected elements in stage 2 (texture)
*
* @param
*/
private void initPosCursorLevel2() {
if (bSkipLevel2) {
iSamplesPerHeatmap = (int) Math.floor(iSamplesPerTexture / 3);
if (iSamplesPerHeatmap % 2 == 0) {
iFirstSampleLevel2 = iPickedSampleLevel2 - (int) Math.floor(iSamplesPerHeatmap / 2) + 1;
iLastSampleLevel2 = iPickedSampleLevel2 + (int) Math.floor(iSamplesPerHeatmap / 2);
}
else {
iFirstSampleLevel2 = iPickedSampleLevel2 - (int) Math.ceil(iSamplesPerHeatmap / 2);
iLastSampleLevel2 = iPickedSampleLevel2 + (int) Math.floor(iSamplesPerHeatmap / 2);
}
}
iSamplesPerHeatmap = iSamplesLevel2 / 3;
if (iSamplesPerHeatmap >= 3 * MIN_SAMPLES_PER_HEATMAP)
iSamplesPerHeatmap = 2 * MIN_SAMPLES_PER_HEATMAP;
else if (iSamplesPerHeatmap > MIN_SAMPLES_PER_HEATMAP)
iSamplesPerHeatmap = MIN_SAMPLES_PER_HEATMAP;
iPickedSampleLevel2 = (int) Math.floor(iSamplesPerHeatmap / 2);
iFirstSampleLevel2 = 0;
iLastSampleLevel2 = iSamplesPerHeatmap - 1;
}
private void calculateTextures() {
// less than 100 elements in VA, level 1 (overview bar) will not be rendered
if (bSkipLevel1) {
iNrTextures = 1;
AlTextures.clear();
iAlNumberSamples.clear();
Texture tempTextur = null;
AlTextures.add(tempTextur);
iAlNumberSamples.add(iSamplesPerTexture);
}
else {
iNrTextures = (int) Math.ceil(contentVA.size() / iSamplesPerTexture);
AlTextures.clear();
iAlNumberSamples.clear();
Texture tempTextur = null;
for (int i = 0; i < iNrTextures; i++) {
AlTextures.add(tempTextur);
iAlNumberSamples.add(iSamplesPerTexture);
}
}
}
/**
* Init textures, build array of textures used for holding the whole examples from contentSelectionManager
*
* @param
*/
private void initTextures(final GL gl) {
if (bSkipLevel1 && bSkipLevel2)
return;
if (bSkipLevel1) {
AlTextures.clear();
iAlNumberSamples.clear();
Texture tempTextur;
int iTextureHeight = contentVA.size();
int iTextureWidth = storageVA.size();
float fLookupValue = 0;
float fOpacity = 0;
FloatBuffer FbTemp = BufferUtil.newFloatBuffer(iTextureWidth * iTextureHeight * 4);
for (Integer iContentIndex : contentVA) {
for (Integer iStorageIndex : storageVA) {
if (contentSelectionManager.checkStatus(ESelectionType.DESELECTED, iContentIndex)) {
fOpacity = 0.3f;
}
else {
fOpacity = 1.0f;
}
fLookupValue =
set.get(iStorageIndex).getFloat(EDataRepresentation.NORMALIZED, iContentIndex);
float[] fArMappingColor = colorMapper.getColor(fLookupValue);
float[] fArRgba =
{ fArMappingColor[0], fArMappingColor[1], fArMappingColor[2], fOpacity };
FbTemp.put(fArRgba);
}
}
FbTemp.rewind();
TextureData texData =
new TextureData(GL.GL_RGBA /* internalFormat */, iTextureWidth /* height */,
iTextureHeight /* width */, 0 /* border */, GL.GL_RGBA /* pixelFormat */,
GL.GL_FLOAT /* pixelType */, false /* mipmap */, false /* dataIsCompressed */,
false /* mustFlipVertically */, FbTemp, null);
tempTextur = TextureIO.newTexture(0);
tempTextur.updateImage(texData);
AlTextures.add(tempTextur);
iAlNumberSamples.add(iSamplesPerTexture);
}
else {
iNrTextures = (int) Math.ceil((contentVA.size() + 0.0001) / iSamplesPerTexture);
AlTextures.clear();
iAlNumberSamples.clear();
Texture tempTextur;
int iTextureHeight = contentVA.size();
int iTextureWidth = storageVA.size();
iSamplesPerTexture = (int) Math.ceil((iTextureHeight + 0.0001) / iNrTextures);
float fLookupValue = 0;
float fOpacity = 0;
FloatBuffer[] FbTemp = new FloatBuffer[iNrTextures];
for (int itextures = 0; itextures < iNrTextures; itextures++) {
if (itextures == iNrTextures - 1) {
iAlNumberSamples.add(iTextureHeight - iSamplesPerTexture * itextures);
FbTemp[itextures] =
BufferUtil.newFloatBuffer((iTextureHeight - iSamplesPerTexture * itextures)
* iTextureWidth * 4);
}
else {
iAlNumberSamples.add(iSamplesPerTexture);
FbTemp[itextures] = BufferUtil.newFloatBuffer(iSamplesPerTexture * iTextureWidth * 4);
}
}
int iCount = 0;
int iTextureCounter = 0;
for (Integer iContentIndex : contentVA) {
iCount++;
for (Integer iStorageIndex : storageVA) {
if (contentSelectionManager.checkStatus(ESelectionType.DESELECTED, iContentIndex)) {
fOpacity = 0.3f;
}
else {
fOpacity = 1.0f;
}
fLookupValue =
set.get(iStorageIndex).getFloat(EDataRepresentation.NORMALIZED, iContentIndex);
float[] fArMappingColor = colorMapper.getColor(fLookupValue);
float[] fArRgba =
{ fArMappingColor[0], fArMappingColor[1], fArMappingColor[2], fOpacity };
FbTemp[iTextureCounter].put(fArRgba);
}
if (iCount >= iAlNumberSamples.get(iTextureCounter)) {
FbTemp[iTextureCounter].rewind();
TextureData texData =
new TextureData(GL.GL_RGBA /* internalFormat */, iTextureWidth /* height */,
iAlNumberSamples.get(iTextureCounter) /* width */, 0 /* border */,
GL.GL_RGBA /* pixelFormat */, GL.GL_FLOAT /* pixelType */, false /* mipmap */,
false /* dataIsCompressed */, false /* mustFlipVertically */,
FbTemp[iTextureCounter], null);
tempTextur = TextureIO.newTexture(0);
tempTextur.updateImage(texData);
AlTextures.add(tempTextur);
iTextureCounter++;
iCount = 0;
}
}
}
}
/**
* Create embedded heat map
*
* @param
*/
private void createHeatMap() {
CmdCreateGLEventListener cmdView =
(CmdCreateGLEventListener) generalManager.getCommandManager().createCommandByType(
ECommandType.CREATE_GL_HEAT_MAP_3D);
float fHeatMapHeight = viewFrustum.getHeight();
float fHeatMapWidth = viewFrustum.getWidth();
cmdView.setAttributes(EProjectionMode.ORTHOGRAPHIC, 0, fHeatMapHeight, 0, fHeatMapWidth, -20, 20,
set, -1);
cmdView.doCommand();
glHeatMapView = (GLHeatMap) cmdView.getCreatedObject();
GeneralManager.get().getUseCase().addView(glHeatMapView);
glHeatMapView.setUseCase(GeneralManager.get().getUseCase());
glHeatMapView.setRenderedRemote(true);
}
private void createDendrogram() {
CmdCreateGLEventListener cmdView =
(CmdCreateGLEventListener) generalManager.getCommandManager().createCommandByType(
ECommandType.CREATE_GL_DENDROGRAM_HORIZONTAL);
float fHeatMapHeight = viewFrustum.getHeight();
float fHeatMapWidth = viewFrustum.getWidth();
cmdView.setAttributes(EProjectionMode.ORTHOGRAPHIC, 0, fHeatMapHeight, 0, fHeatMapWidth, -20, 20,
set, -1);
cmdView.doCommand();
glDendrogramView = (GLDendrogram) cmdView.getCreatedObject();
GeneralManager.get().getUseCase().addView(glDendrogramView);
glDendrogramView.setUseCase(GeneralManager.get().getUseCase());
glDendrogramView.setRenderedRemote(true);
}
@Override
public void setDetailLevel(EDetailLevel detailLevel) {
super.setDetailLevel(detailLevel);
}
@Override
public void displayLocal(GL gl) {
if (set == null)
return;
pickingManager.handlePicking(this, gl);
if (bIsDisplayListDirtyLocal) {
buildDisplayList(gl, iGLDisplayListIndexLocal);
bIsDisplayListDirtyLocal = false;
}
iGLDisplayListToCall = iGLDisplayListIndexLocal;
display(gl);
checkForHits(gl);
if (eBusyModeState != EBusyModeState.OFF) {
renderBusyMode(gl);
}
}
@Override
public void displayRemote(GL gl) {
if (set == null)
return;
if (bIsDisplayListDirtyRemote) {
buildDisplayList(gl, iGLDisplayListIndexRemote);
bIsDisplayListDirtyRemote = false;
}
iGLDisplayListToCall = iGLDisplayListIndexRemote;
display(gl);
checkForHits(gl);
}
/**
* Function called any time a update is triggered external
*
* @param
*/
@Override
protected void reactOnExternalSelection(boolean scrollToSelection) {
if (scrollToSelection && bSkipLevel1 == false && bSkipLevel2 == false) {
setTexture();
}
}
@Override
protected void reactOnVAChanges(IVirtualArrayDelta delta) {
glHeatMapView.handleVirtualArrayUpdate(delta, getShortInfo());
bRedrawTextures = true;
setDisplayListDirty();
}
/**
* Render caption, simplified version used in (original) heatmap
*
* @param gl
* @param sLabel
* @param fXOrigin
* @param fYOrigin
* @param fFontScaling
*/
private void renderCaption(GL gl, String sLabel, float fXOrigin, float fYOrigin, float fFontScaling) {
textRenderer.setColor(1, 1, 1, 1);
gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT);
gl.glTranslatef(fXOrigin, fYOrigin, 0);
textRenderer.begin3DRendering();
textRenderer.draw3D(sLabel, 0, 0, 0, fFontScaling);
textRenderer.end3DRendering();
gl.glTranslatef(-fXOrigin, -fYOrigin, 0);
gl.glPopAttrib();
}
/**
* Render a curved (nice looking) grey area between two views
*
* @param gl
* @param startpoint1
* @param endpoint1
* @param startpoint2
* @param endpoint2
*/
private void renderSelectedDomain(GL gl, Vec3f startpoint1, Vec3f endpoint1, Vec3f startpoint2,
Vec3f endpoint2) {
float fthickness = (endpoint1.x() - startpoint1.x()) / 4;
float fScalFactor1, fScalFactor2;
if (endpoint1.y() - startpoint1.y() < 0.2f) {
fScalFactor1 = (endpoint1.y() - startpoint1.y()) * 5f;
}
else {
fScalFactor1 = 1;
}
if (startpoint2.y() - endpoint2.y() < 0.2f) {
fScalFactor2 = (startpoint2.y() - endpoint2.y()) * 5f;
}
else {
fScalFactor2 = 1;
}
gl.glColor4f(0.5f, 0.5f, 0.5f, 1f);
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(startpoint1.x(), startpoint1.y(), startpoint1.z());
gl.glVertex3f(startpoint1.x() + 2 * fthickness, startpoint1.y(), startpoint1.z());
gl.glVertex3f(startpoint2.x() + 2 * fthickness, startpoint2.y(), startpoint2.z());
gl.glVertex3f(startpoint2.x(), startpoint2.y(), startpoint2.z());
gl.glEnd();
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(endpoint1.x(), endpoint1.y(), endpoint1.z());
gl.glVertex3f(endpoint1.x() - 1 * fthickness, endpoint1.y(), endpoint1.z());
gl.glVertex3f(endpoint2.x() - 1 * fthickness, endpoint2.y(), endpoint2.z());
gl.glVertex3f(endpoint2.x(), endpoint2.y(), endpoint2.z());
gl.glEnd();
// fill gap
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(endpoint1.x() - 1 * fthickness, endpoint1.y() - 0.1f * fScalFactor1, endpoint1.z());
gl.glVertex3f(endpoint1.x() - 2 * fthickness, endpoint1.y() - 0.1f * fScalFactor1, endpoint1.z());
gl.glVertex3f(endpoint2.x() - 2 * fthickness, endpoint2.y() + 0.1f * fScalFactor2, endpoint2.z());
gl.glVertex3f(endpoint2.x() - 1 * fthickness, endpoint2.y() + 0.1f * fScalFactor2, endpoint2.z());
gl.glEnd();
gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT);
gl.glColor4f(1, 1, 1, 1);
Texture TextureMask = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_MASK_CURVE);
TextureMask.enable();
TextureMask.bind();
TextureCoords texCoordsMask = TextureMask.getImageTexCoords();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoordsMask.right(), texCoordsMask.top());
gl.glVertex3f(startpoint1.x() + 2 * fthickness, startpoint1.y(), startpoint1.z());
gl.glTexCoord2f(texCoordsMask.left(), texCoordsMask.top());
gl.glVertex3f(startpoint1.x() + 1 * fthickness, startpoint1.y(), startpoint1.z());
gl.glTexCoord2f(texCoordsMask.left(), texCoordsMask.bottom());
gl.glVertex3f(startpoint1.x() + 1 * fthickness, startpoint1.y() + 0.1f * fScalFactor1, startpoint1
.z());
gl.glTexCoord2f(texCoordsMask.right(), texCoordsMask.bottom());
gl.glVertex3f(startpoint1.x() + 2 * fthickness, startpoint1.y() + 0.1f * fScalFactor1, startpoint1
.z());
gl.glEnd();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoordsMask.right(), texCoordsMask.top());
gl.glVertex3f(startpoint2.x() + 2 * fthickness, startpoint2.y(), startpoint2.z());
gl.glTexCoord2f(texCoordsMask.left(), texCoordsMask.top());
gl.glVertex3f(startpoint2.x() + 1 * fthickness, startpoint2.y(), startpoint2.z());
gl.glTexCoord2f(texCoordsMask.left(), texCoordsMask.bottom());
gl.glVertex3f(startpoint2.x() + 1 * fthickness, startpoint2.y() - 0.1f * fScalFactor2, startpoint2
.z());
gl.glTexCoord2f(texCoordsMask.right(), texCoordsMask.bottom());
gl.glVertex3f(startpoint2.x() + 2 * fthickness, startpoint2.y() - 0.1f * fScalFactor2, startpoint2
.z());
gl.glEnd();
TextureMask.disable();
Texture TextureMaskNeg = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_MASK_CURVE_NEG);
TextureMaskNeg.enable();
TextureMaskNeg.bind();
TextureCoords texCoordsMaskNeg = TextureMaskNeg.getImageTexCoords();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoordsMaskNeg.left(), texCoordsMaskNeg.bottom());
gl.glVertex3f(endpoint1.x() - 2 * fthickness, endpoint1.y() - 0.1f * fScalFactor1, endpoint1.z());
gl.glTexCoord2f(texCoordsMaskNeg.right(), texCoordsMaskNeg.bottom());
gl.glVertex3f(endpoint1.x() - 1 * fthickness, endpoint1.y() - 0.1f * fScalFactor1, endpoint1.z());
gl.glTexCoord2f(texCoordsMaskNeg.right(), texCoordsMaskNeg.top());
gl.glVertex3f(endpoint1.x() - 1 * fthickness, endpoint1.y(), endpoint1.z());
gl.glTexCoord2f(texCoordsMaskNeg.left(), texCoordsMaskNeg.top());
gl.glVertex3f(endpoint1.x() - 2 * fthickness, endpoint1.y(), endpoint1.z());
gl.glEnd();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoordsMaskNeg.left(), texCoordsMaskNeg.bottom());
gl.glVertex3f(endpoint2.x() - 2 * fthickness, endpoint2.y() + 0.1f * fScalFactor2, endpoint2.z());
gl.glTexCoord2f(texCoordsMaskNeg.right(), texCoordsMaskNeg.bottom());
gl.glVertex3f(endpoint2.x() - 1 * fthickness, endpoint2.y() + 0.1f * fScalFactor2, endpoint2.z());
gl.glTexCoord2f(texCoordsMaskNeg.right(), texCoordsMaskNeg.top());
gl.glVertex3f(endpoint2.x() - 1 * fthickness, endpoint2.y(), endpoint2.z());
gl.glTexCoord2f(texCoordsMaskNeg.left(), texCoordsMaskNeg.top());
gl.glVertex3f(endpoint2.x() - 2 * fthickness, endpoint2.y(), endpoint2.z());
gl.glEnd();
TextureMaskNeg.disable();
gl.glPopAttrib();
}
private void renderClassAssignmentsExperimentsLevel2(final GL gl) {
float fWidth = viewFrustum.getWidth() / 4.0f * fAnimationScale;
int iNrElements = storageVA.size();
float fWidthSamples = fWidth / iNrElements;
float fxpos = 0;
float fHeight = viewFrustum.getHeight();
IGroupList groupList = storageVA.getGroupList();
int iNrClasses = groupList.size();
gl.glLineWidth(1f);
for (int i = 0; i < iNrClasses; i++) {
float classWidth = groupList.get(i).getNrElements() * fWidthSamples;
if (groupList.get(i).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (groupList.get(i).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.HIER_HEAT_MAP_EXPERIMENTS_GROUP, i));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fxpos, fHeight, 0);
gl.glVertex3f(fxpos, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight, 0);
gl.glEnd();
gl.glPopName();
if (i == iNrClasses - 1)
return;
gl.glColor4f(0f, 0f, 1f, 1);
gl.glLineWidth(1f);
gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(fxpos, fHeight, 0);
// gl.glVertex3f(fxpos, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, 0, 0);
gl.glEnd();
fxpos = fxpos + classWidth;
}
}
private void renderClassAssignmentsExperimentsLevel3(final GL gl) {
float fWidth = viewFrustum.getWidth() / 4.0f * fAnimationScale;
int iNrElements = storageVA.size();
float fWidthSamples = fWidthEHM / iNrElements;
float fxpos = 0;
if (bSkipLevel2 == false)
fxpos = fWidth + GAP_LEVEL2_3;
float fHeight = viewFrustum.getHeight();
IGroupList groupList = storageVA.getGroupList();
int iNrClasses = groupList.size();
gl.glLineWidth(1f);
for (int i = 0; i < iNrClasses; i++) {
float classWidth = groupList.get(i).getNrElements() * fWidthSamples;
if (groupList.get(i).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (groupList.get(i).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.HIER_HEAT_MAP_EXPERIMENTS_GROUP, i));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fxpos, fHeight, 0);
gl.glVertex3f(fxpos, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight, 0);
gl.glEnd();
gl.glPopName();
if (i == iNrClasses - 1)
return;
gl.glColor4f(0f, 0f, 1f, 1);
gl.glLineWidth(1f);
gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(fxpos, 0.1f, 0.1f);
// gl.glVertex3f(fxpos, fHeight + 0.1f, 0.1f);
gl.glVertex3f(fxpos + classWidth, fHeight + 0.1f, 0.1f);
gl.glVertex3f(fxpos + classWidth, 0, 0.1f);
gl.glEnd();
fxpos = fxpos + classWidth;
}
}
private void renderClassAssignmentsGenesLevel1(final GL gl) {
float fHeight = viewFrustum.getHeight();
int iNrElements = iNumberOfElements;
float fHeightSamples = fHeight / iNrElements;
float fyPos = fHeight;
IGroupList groupList = contentVA.getGroupList();
int iNrClasses = groupList.size();
gl.glLineWidth(1f);
for (int i = 0; i < iNrClasses; i++) {
float classHeight = groupList.get(i).getNrElements() * fHeightSamples;
if (groupList.get(i).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (groupList.get(i).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP, i));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(-0.1f, fyPos, 0);
gl.glVertex3f(0, fyPos, 0);
gl.glVertex3f(0, fyPos - classHeight, 0);
gl.glVertex3f(-0.1f, fyPos - classHeight, 0);
gl.glEnd();
gl.glPopName();
if (i == iNrClasses - 1)
return;
gl.glColor4f(0f, 0f, 1f, 1);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(-0.1f, fyPos - classHeight, 0.1f);
gl.glVertex3f(0.1f, fyPos - classHeight, 0.1f);
gl.glEnd();
fyPos = fyPos - classHeight;
}
}
private void renderClassAssignmentsGenesLevel2(final GL gl) {
float fHeight = viewFrustum.getHeight();
float fHeightSamples = fHeight / iSamplesLevel2;
float fFieldWith = viewFrustum.getWidth() / 4.0f * fAnimationScale;
// cluster border stuff
int iIdxCluster = 0;
int iCounter = iFirstSampleLevel1;
Group group = contentVA.getGroupList().get(iIdxCluster);
while (group.getNrElements() < iCounter) {
iIdxCluster++;
iCounter -= group.getNrElements();
group = contentVA.getGroupList().get(iIdxCluster);
}
int iCnt = 0;
for (int i = 0; i < iSamplesLevel2; i++) {
if (iCounter == contentVA.getGroupList().get(iIdxCluster).getNrElements()) {
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP,
iIdxCluster));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(-0.1f, fHeight, 0);
gl.glVertex3f(0, fHeight, 0);
gl.glVertex3f(0, fHeight - fHeightSamples * iCnt, 0);
gl.glVertex3f(-0.1f, fHeight - fHeightSamples * iCnt, 0);
gl.glEnd();
gl.glPopName();
gl.glColor4f(0f, 0f, 1f, 1);
gl.glLineWidth(1f);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(-0.1f, fHeight - fHeightSamples * iCnt, 0.1f);
gl.glVertex3f(fFieldWith, fHeight - fHeightSamples * iCnt, 0.1f);
gl.glEnd();
fHeight -= fHeightSamples * iCnt;
iIdxCluster++;
iCounter = 0;
iCnt = 0;
}
iCnt++;
iCounter++;
}
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP,
iIdxCluster));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(-0.1f, fHeight, 0);
gl.glVertex3f(0, fHeight, 0);
gl.glVertex3f(0, 0, 0);
gl.glVertex3f(-0.1f, 0, 0);
gl.glEnd();
gl.glPopName();
}
private void renderClassAssignmentsGenesLevel3(final GL gl) {
float fHeight = viewFrustum.getHeight();
float fHeightSamples = fHeight / iSamplesPerHeatmap;
float fOffsetX = 0;
if (bSkipLevel2 == false)
fOffsetX = GAP_LEVEL2_3;
// cluster border stuff
int iIdxCluster = 0;
int iCounter = iFirstSampleLevel1 + iFirstSampleLevel2;
Group group = contentVA.getGroupList().get(iIdxCluster);
while (group.getNrElements() < iCounter) {
iIdxCluster++;
iCounter -= group.getNrElements();
group = contentVA.getGroupList().get(iIdxCluster);
}
int iCnt = 0;
for (int i = 0; i < iSamplesPerHeatmap; i++) {
if (iCounter == contentVA.getGroupList().get(iIdxCluster).getNrElements()) {
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP,
iIdxCluster));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fOffsetX - 0.1f, fHeight, 0);
gl.glVertex3f(fOffsetX, fHeight, 0);
gl.glVertex3f(fOffsetX, fHeight - fHeightSamples * iCnt, 0);
gl.glVertex3f(fOffsetX - 0.1f, fHeight - fHeightSamples * iCnt, 0);
gl.glEnd();
gl.glPopName();
gl.glColor4f(0f, 0f, 1f, 1);
gl.glLineWidth(1f);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fOffsetX - 0.1f, fHeight - fHeightSamples * iCnt, 0.1f);
gl.glVertex3f(fOffsetX + fWidthEHM, fHeight - fHeightSamples * iCnt, 0.1f);
gl.glEnd();
fHeight -= fHeightSamples * iCnt;
iIdxCluster++;
iCounter = 0;
iCnt = 0;
}
iCnt++;
iCounter++;
}
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP,
iIdxCluster));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fOffsetX - 0.1f, fHeight, 0);
gl.glVertex3f(fOffsetX, fHeight, 0);
gl.glVertex3f(fOffsetX, 0, 0);
gl.glVertex3f(fOffsetX - 0.1f, 0, 0);
gl.glEnd();
gl.glPopName();
}
/**
* Render the first stage of the hierarchy (OverviewBar)
*
* @param gl
*/
private void renderOverviewBar(GL gl) {
float fHeight;
float fWidth;
float fyOffset = 0.0f;
fHeight = viewFrustum.getHeight();
fWidth = 0.1f;
float fHeightElem = fHeight / iNumberOfElements;
float fStep = 0;
gl.glColor4f(1f, 1f, 0f, 1f);
for (int i = 0; i < iNrTextures; i++) {
fStep = fHeightElem * iAlNumberSamples.get(iNrTextures - i - 1);
AlTextures.get(iNrTextures - i - 1).enable();
AlTextures.get(iNrTextures - i - 1).bind();
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
TextureCoords texCoords = AlTextures.get(iNrTextures - i - 1).getImageTexCoords();
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.HIER_HEAT_MAP_TEXTURE_SELECTION, iNrTextures - i));
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords.left(), texCoords.top());
gl.glVertex3f(0, fyOffset, 0);
gl.glTexCoord2d(texCoords.left(), texCoords.bottom());
gl.glVertex3f(0, fyOffset + fStep, 0);
gl.glTexCoord2d(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fWidth, fyOffset + fStep, 0);
gl.glTexCoord2d(texCoords.right(), texCoords.top());
gl.glVertex3f(fWidth, fyOffset, 0);
gl.glEnd();
gl.glPopName();
fyOffset += fStep;
AlTextures.get(iNrTextures - i - 1).disable();
}
}
/**
* Render marker in OverviewBar for visualization of the currently (in stage 2) rendered part
*
* @param gl
*/
private void renderMarkerOverviewBar(final GL gl) {
float fHeight = viewFrustum.getHeight();
float fFieldWith = 0.1f;
Vec3f startpoint1, endpoint1, startpoint2, endpoint2;
float fHeightElem = fHeight / iNumberOfElements;
if (bIsDraggingActiveLevel1 == false && bIsDraggingWholeBlockLevel1 == false) {
fPosCursorFirstElementLevel1 = viewFrustum.getHeight() - iFirstSampleLevel1 * fHeightElem;
fPosCursorLastElementLevel1 = viewFrustum.getHeight() - (iLastSampleLevel1 + 1) * fHeightElem;
}
// int iStartElem = 0;
// int iLastElem = 0;
//
// boolean colorToggle = true;
//
// gl.glLineWidth(2f);
// for (int currentTextureIdx = 0; currentTextureIdx < iNrTextures; currentTextureIdx++) {
//
// iStartElem = iLastElem;
// iLastElem += iAlNumberSamples.get(currentTextureIdx);
//
// if (colorToggle)
// gl.glColor4f(0f, 0f, 0f, 1f);
// else
// gl.glColor4f(1f, 1f, 1f, 1f);
//
// colorToggle = (colorToggle == true) ? false : true;
//
// gl.glBegin(GL.GL_LINE_LOOP);
// gl.glVertex3f(0, fHeight - fHeightElem * iStartElem, 0);
// gl.glVertex3f(fFieldWith, fHeight - fHeightElem * iStartElem, 0);
// // Different handling for last texture. To avoid problems with visualization.
// if (currentTextureIdx == iNrTextures - 1) {
// gl.glVertex3f(fFieldWith, (fHeight - fHeightElem * iLastElem), 0);
// gl.glVertex3f(0, (fHeight - fHeightElem * iLastElem), 0);
// }
// else {
// gl.glVertex3f(fFieldWith, (fHeight - fHeightElem * iLastElem) + 0.01f, 0);
// gl.glVertex3f(0, (fHeight - fHeightElem * iLastElem) + 0.01f, 0);
// }
// gl.glEnd();
// }
// selected domain level 1
startpoint1 = new Vec3f(fFieldWith, fPosCursorFirstElementLevel1, 0);
endpoint1 = new Vec3f(GAP_LEVEL1_2, fHeight, 0);
startpoint2 = new Vec3f(fFieldWith, fPosCursorLastElementLevel1, 0);
endpoint2 = new Vec3f(GAP_LEVEL1_2, 0, 0);
renderSelectedDomain(gl, startpoint1, endpoint1, startpoint2, endpoint2);
gl.glColor4fv(MOUSE_OVER_COLOR, 0);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, fPosCursorFirstElementLevel1, 0);
gl.glVertex3f(fFieldWith, fPosCursorFirstElementLevel1, 0);
gl.glVertex3f(fFieldWith, fPosCursorLastElementLevel1, 0);
gl.glVertex3f(0, fPosCursorLastElementLevel1, 0);
// gl.glVertex3f(0, viewFrustum.getHeight() - iFirstSampleLevel1 * fHeightElem, 0);
// gl.glVertex3f(fFieldWith, viewFrustum.getHeight() - iFirstSampleLevel1 * fHeightElem, 0);
// gl.glVertex3f(fFieldWith, viewFrustum.getHeight() - (iLastSampleLevel1 + 1) * fHeightElem, 0);
// gl.glVertex3f(0, viewFrustum.getHeight() - (iLastSampleLevel1 + 1) * fHeightElem, 0);
gl.glEnd();
gl.glBegin(GL.GL_LINE_LOOP);
gl
.glVertex3f(0, viewFrustum.getHeight() - (iFirstSampleLevel1 + iFirstSampleLevel2) * fHeightElem,
0);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight() - (iFirstSampleLevel1 + iFirstSampleLevel2)
* fHeightElem, 0);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- ((iFirstSampleLevel1 + iLastSampleLevel2) + 1) * fHeightElem, 0);
gl.glVertex3f(0, viewFrustum.getHeight() - ((iFirstSampleLevel1 + iLastSampleLevel2) + 1)
* fHeightElem, 0);
gl.glEnd();
if (bRenderCaption == true) {
renderCaption(gl, "nr:" + iSamplesLevel2, 0.0f, viewFrustum.getHeight() - iPickedSampleLevel1
* fHeightElem, 0.004f);
}
gl.glColor4f(1f, 1f, 1f, 1f);
}
/**
* Render marker next to OverviewBar for visualization of selected elements in the data set
*
* @param gl
*/
private void renderSelectedElementsOverviewBar(GL gl) {
float fHeight = viewFrustum.getHeight();
float fBarWidth = 0.1f;
float fHeightElem = fHeight / contentVA.size();
// for (HeatMapSelection selection : AlSelection) {
// if (selection.getSelectionType() == ESelectionType.MOUSE_OVER) {
// gl.glColor4fv(MOUSE_OVER_COLOR, 0);
// }
// else if (selection.getSelectionType() == ESelectionType.SELECTION) {
// gl.glColor4fv(SELECTED_COLOR, 0);
// }
// // else if (selection.getSelectionType() == ESelectionType.DESELECTED) {
// // gl.glColor4f(1, 1, 1, 0.5f);
// // }
// else
// continue;
//
// float fStartElem = 0;
//
// for (int i = 0; i < selection.getTexture(); i++)
// fStartElem += iAlNumberSamples.get(i);
//
// // elements in overview bar
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(fBarWidth, fHeight - fHeightElem * fStartElem, 0.001f);
// gl.glVertex3f(fBarWidth + 0.1f, fHeight - fHeightElem * fStartElem, 0.001f);
// gl.glVertex3f(fBarWidth + 0.1f, fHeight - fHeightElem
// * (fStartElem + iAlNumberSamples.get(selection.getTexture())), 0.001f);
// gl.glVertex3f(fBarWidth, fHeight - fHeightElem
// * (fStartElem + iAlNumberSamples.get(selection.getTexture())), 0.001f);
// gl.glEnd();
// }
// gl.glColor4f(1f, 1f, 0f, 1f);
}
/**
* Render the second stage of the hierarchy (Texture)
*
* @param gl
*/
private void renderTextureHeatMap(GL gl) {
float fHeight;
float fWidth;
fHeight = viewFrustum.getHeight();
fWidth = viewFrustum.getWidth() / 4.0f * fAnimationScale;
int iFirstTexture = 0;
int iLastTexture = 0;
int iFirstElementFirstTexture = iFirstSampleLevel1;
int iLastElementLastTexture = iLastSampleLevel1;
int iNrTexturesInUse = 0;
gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_FIELD_SELECTION, 1));
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
if (bSkipLevel1) {
Texture TexTemp1 = AlTextures.get(0);
TexTemp1.enable();
TexTemp1.bind();
TextureCoords texCoords1 = TexTemp1.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords1.left(), texCoords1.top());
gl.glVertex3f(0, 0, 0);
gl.glTexCoord2d(texCoords1.left(), texCoords1.bottom());
gl.glVertex3f(0, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.bottom());
gl.glVertex3f(fWidth, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.top());
gl.glVertex3f(fWidth, 0, 0);
gl.glEnd();
TexTemp1.disable();
}
else {
while (iAlNumberSamples.get(iFirstTexture) < iFirstElementFirstTexture) {
iFirstElementFirstTexture -= iAlNumberSamples.get(iFirstTexture);
if (iFirstTexture < iAlNumberSamples.size() - 1)
iFirstTexture++;
}
while (iLastElementLastTexture > iAlNumberSamples.get(iLastTexture)) {
iLastElementLastTexture -= iAlNumberSamples.get(iLastTexture);
iLastTexture++;
if (iLastTexture == iAlNumberSamples.size() - 1) {
if (iLastElementLastTexture > iSamplesPerTexture)
iLastElementLastTexture = iSamplesPerTexture;
break;
}
}
iNrTexturesInUse = iLastTexture - iFirstTexture + 1;
// System.out.println("\niSamplesPerTexture: " + iSamplesPerTexture + " isamplesLevel2: "
// + iSamplesLevel2);
// System.out.println("iFirstTexture: " + iFirstTexture);
// System.out.println("iFirstElementFirstTexture: " + iFirstElementFirstTexture);
// System.out.println("iLastTexture: " + iLastTexture);
// System.out.println("iLastElementLastTexture: " + iLastElementLastTexture);
// System.out.println("iNrTexturesInUse: " + iNrTexturesInUse);
if (iNrTexturesInUse == 1) {
double dScalingFirstElement = (iFirstElementFirstTexture + 0.001) / iSamplesLevel2;
double dScalingLastElement = (iLastElementLastTexture + 0.001) / iSamplesLevel2;
// System.out.println("dScalingFirstElement: " + dScalingFirstElement);
// System.out.println("dScalingLastElement: " + dScalingLastElement);
Texture TexTemp1 = AlTextures.get(iFirstTexture);
TexTemp1.enable();
TexTemp1.bind();
TextureCoords texCoords1 = TexTemp1.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords1.left(), texCoords1.top() * dScalingLastElement);
gl.glVertex3f(0, 0, 0);
gl.glTexCoord2d(texCoords1.left(), texCoords1.bottom() * dScalingFirstElement);
gl.glVertex3f(0, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.bottom() * dScalingFirstElement);
gl.glVertex3f(fWidth, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.top() * dScalingLastElement);
gl.glVertex3f(fWidth, 0, 0);
gl.glEnd();
TexTemp1.disable();
}
else if (iNrTexturesInUse == 2) {
// float fScalingFirstTexture =
// (iSamplesPerTexture - iFirstElementFirstTexture + 0.001f) / iSamplesLevel2;
float fScalingLastTexture = (iLastElementLastTexture + 0.001f) / iSamplesLevel2;
// float fRatioFirstTexture =
// (iSamplesPerTexture - iFirstElementFirstTexture + 0.001f) / iSamplesPerTexture;
// float fRatioLastTexture = (iLastElementLastTexture + 0.001f) / iSamplesPerTexture;
float fRatioFirstTexture =
(iSamplesPerTexture - iFirstElementFirstTexture + 0.001f)
/ iAlNumberSamples.get(iFirstTexture);
float fRatioLastTexture =
(iLastElementLastTexture + 0.001f) / iAlNumberSamples.get(iLastTexture);
// System.out.println("dScalingFirstElement: " + dScalingFirstElement);
// System.out.println("dScalingLastElement: " + dScalingLastElement);
// double sum = dScalingLastElement + dScalingFirstElement;
// System.out.println("sum : " + sum);
Texture TexTemp1 = AlTextures.get(iFirstTexture);
TexTemp1.enable();
TexTemp1.bind();
TextureCoords texCoords1 = TexTemp1.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords1.left(), texCoords1.top());
gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords1.left(), texCoords1.bottom() + (1 - fRatioFirstTexture));
gl.glVertex3f(0, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.bottom() + (1 - fRatioFirstTexture));
gl.glVertex3f(fWidth, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.top());
gl.glVertex3f(fWidth, fHeight * fScalingLastTexture, 0);
gl.glEnd();
TexTemp1.disable();
// gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(viewFrustum.getWidth(), fHeight * fScalingLastTexture, 0);
// gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
// gl.glEnd();
Texture TexTemp2 = AlTextures.get(iLastTexture);
TexTemp2.enable();
TexTemp2.bind();
TextureCoords texCoords2 = TexTemp2.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords2.left(), texCoords2.top() * fRatioLastTexture);
gl.glVertex3f(0, 0, 0);
gl.glTexCoord2d(texCoords2.left(), texCoords2.bottom());
gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords2.right(), texCoords2.bottom());
gl.glVertex3f(fWidth, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords2.right(), texCoords2.top() * fRatioLastTexture);
gl.glVertex3f(fWidth, 0, 0);
gl.glEnd();
TexTemp2.disable();
}
else if (iNrTexturesInUse == 3) {
float fScalingFirstTexture =
(iSamplesPerTexture - iFirstElementFirstTexture + 0.001f) / iSamplesLevel2;
float fScalingLastTexture = (iLastElementLastTexture + 0.001f) / iSamplesLevel2;
// float fRatioFirstTexture =
// (iSamplesPerTexture - iFirstElementFirstTexture + 0.001f) / iSamplesPerTexture;
// float fRatioLastTexture = (iLastElementLastTexture + 0.001f) / iSamplesPerTexture;
float fRatioFirstTexture =
(iSamplesPerTexture - iFirstElementFirstTexture + 0.001f)
/ iAlNumberSamples.get(iFirstTexture);
float fRatioLastTexture =
(iLastElementLastTexture + 0.001f) / iAlNumberSamples.get(iLastTexture);
Texture TexTemp1 = AlTextures.get(iFirstTexture);
TexTemp1.enable();
TexTemp1.bind();
TextureCoords texCoords1 = TexTemp1.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords1.left(), texCoords1.top());
gl.glVertex3f(0, fHeight * (1 - fScalingFirstTexture), 0);
gl.glTexCoord2d(texCoords1.left(), texCoords1.bottom() + (1 - fRatioFirstTexture));
gl.glVertex3f(0, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.bottom() + (1 - fRatioFirstTexture));
gl.glVertex3f(fWidth, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.top());
gl.glVertex3f(fWidth, fHeight * (1 - fScalingFirstTexture), 0);
gl.glEnd();
TexTemp1.disable();
// gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(viewFrustum.getWidth(), fHeight * (1 - fScalingFirstTexture), 0);
// gl.glVertex3f(0, fHeight * (1 - fScalingFirstTexture), 0);
// gl.glEnd();
Texture TexTemp2 = AlTextures.get(iFirstTexture + 1);
TexTemp2.enable();
TexTemp2.bind();
TextureCoords texCoords2 = TexTemp2.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords2.left(), texCoords2.top());
gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords2.left(), texCoords2.bottom());
gl.glVertex3f(0, fHeight * (1 - fScalingFirstTexture), 0);
gl.glTexCoord2d(texCoords2.right(), texCoords2.bottom());
gl.glVertex3f(fWidth, fHeight * (1 - fScalingFirstTexture), 0);
gl.glTexCoord2d(texCoords2.right(), texCoords2.top());
gl.glVertex3f(fWidth, fHeight * fScalingLastTexture, 0);
gl.glEnd();
TexTemp2.disable();
// gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(viewFrustum.getWidth(), fHeight * fScalingLastTexture, 0);
// gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
// gl.glEnd();
Texture TexTemp3 = AlTextures.get(iLastTexture);
TexTemp3.enable();
TexTemp3.bind();
TextureCoords texCoords3 = TexTemp3.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords3.left(), texCoords3.top() * fRatioLastTexture);
gl.glVertex3f(0, 0, 0);
gl.glTexCoord2d(texCoords3.left(), texCoords3.bottom());
gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords3.right(), texCoords3.bottom());
gl.glVertex3f(fWidth, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords3.right(), texCoords3.top() * fRatioLastTexture);
gl.glVertex3f(fWidth, 0, 0);
gl.glEnd();
TexTemp3.disable();
}
else {
// FIXME: do something smart
System.out.println("something went wrong !!");
}
}
gl.glPopName();
gl.glPopAttrib();
}
/**
* Render marker in Texture for visualization of the currently (in stage 3) rendered part
*
* @param gl
*/
private void renderMarkerTexture(final GL gl) {
float fFieldWith = viewFrustum.getWidth() / 4.0f * fAnimationScale;
// float fHeightSampleLevel2 = viewFrustum.getHeight() / (iAlNumberSamples.get(iSelectorBar - 1));// *
// 2);
float fHeightSampleLevel2 = viewFrustum.getHeight() / iSamplesLevel2;
Vec3f startpoint1, endpoint1, startpoint2, endpoint2;
gl.glColor4f(1, 1, 0, 1);
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, viewFrustum.getHeight() - iFirstSampleLevel2 * fHeightSampleLevel2, 0);
gl.glVertex3f(fFieldWith, viewFrustum.getHeight() - iFirstSampleLevel2 * fHeightSampleLevel2, 0);
gl.glVertex3f(fFieldWith, viewFrustum.getHeight() - (iLastSampleLevel2 + 1) * fHeightSampleLevel2, 0);
gl.glVertex3f(0, viewFrustum.getHeight() - (iLastSampleLevel2 + 1) * fHeightSampleLevel2, 0);
// gl.glVertex3f(0, fPosCursorFirstElementLevel3, 0);
// gl.glVertex3f(fFieldWith, fPosCursorFirstElementLevel3, 0);
// gl.glVertex3f(fFieldWith, fPosCursorLastElementLevel3, 0);
// gl.glVertex3f(0, fPosCursorLastElementLevel3, 0);
gl.glEnd();
if (bIsDraggingActiveLevel2 == false) {
fPosCursorFirstElementLevel2 = viewFrustum.getHeight() - iFirstSampleLevel2 * fHeightSampleLevel2;
fPosCursorLastElementLevel2 =
viewFrustum.getHeight() - (iLastSampleLevel2 + 1) * fHeightSampleLevel2;
}
startpoint1 =
new Vec3f(fFieldWith, viewFrustum.getHeight() - iFirstSampleLevel2 * fHeightSampleLevel2, 0);
endpoint1 = new Vec3f(fFieldWith + GAP_LEVEL2_3, viewFrustum.getHeight(), 0);
startpoint2 =
new Vec3f(fFieldWith, viewFrustum.getHeight() - (iLastSampleLevel2 + 1) * fHeightSampleLevel2, 0);
endpoint2 = new Vec3f(fFieldWith + GAP_LEVEL2_3, 0.0f, 0);
renderSelectedDomain(gl, startpoint1, endpoint1, startpoint2, endpoint2);
Texture tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_MIDDLE);
tempTexture.enable();
tempTexture.bind();
float fYCoord = viewFrustum.getHeight() / 2;
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl
.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_INFOCUS_SELECTION,
1));
if (bIsHeatmapInFocus) {
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(fFieldWith + 0.3f, fYCoord - 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fFieldWith + 0.3f, fYCoord + 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(fFieldWith + 0.4f, fYCoord + 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(fFieldWith + 0.4f, fYCoord - 0.3f, 0.1f);
gl.glEnd();
}
else {
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(fFieldWith + 0.3f, fYCoord - 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(fFieldWith + 0.3f, fYCoord + 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fFieldWith + 0.4f, fYCoord + 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(fFieldWith + 0.4f, fYCoord - 0.3f, 0.1f);
gl.glEnd();
}
gl.glPopName();
tempTexture.disable();
if (bRenderCaption == true) {
renderCaption(gl, "Number Samples:" + iSamplesPerHeatmap, 0.0f, viewFrustum.getHeight()
- iPickedSampleLevel2 * fHeightSampleLevel2, 0.005f);
bRenderCaption = false;
}
}
/**
* Render marker in Texture (level 2) for visualization of selected elements in the data set
*
* @param gl
*/
private void renderSelectedElementsTexture(GL gl) {
float fFieldWith = viewFrustum.getWidth() / 4.0f * fAnimationScale;
float fHeightSample = viewFrustum.getHeight() / iSamplesLevel2;
float fExpWidth = fFieldWith / storageVA.size();
gl.glEnable(GL.GL_LINE_STIPPLE);
gl.glLineStipple(2, (short) 0xAAAA);
gl.glColor4fv(MOUSE_OVER_COLOR, 0);
Set<Integer> selectedSet = storageSelectionManager.getElements(ESelectionType.MOUSE_OVER);
int iColumnIndex = 0;
for (int iTempLine : storageVA) {
for (Integer iCurrentLine : selectedSet) {
if (iTempLine == iCurrentLine) {
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(iColumnIndex * fExpWidth, 0, SELECTION_Z);
gl.glVertex3f((iColumnIndex + 1) * fExpWidth, 0, SELECTION_Z);
gl.glVertex3f((iColumnIndex + 1) * fExpWidth, viewFrustum.getHeight(), SELECTION_Z);
gl.glVertex3f(iColumnIndex * fExpWidth, viewFrustum.getHeight(), SELECTION_Z);
gl.glEnd();
}
}
iColumnIndex++;
}
gl.glColor4fv(SELECTED_COLOR, 0);
selectedSet = storageSelectionManager.getElements(ESelectionType.SELECTION);
int iLineIndex = 0;
for (int iTempLine : storageVA) {
for (Integer iCurrentLine : selectedSet) {
if (iTempLine == iCurrentLine) {
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(iLineIndex * fExpWidth, 0, SELECTION_Z);
gl.glVertex3f((iLineIndex + 1) * fExpWidth, 0, SELECTION_Z);
gl.glVertex3f((iLineIndex + 1) * fExpWidth, viewFrustum.getHeight(), SELECTION_Z);
gl.glVertex3f(iLineIndex * fExpWidth, viewFrustum.getHeight(), SELECTION_Z);
gl.glEnd();
}
}
iLineIndex++;
}
gl.glDisable(GL.GL_LINE_STIPPLE);
Set<Integer> setMouseOverElements = contentSelectionManager.getElements(ESelectionType.MOUSE_OVER);
gl.glColor4fv(MOUSE_OVER_COLOR, 0);
for (Integer mouseOverElement : setMouseOverElements) {
int selectedElement = contentVA.indexOf(mouseOverElement.intValue());
if (selectedElement >= iFirstSampleLevel1 && selectedElement <= iLastSampleLevel1) {
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(-0.0f, viewFrustum.getHeight() - (selectedElement - iFirstSampleLevel1)
* fHeightSample, SELECTION_Z);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- (selectedElement - iFirstSampleLevel1) * fHeightSample, SELECTION_Z);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- (selectedElement + 1 - iFirstSampleLevel1) * fHeightSample, SELECTION_Z);
gl.glVertex3f(-0.0f, viewFrustum.getHeight() - (selectedElement + 1 - iFirstSampleLevel1)
* fHeightSample, SELECTION_Z);
gl.glEnd();
}
}
Set<Integer> setSelectedElements = contentSelectionManager.getElements(ESelectionType.SELECTION);
gl.glColor4fv(SELECTED_COLOR, 0);
for (Integer iSelectedElement : setSelectedElements) {
int selectedElement = contentVA.indexOf(iSelectedElement.intValue());
if (selectedElement >= iFirstSampleLevel1 && selectedElement <= iLastSampleLevel1) {
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(-0.0f, viewFrustum.getHeight() - (selectedElement - iFirstSampleLevel1)
* fHeightSample, SELECTION_Z);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- (selectedElement - iFirstSampleLevel1) * fHeightSample, SELECTION_Z);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- (selectedElement + 1 - iFirstSampleLevel1) * fHeightSample, SELECTION_Z);
gl.glVertex3f(-0.0f, viewFrustum.getHeight() - (selectedElement + 1 - iFirstSampleLevel1)
* fHeightSample, SELECTION_Z);
gl.glEnd();
}
}
}
/**
* Render cursor used for controlling level 1
*
* @param gl
*/
private void renderCursorLevel1(final GL gl) {
gl.glTranslatef(0.1f, 0, 0);
Texture tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_SMALL);
tempTexture.enable();
tempTexture.bind();
TextureCoords texCoords = tempTexture.getImageTexCoords();
// Polygon for iFirstElement-Cursor
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_CURSOR_LEVEL1, 1));
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel1, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel1, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel1 + 0.1f, 0);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel1 + 0.1f, 0);
gl.glEnd();
gl.glPopName();
// Polygon for iLastElement-Cursor
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_CURSOR_LEVEL1, 2));
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(0.0f, fPosCursorLastElementLevel1, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel1, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel1 - 0.1f, 0);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.0f, fPosCursorLastElementLevel1 - 0.1f, 0);
gl.glEnd();
gl.glPopName();
// fill gap between cursor
gl.glColor4f(0f, 0f, 0f, 0.45f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_BLOCK_CURSOR_LEVEL1,
1));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel1, 0);
gl.glVertex3f(0.0f, fPosCursorLastElementLevel1, 0);
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel1, 0);
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel1, 0);
gl.glEnd();
gl.glPopName();
gl.glPopAttrib();
tempTexture.disable();
gl.glTranslatef(-0.1f, 0, 0);
}
/**
* Render cursor used for controlling hierarchical heatmap (e.g. next Texture, previous Texture, set
* heatmap in focus)
*
* @param gl
*/
private void renderCursorLevel2(final GL gl) {
float fHeight = viewFrustum.getHeight();
float fWidth = viewFrustum.getWidth() / 4.0f;
Texture tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_SIDE);
tempTexture.enable();
tempTexture.bind();
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT);
gl.glColor4f(1f, 1, 1, 1f);
gl.glTranslatef(-viewFrustum.getWidth() / 4.0f * fAnimationScale, 0, 0);
// if (iSelectorBar != 1) {
// // Polygon for selecting previous texture
// gl.glPushName(pickingManager
// .getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_TEXTURE_CURSOR, 1));
// // left
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(0.0f, fHeight, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(0.1f, fHeight, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(0.1f, fHeight + 0.1f, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(0.0f, fHeight + 0.1f, 0);
// gl.glEnd();
//
// // right
// if (bIsHeatmapInFocus) {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 5 - 0.1f, fHeight, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 5, fHeight, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 5, fHeight + 0.1f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 5 - 0.1f, fHeight + 0.1f, 0);
// gl.glEnd();
// }
// else {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth - 0.1f, fHeight, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth, fHeight, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth, fHeight + 0.1f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth - 0.1f, fHeight + 0.1f, 0);
// gl.glEnd();
// }
//
// tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_MIDDLE);
// tempTexture.enable();
// tempTexture.bind();
//
// texCoords = tempTexture.getImageTexCoords();
// // middle
// if (bIsHeatmapInFocus) {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 10 - 0.15f, fHeight, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 10 + 0.15f, fHeight, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 10 + 0.15f, fHeight + 0.1f, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 10 - 0.15f, fHeight + 0.1f, 0);
// gl.glEnd();
// }
// else {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 2 - 0.15f, fHeight, 0.001f);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 2 + 0.15f, fHeight, 0.001f);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 2 + 0.15f, fHeight + 0.1f, 0.001f);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 2 - 0.15f, fHeight + 0.1f, 0.001f);
// gl.glEnd();
//
// // fill gap between middle and side
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(0.1f, fHeight, 0);
// gl.glVertex3f(fWidth / 2 - 0.15f, fHeight, 0);
// gl.glVertex3f(fWidth / 2 - 0.15f, fHeight + 0.1f, 0);
// gl.glVertex3f(0.1f, fHeight + 0.1f, 0);
// gl.glEnd();
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(fWidth - 0.1f, fHeight, 0);
// gl.glVertex3f(fWidth / 2 + 0.15f, fHeight, 0);
// gl.glVertex3f(fWidth / 2 + 0.15f, fHeight + 0.1f, 0);
// gl.glVertex3f(fWidth - 0.1f, fHeight + 0.1f, 0);
// gl.glEnd();
// }
// gl.glPopName();
// }
//
// tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_SIDE);
// tempTexture.enable();
// tempTexture.bind();
//
// texCoords = tempTexture.getImageTexCoords();
//
// // if (iSelectorBar != iNrSelBar - 1) {
// if (iSelectorBar != iNrSelBar) {
// // Polygon for selecting next texture
// gl.glPushName(pickingManager
// .getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_TEXTURE_CURSOR, 2));
// // left
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(0.0f, 0.0f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(0.1f, 0.0f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(0.1f, -0.1f, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(0.0f, -0.1f, 0);
// gl.glEnd();
//
// // right
// if (bIsHeatmapInFocus) {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 5 - 0.1f, 0, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 5, 0, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 5, -0.1f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 5 - 0.1f, -0.1f, 0);
// gl.glEnd();
// }
// else {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth - 0.1f, 0, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth, 0, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth, -0.1f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth - 0.1f, -0.1f, 0);
// gl.glEnd();
// }
//
// tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_MIDDLE);
// tempTexture.enable();
// tempTexture.bind();
//
// texCoords = tempTexture.getImageTexCoords();
// // middle
// if (bIsHeatmapInFocus) {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 10 - 0.15f, 0, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 10 + 0.15f, 0, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 10 + 0.15f, -0.1f, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 10 - 0.15f, -0.1f, 0);
// gl.glEnd();
// }
// else {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 2 - 0.15f, 0, 0.001f);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 2 + 0.15f, 0, 0.001f);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 2 + 0.15f, -0.1f, 0.001f);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 2 - 0.15f, -0.1f, 0.001f);
// gl.glEnd();
//
// // fill gap between middle and side
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(0.1f, 0, 0);
// gl.glVertex3f(fWidth / 2 - 0.15f, 0, 0);
// gl.glVertex3f(fWidth / 2 - 0.15f, -0.1f, 0);
// gl.glVertex3f(0.1f, -0.1f, 0);
// gl.glEnd();
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(fWidth - 0.1f, 0, 0);
// gl.glVertex3f(fWidth / 2 + 0.15f, 0, 0);
// gl.glVertex3f(fWidth / 2 + 0.15f, -0.1f, 0);
// gl.glVertex3f(fWidth - 0.1f, -0.1f, 0);
// gl.glEnd();
// }
// gl.glPopName();
// }
//
gl.glTranslatef(viewFrustum.getWidth() / 4.0f * fAnimationScale, 0, 0);
tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_SMALL);
tempTexture.enable();
tempTexture.bind();
texCoords = tempTexture.getImageTexCoords();
// Polygon for iFirstElement-Cursor
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_CURSOR_LEVEL2, 1));
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel2, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel2, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel2 + 0.1f, 0);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel2 + 0.1f, 0);
gl.glEnd();
gl.glPopName();
// Polygon for iLastElement-Cursor
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_CURSOR_LEVEL2, 2));
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(0.0f, fPosCursorLastElementLevel2, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel2, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel2 - 0.1f, 0);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.0f, fPosCursorLastElementLevel2 - 0.1f, 0);
gl.glEnd();
gl.glPopName();
// fill gap between cursor
gl.glColor4f(0f, 0f, 0f, 0.45f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_BLOCK_CURSOR_LEVEL2,
1));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel2, 0);
gl.glVertex3f(0.0f, fPosCursorLastElementLevel2, 0);
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel2, 0);
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel2, 0);
gl.glEnd();
gl.glPopName();
gl.glPopAttrib();
tempTexture.disable();
}
@Override
public void display(GL gl) {
processEvents();
if (generalManager.isWiiModeActive()) {
handleWiiInput();
}
if (generalManager.getTrackDataProvider().isTrackModeActive()) {
handleTrackInput(gl);
}
if (bIsDraggingActiveLevel2) {
handleCursorDraggingLevel2(gl);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingActiveLevel2 = false;
}
}
if (bIsDraggingWholeBlockLevel2) {
handleBlockDraggingLevel2(gl);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingWholeBlockLevel2 = false;
}
}
if (bIsDraggingActiveLevel1) {
handleCursorDraggingLevel1(gl);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingActiveLevel1 = false;
}
}
if (bIsDraggingWholeBlockLevel1) {
handleBlockDraggingLevel1(gl);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingWholeBlockLevel1 = false;
}
}
if (bDragDropExpGroup) {
handleDragDropGroupExperiments(gl);
if (glMouseListener.wasMouseReleased()) {
bDragDropExpGroup = false;
}
}
if (bDragDropGeneGroup) {
handleDragDropGroupGenes(gl);
if (glMouseListener.wasMouseReleased()) {
bDragDropGeneGroup = false;
}
}
// if (bSplitGroupExp) {
// handleGroupSplitExperiments(gl);
// if (glMouseListener.wasMouseReleased()) {
// bSplitGroupExp = false;
// }
// }
// if (bSplitGroupGene) {
// handleGroupSplitGenes(gl);
// if (glMouseListener.wasMouseReleased()) {
// bSplitGroupGene = false;
// }
// }
gl.glCallList(iGLDisplayListToCall);
float fright = 0.0f;
float ftop = viewFrustum.getTop();
float fleftOffset = 0;
if (bSkipLevel1 == false) {
gl.glTranslatef(GAP_LEVEL2_3, 0, 0);
}
if (bSkipLevel2 == false) {
if (bIsHeatmapInFocus) {
fright = viewFrustum.getWidth() - 1.2f;
fleftOffset = 0.095f + // width level 1 + boarder
GAP_LEVEL1_2 + // width gap between level 1 and 2
viewFrustum.getWidth() / 4f * 0.2f;
}
else {
fright = viewFrustum.getWidth() - 2.75f;
fleftOffset = 0.075f + // width level 1
GAP_LEVEL1_2 + // width gap between level 1 and 2
viewFrustum.getWidth() / 4f;
}
if (glHeatMapView.isInDefaultOrientation()) {
gl.glTranslatef(fleftOffset, +0.4f, 0);
}
else {
gl.glTranslatef(fleftOffset, -0.2f, 0);
}
}
else {
ftop = viewFrustum.getTop();
fright = viewFrustum.getWidth();
gl.glTranslatef(0.1f, -0.2f, 0);
}
// render embedded heat map
glHeatMapView.getViewFrustum().setTop(ftop);
glHeatMapView.getViewFrustum().setRight(fright);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_VIEW_SELECTION,
glHeatMapView.getID()));
glHeatMapView.displayRemote(gl);
gl.glPopName();
fWidthEHM = glHeatMapView.getViewFrustum().getWidth() - 0.95f;
// render embedded dendrogram
glDendrogramView.getViewFrustum().setTop(ftop);
glDendrogramView.getViewFrustum().setRight(fright);
glDendrogramView.setDisplayListDirty();
// glDendrogramView.displayRemote(gl);
if (bSkipLevel2 == false) {
if (glHeatMapView.isInDefaultOrientation()) {
gl.glTranslatef(-fleftOffset, -0.4f, 0);
}
else {
gl.glTranslatef(-fleftOffset, +0.2f, 0);
}
}
else
gl.glTranslatef(-0.1f, 0.2f, 0);
if (bSkipLevel1 == false) {
gl.glTranslatef(-GAP_LEVEL2_3, 0, 0);
}
contextMenu.render(gl, this);
}
private void buildDisplayList(final GL gl, int iGLDisplayListIndex) {
if (bRedrawTextures) {
initTextures(gl);
bRedrawTextures = false;
}
if (bHasFrustumChanged) {
glHeatMapView.setDisplayListDirty();
glDendrogramView.setDisplayListDirty();
bHasFrustumChanged = false;
}
gl.glNewList(iGLDisplayListIndex, GL.GL_COMPILE);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glLoadIdentity();
// background color
gl.glColor4f(0, 0, 0, 0.15f);
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(0, 0, -0.1f);
gl.glVertex3f(viewFrustum.getRight(), 0, -0.1f);
gl.glVertex3f(viewFrustum.getRight(), viewFrustum.getHeight(), -0.1f);
gl.glVertex3f(0, viewFrustum.getHeight(), -0.1f);
gl.glEnd();
// padding along borders
viewFrustum.setTop(viewFrustum.getTop() - 0.6f);
viewFrustum.setLeft(viewFrustum.getLeft() + 0.1f);
gl.glTranslatef(0.1f, 0.4f, 0);
if (contentVA.getGroupList() != null && bSkipLevel1 == false)
renderClassAssignmentsGenesLevel1(gl);
if (bSkipLevel1 == false) {
handleTexturePickingLevel1(gl);
}
if (bSkipLevel2 == false) {
handleTexturePickingLevel2(gl);
}
// all stuff for rendering level 1 (overview bar)
if (bSkipLevel1 == false) {
renderOverviewBar(gl);
renderMarkerOverviewBar(gl);
// renderSelectedElementsOverviewBar(gl);
renderCursorLevel1(gl);
gl.glTranslatef(GAP_LEVEL2_3, 0, 0);
}
else {
gl.glColor4f(1f, 1f, 0f, 1f);
}
if (bIsHeatmapInFocus) {
fAnimationScale = 0.2f;
}
else {
fAnimationScale = 1.0f;
}
// all stuff for rendering level 2 (textures)
if (bSkipLevel2 == false) {
gl.glColor4f(1f, 1f, 1f, 1f);
renderTextureHeatMap(gl);
renderMarkerTexture(gl);
renderSelectedElementsTexture(gl);
if (contentVA.getGroupList() != null)
renderClassAssignmentsGenesLevel2(gl);
if (storageVA.getGroupList() != null)
renderClassAssignmentsExperimentsLevel2(gl);
}
else {
initHierarchy();
setEmbeddedHeatMapData();
}
if (bSkipLevel2 == false) {
gl.glTranslatef(viewFrustum.getWidth() / 4.0f * fAnimationScale, 0, 0);
renderCursorLevel2(gl);
}
if (contentVA.getGroupList() != null)
renderClassAssignmentsGenesLevel3(gl);
if (bSkipLevel2 == false)
gl.glTranslatef(-(viewFrustum.getWidth() / 4.0f * fAnimationScale), 0, 0);
if (storageVA.getGroupList() != null) {
renderClassAssignmentsExperimentsLevel3(gl);
}
viewFrustum.setTop(viewFrustum.getTop() + 0.6f);
viewFrustum.setLeft(viewFrustum.getLeft() - 0.1f);
gl.glTranslatef(-0.1f, -0.4f, 0);
if (bSkipLevel1 == false) {
gl.glTranslatef(-GAP_LEVEL1_2, 0, 0);
}
gl.glEndList();
}
/**
* Function responsible for handling SelectionDelta for embedded heatmap
*/
private void setEmbeddedHeatMapData() {
int iCount = iFirstSampleLevel1 + iFirstSampleLevel2;
// SelectionCommand command = new SelectionCommand(ESelectionCommandType.RESET);
// commands.add(command);
// glHeatMapView.handleContentTriggerSelectionCommand(eFieldDataType, command);
glHeatMapView.resetView();
IVirtualArrayDelta delta = new VirtualArrayDelta(EVAType.CONTENT_EMBEDDED_HM, eFieldDataType);
ISelectionDelta selectionDelta = new SelectionDelta(eFieldDataType);
IVirtualArray currentVirtualArray = contentVA;
int iIndex = 0;
int iContentIndex = 0;
int iStorageIndex = 0;
Set<Integer> setMouseOverElements = contentSelectionManager.getElements(ESelectionType.MOUSE_OVER);
Set<Integer> setSelectedElements = contentSelectionManager.getElements(ESelectionType.SELECTION);
Set<Integer> setDeselectedElements = contentSelectionManager.getElements(ESelectionType.DESELECTED);
for (int index = 0; index < iSamplesPerHeatmap; index++) {
iIndex = iCount + index;
if (iIndex < currentVirtualArray.size()) {
iContentIndex = currentVirtualArray.get(iIndex);
}
delta.add(VADeltaItem.append(iContentIndex));
// set elements mouse over in embedded heat Map
for (Integer iSelectedID : setMouseOverElements) {
if (iSelectedID == iContentIndex)
selectionDelta.addSelection(iContentIndex, ESelectionType.MOUSE_OVER);
}
// set elements selected in embedded heat Map
for (Integer iSelectedID : setSelectedElements) {
if (iSelectedID == iContentIndex)
selectionDelta.addSelection(iContentIndex, ESelectionType.SELECTION);
}
// set elements deselected in embedded heat Map
for (Integer iSelectedID : setDeselectedElements) {
if (iSelectedID == iContentIndex)
selectionDelta.addSelection(iContentIndex, ESelectionType.DESELECTED);
}
}
glHeatMapView.handleVirtualArrayUpdate(delta, getShortInfo());
if (selectionDelta.size() > 0) {
glHeatMapView.handleSelectionUpdate(selectionDelta, true, null);
}
// selected experiments
SelectionCommand command = new SelectionCommand(ESelectionCommandType.RESET);
glHeatMapView.handleStorageTriggerSelectionCommand(eExperimentDataType, command);
IVirtualArrayDelta deltaExp = new VirtualArrayDelta(storageVAType, eExperimentDataType);
ISelectionDelta selectionDeltaEx = new SelectionDelta(eExperimentDataType);
IVirtualArray currentVirtualArrayEx = storageVA;
setMouseOverElements = storageSelectionManager.getElements(ESelectionType.MOUSE_OVER);
setSelectedElements = storageSelectionManager.getElements(ESelectionType.SELECTION);
for (int index = 0; index < currentVirtualArrayEx.size(); index++) {
iStorageIndex = currentVirtualArrayEx.get(index);
deltaExp.add(VADeltaItem.append(iStorageIndex));
// set elements mouse over in embedded heat Map
for (Integer iSelectedID : setMouseOverElements) {
if (iSelectedID == iStorageIndex)
selectionDeltaEx.addSelection(iStorageIndex, ESelectionType.MOUSE_OVER);
}
// set elements selected in embedded heat Map
for (Integer iSelectedID : setSelectedElements) {
if (iSelectedID == iStorageIndex)
selectionDeltaEx.addSelection(iStorageIndex, ESelectionType.SELECTION);
}
}
glHeatMapView.handleVirtualArrayUpdate(deltaExp, getShortInfo());
if (selectionDeltaEx.size() > 0) {
glHeatMapView.handleSelectionUpdate(selectionDeltaEx, true, null);
}
}
public void renderHorizontally(boolean bRenderStorageHorizontally) {
if (glHeatMapView.isInDefaultOrientation()) {
glHeatMapView.changeOrientation(false);
}
else {
glHeatMapView.changeOrientation(true);
}
setDisplayListDirty();
}
@Override
protected void initLists() {
if (bRenderOnlyContext)
contentVAType = EVAType.CONTENT_CONTEXT;
else
contentVAType = EVAType.CONTENT;
contentVA = useCase.getVA(contentVAType);
storageVA = useCase.getVA(EVAType.STORAGE);
// In case of importing group info
if (set.isGeneClusterInfo())
contentVA.setGroupList(set.getGroupListGenes());
if (set.isExperimentClusterInfo())
storageVA.setGroupList(set.getGroupListExperiments());
contentSelectionManager.resetSelectionManager();
storageSelectionManager.resetSelectionManager();
contentSelectionManager.setVA(contentVA);
storageSelectionManager.setVA(storageVA);
int iNumberOfColumns = contentVA.size();
int iNumberOfRows = storageVA.size();
for (int iRowCount = 0; iRowCount < iNumberOfRows; iRowCount++) {
storageSelectionManager.initialAdd(storageVA.get(iRowCount));
}
// this for loop executes one per axis
for (int iColumnCount = 0; iColumnCount < iNumberOfColumns; iColumnCount++) {
contentSelectionManager.initialAdd(contentVA.get(iColumnCount));
}
setDisplayListDirty();
}
@Override
public String getShortInfo() {
return "Hierarchical Heat Map (" + contentVA.size() + useCase.getContentLabel(false, true) + " / "
+ storageVA.size() + " experiments)";
}
@Override
public String getDetailedInfo() {
StringBuffer sInfoText = new StringBuffer();
sInfoText.append("<b>Type:</b> Hierarchical Heat Map\n");
if (bRenderStorageHorizontally) {
sInfoText.append(contentVA.size() + " " + useCase.getContentLabel(false, true)
+ " in columns and " + storageVA.size() + " experiments in rows.\n");
}
else {
sInfoText.append(contentVA.size() + " " + useCase.getContentLabel(true, true) + " in rows and "
+ storageVA.size() + " experiments in columns.\n");
}
if (bRenderOnlyContext) {
sInfoText.append("Showing only " + " " + useCase.getContentLabel(false, true)
+ " which occur in one of the other views in focus\n");
}
else {
if (dataFilterLevel == EDataFilterLevel.COMPLETE) {
sInfoText.append("Showing all " + useCase.getContentLabel(false, true) + " in the dataset\n");
}
else if (dataFilterLevel == EDataFilterLevel.ONLY_MAPPING) {
sInfoText.append("Showing all " + useCase.getContentLabel(false, true)
+ " that have a known DAVID ID mapping\n");
}
else if (dataFilterLevel == EDataFilterLevel.ONLY_CONTEXT) {
sInfoText
.append("Showing all genes that are contained in any of the KEGG or Biocarta pathways\n");
}
}
return sInfoText.toString();
}
/**
* Determine selected element in stage 1 (overview bar)
*
* @param gl
*/
private void handleTexturePickingLevel1(GL gl) {
int iNumberSample = iNumberOfElements;
float fOffsety;
float fHeightSample = viewFrustum.getHeight() / iNumberSample;
float[] fArPickingCoords = new float[3];
if (pickingPointLevel1 != null) {
fArPickingCoords =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, pickingPointLevel1.x,
pickingPointLevel1.y);
fOffsety = viewFrustum.getHeight() - fArPickingCoords[1] + 0.4f;
iPickedSampleLevel1 = (int) Math.ceil(fOffsety / fHeightSample);
pickingPointLevel1 = null;
if (iSamplesLevel2 % 2 == 0) {
iFirstSampleLevel1 = iPickedSampleLevel1 - (int) Math.floor(iSamplesLevel2 / 2) + 1;
iLastSampleLevel1 = iPickedSampleLevel1 + (int) Math.floor(iSamplesLevel2 / 2);
}
else {
iFirstSampleLevel1 = iPickedSampleLevel1 - (int) Math.ceil(iSamplesLevel2 / 2);
iLastSampleLevel1 = iPickedSampleLevel1 + (int) Math.floor(iSamplesLevel2 / 2);
}
if (iPickedSampleLevel1 < iSamplesLevel2 / 2) {
iPickedSampleLevel1 = (int) Math.floor(iSamplesLevel2 / 2);
iFirstSampleLevel1 = 0;
iLastSampleLevel1 = iSamplesLevel2 - 1;
}
else if (iPickedSampleLevel1 > iNumberSample - 1 - iSamplesLevel2 / 2) {
iPickedSampleLevel1 = (int) Math.ceil(iNumberSample - iSamplesLevel2 / 2);
iLastSampleLevel1 = iNumberSample - 1;
iFirstSampleLevel1 = iNumberSample - iSamplesLevel2;
}
}
// initPosCursorLevel2();
setDisplayListDirty();
setEmbeddedHeatMapData();
}
/**
* Determine selected element in stage 2 (texture)
*
* @param gl
*/
private void handleTexturePickingLevel2(GL gl) {
int iNumberSample = iSamplesLevel2;
float fOffsety;
float fHeightSample = viewFrustum.getHeight() / iNumberSample;
float[] fArPickingCoords = new float[3];
if (pickingPointLevel2 != null) {
fArPickingCoords =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, pickingPointLevel2.x,
pickingPointLevel2.y);
fOffsety = viewFrustum.getHeight() - fArPickingCoords[1] + 0.4f;
iPickedSampleLevel2 = (int) Math.ceil(fOffsety / fHeightSample);
pickingPointLevel2 = null;
if (iSamplesLevel2 % 2 == 0) {
iFirstSampleLevel2 = iPickedSampleLevel2 - (int) Math.floor(iSamplesPerHeatmap / 2) + 1;
iLastSampleLevel2 = iPickedSampleLevel2 + (int) Math.floor(iSamplesPerHeatmap / 2);
}
else {
iFirstSampleLevel2 = iPickedSampleLevel2 - (int) Math.ceil(iSamplesPerHeatmap / 2);
iLastSampleLevel2 = iPickedSampleLevel2 + (int) Math.floor(iSamplesPerHeatmap / 2);
}
if (iPickedSampleLevel2 < iSamplesPerHeatmap / 2) {
iPickedSampleLevel2 = (int) Math.floor(iSamplesPerHeatmap / 2);
iFirstSampleLevel2 = 0;
iLastSampleLevel2 = iSamplesPerHeatmap - 1;
}
else if (iPickedSampleLevel2 > iNumberSample - 1 - iSamplesPerHeatmap / 2) {
iPickedSampleLevel2 = (int) Math.ceil(iNumberSample - iSamplesPerHeatmap / 2);
iLastSampleLevel2 = iNumberSample - 1;
iFirstSampleLevel2 = iNumberSample - iSamplesPerHeatmap;
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
}
/**
* Handles drag&drop of groups in experiment dimension
*
* @param gl
*/
private void handleDragDropGroupExperiments(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iTargetIdx = 0;
int iNrSamples = storageVA.size();
float fgaps = 0;
if (bSkipLevel1)
fgaps = GAP_LEVEL2_3 + 0.2f;
else
fgaps = GAP_LEVEL1_2 + GAP_LEVEL2_3;
float fleftOffset = 0.075f + // width level 1
fgaps + viewFrustum.getWidth() / 4f * fAnimationScale;
float fWidthSample = fWidthEHM / iNrSamples;
int currentElement;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
IGroupList groupList = storageVA.getGroupList();
int iNrElementsInGroup = groupList.get(iExpGroupToDrag).getNrElements();
float currentWidth = fWidthSample * iNrElementsInGroup;
float fHeight = viewFrustum.getHeight();
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fArTargetWorldCoordinates[0], fHeight, 0);
gl.glVertex3f(fArTargetWorldCoordinates[0], fHeight - 0.1f, 0);
gl.glVertex3f(fArTargetWorldCoordinates[0] + currentWidth, fHeight - 0.1f, 0);
gl.glVertex3f(fArTargetWorldCoordinates[0] + currentWidth, fHeight, 0);
gl.glEnd();
float fXPosRelease = fArTargetWorldCoordinates[0] - fleftOffset;
currentElement = (int) Math.ceil(fXPosRelease / fWidthSample);
int iElemOffset = 0;
int cnt = 0;
if (groupList == null) {
System.out.println("No group assignment available!");
return;
}
for (Group currentGroup : groupList) {
if (currentElement < (iElemOffset + currentGroup.getNrElements())) {
iTargetIdx = cnt;
break;
}
cnt++;
iElemOffset += currentGroup.getNrElements();
}
float fPosDropMarker = fleftOffset + fWidthSample * iElemOffset;
gl.glLineWidth(6f);
gl.glColor3f(1, 0, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fPosDropMarker, fHeight, 0);
gl.glVertex3f(fPosDropMarker, fHeight - 0.2f, 0);
gl.glEnd();
if (glMouseListener.wasMouseReleased()) {
if (groupList.move(storageVA, iExpGroupToDrag, iTargetIdx) == false)
System.out.println("Move operation not allowed!");
bDragDropExpGroup = false;
bRedrawTextures = true;
setDisplayListDirty();
}
}
/**
* Handles drag&drop of groups in gene dimension
*
* @param gl
*/
private void handleDragDropGroupGenes(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iTargetIdx = 0;
int iNumberSample = iNumberOfElements;
float fOffsety;
int currentElement;
float fHeight = viewFrustum.getHeight() - 0.2f;
float fHeightSample = (fHeight - 0.4f) / iNumberSample;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
IGroupList groupList = contentVA.getGroupList();
int iNrElementsInGroup = groupList.get(iGeneGroupToDrag).getNrElements();
float currentHeight = fHeightSample * iNrElementsInGroup;
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(0f, fArTargetWorldCoordinates[1], 0);
gl.glVertex3f(0f, fArTargetWorldCoordinates[1] + currentHeight, 0);
gl.glVertex3f(0.1f, fArTargetWorldCoordinates[1] + currentHeight, 0);
gl.glVertex3f(0.1f, fArTargetWorldCoordinates[1], 0);
gl.glEnd();
fOffsety = viewFrustum.getHeight() - fArTargetWorldCoordinates[1] - 0.4f;
currentElement = (int) Math.ceil(fOffsety / fHeightSample);
int iElemOffset = 0;
int cnt = 0;
if (groupList == null) {
System.out.println("No group assignment available!");
return;
}
for (Group currentGroup : groupList) {
if (currentElement < (iElemOffset + currentGroup.getNrElements())) {
iTargetIdx = cnt;
break;
}
cnt++;
iElemOffset += currentGroup.getNrElements();
}
float fPosDropMarker = fHeight - (fHeightSample * iElemOffset);
gl.glLineWidth(6f);
gl.glColor3f(1, 0, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(0, fPosDropMarker, 0);
gl.glVertex3f(0.2f, fPosDropMarker, 0);
gl.glEnd();
if (glMouseListener.wasMouseReleased()) {
if (groupList.move(contentVA, iGeneGroupToDrag, iTargetIdx) == false)
System.out.println("Move operation not allowed!");
bDragDropGeneGroup = false;
bRedrawTextures = true;
setDisplayListDirty();
}
}
/**
* Handles the dragging cursor for gene groups
*
* @param gl
*/
private void handleGroupSplitGenes(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
float[] fArDraggedPoint = new float[3];
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
if (glMouseListener.wasMouseReleased()) {
bSplitGroupGene = false;
fArDraggedPoint =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, DraggingPoint.x,
DraggingPoint.y);
float fYPosDrag = fArDraggedPoint[1] - 0.4f;
float fYPosRelease = fArTargetWorldCoordinates[1] - 0.4f;
float fHeight = viewFrustum.getHeight() - 0.6f;
int iNrSamples = contentVA.size();
float fHeightSample = fHeight / iNrSamples;
int iFirstSample = iNrSamples - (int) Math.floor(fYPosDrag / fHeightSample);
int iLastSample = iNrSamples - (int) Math.ceil(fYPosRelease / fHeightSample);
// System.out.println("von: " + fYPosDrag + " bis: " + fYPosRelease);
// System.out.println("von: " + iFirstSample + " bis: " + iLastSample);
if (contentVA.getGroupList().split(iGroupToSplit, iFirstSample, iLastSample) == false)
System.out.println("Operation not allowed!!");
}
}
/**
* Handles the dragging cursor for experiments groups
*
* @param gl
*/
private void handleGroupSplitExperiments(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
float[] fArDraggedPoint = new float[3];
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
if (glMouseListener.wasMouseReleased()) {
bSplitGroupExp = false;
fArDraggedPoint =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, DraggingPoint.x,
DraggingPoint.y);
float fXPosDrag = fArDraggedPoint[0] - 0.7f;
float fXPosRelease = fArTargetWorldCoordinates[0] - 0.7f;
float fWidth = viewFrustum.getWidth() / 4.0f * fAnimationScale;
int iNrSamples = storageVA.size();
float fWidthSample = fWidth / iNrSamples;
int iFirstSample = (int) Math.floor(fXPosDrag / fWidthSample);
int iLastSample = (int) Math.ceil(fXPosRelease / fWidthSample);
if (storageVA.getGroupList().split(iGroupToSplit, iLastSample, iFirstSample) == false)
System.out.println("Operation not allowed!!");
}
}
private void handleBlockDraggingLevel1(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iselElement;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
float fTextureHeight = viewFrustum.getHeight() - 0.6f;
float fStep = fTextureHeight / iNumberOfElements;
float fYPosMouse = fArTargetWorldCoordinates[1] - 0.4f;
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
if (iSamplesLevel2 % 2 == 0) {
if ((iselElement - (int) Math.floor(iSamplesLevel2 / 2) + 1) >= 0
&& (iselElement + (int) Math.floor(iSamplesLevel2 / 2)) < iNumberOfElements) {
iFirstSampleLevel1 = iselElement - (int) Math.floor(iSamplesLevel2 / 2) + 1;
fPosCursorFirstElementLevel1 = fTextureHeight - (iFirstSampleLevel1 * fStep);
iLastSampleLevel1 = iselElement + (int) Math.floor(iSamplesLevel2 / 2);
fPosCursorLastElementLevel1 = fTextureHeight - ((iLastSampleLevel1 + 1) * fStep);
}
}
else {
if ((iselElement - (int) Math.ceil(iSamplesLevel2 / 2)) >= 0
&& (iselElement + (int) Math.floor(iSamplesLevel2 / 2)) < iNumberOfElements) {
iFirstSampleLevel1 = iselElement - (int) Math.ceil(iSamplesLevel2 / 2);
fPosCursorFirstElementLevel1 = fTextureHeight - (iFirstSampleLevel1 * fStep);
iLastSampleLevel1 = iselElement + (int) Math.floor(iSamplesLevel2 / 2);
fPosCursorLastElementLevel1 = fTextureHeight - ((iLastSampleLevel1 + 1) * fStep);
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
// System.out.println(" iSamplesPerTexture: " + iSamplesPerTexture + " iFirstSampleLevel1: "
// + iFirstSampleLevel1 + " iLastSampleLevel1: " + iLastSampleLevel1);
// System.out.println("fPosCursorFirstElementLevel2: " + fPosCursorFirstElementLevel2
// + " fPosCursorLastElementLevel2: " + fPosCursorLastElementLevel2);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingWholeBlockLevel1 = false;
bDisableCursorDraggingLevel1 = false;
// initPosCursorLevel2();
}
}
/**
* Function used for updating position of block (block of elements rendered in EHM) in case of dragging
*
* @param gl
*/
private void handleBlockDraggingLevel2(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iselElement;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
float fTextureHeight = viewFrustum.getHeight() - 0.6f;
float fStep = fTextureHeight / iSamplesLevel2;
float fYPosMouse = fArTargetWorldCoordinates[1] - 0.4f;
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
if (iSamplesPerHeatmap % 2 == 0) {
if ((iselElement - (int) Math.floor(iSamplesPerHeatmap / 2) + 1) >= 0
&& (iselElement + (int) Math.floor(iSamplesPerHeatmap / 2)) < iSamplesLevel2) {
iFirstSampleLevel2 = iselElement - (int) Math.floor(iSamplesPerHeatmap / 2) + 1;
fPosCursorFirstElementLevel2 = fTextureHeight - (iFirstSampleLevel2 * fStep);
iLastSampleLevel2 = iselElement + (int) Math.floor(iSamplesPerHeatmap / 2);
fPosCursorLastElementLevel2 = fTextureHeight - ((iLastSampleLevel2 + 1) * fStep);
}
}
else {
if ((iselElement - (int) Math.ceil(iSamplesPerHeatmap / 2)) >= 0
&& (iselElement + (int) Math.floor(iSamplesPerHeatmap / 2)) < iSamplesLevel2) {
iFirstSampleLevel2 = iselElement - (int) Math.ceil(iSamplesPerHeatmap / 2);
fPosCursorFirstElementLevel2 = fTextureHeight - (iFirstSampleLevel2 * fStep);
iLastSampleLevel2 = iselElement + (int) Math.floor(iSamplesPerHeatmap / 2);
fPosCursorLastElementLevel2 = fTextureHeight - ((iLastSampleLevel2 + 1) * fStep);
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
if (glMouseListener.wasMouseReleased()) {
bIsDraggingWholeBlockLevel2 = false;
bDisableCursorDraggingLevel2 = false;
}
}
private void handleCursorDraggingLevel1(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iselElement;
int iNrSamples;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
float fTextureHeight = viewFrustum.getHeight() - 0.6f;
float fStep = fTextureHeight / iNumberOfElements;
float fYPosMouse = fArTargetWorldCoordinates[1] - 0.4f;
// cursor for iFirstElement
if (iDraggedCursorLevel1 == 1) {
if (fYPosMouse > fPosCursorLastElementLevel1 && fYPosMouse <= viewFrustum.getHeight() - 0.6f) {
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
iNrSamples = iLastSampleLevel1 - iselElement + 1;
if (iNrSamples >= MIN_SAMPLES_PER_TEXTURE && iNrSamples < MAX_SAMPLES_PER_TEXTURE) {
fPosCursorFirstElementLevel1 = fYPosMouse;
iFirstSampleLevel1 = iselElement;
iSamplesLevel2 = iLastSampleLevel1 - iFirstSampleLevel1 + 1;
// // update Preference store
// generalManager.getPreferenceStore().setValue(
// PreferenceConstants.HM_NUM_SAMPLES_PER_TEXTURE, iSamplesPerTexture);
}
}
}
// cursor for iLastElement
if (iDraggedCursorLevel1 == 2) {
if (fYPosMouse < fPosCursorFirstElementLevel1 && fYPosMouse >= 0.0f) {
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
iNrSamples = iselElement - iFirstSampleLevel1 + 1;
if (iNrSamples >= MIN_SAMPLES_PER_TEXTURE && iNrSamples < MAX_SAMPLES_PER_TEXTURE) {
fPosCursorLastElementLevel1 = fYPosMouse;
iLastSampleLevel1 = iselElement;
iSamplesLevel2 = iLastSampleLevel1 - iFirstSampleLevel1 + 1;
// // update Preference store
// generalManager.getPreferenceStore().setValue(
// PreferenceConstants.HM_NUM_SAMPLES_PER_TEXTURE, iSamplesPerTexture);
}
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
// System.out.println(" iSamplesPerTexture: " + iSamplesPerTexture + " iFirstSampleLevel1: "
// + iFirstSampleLevel1 + " iLastSampleLevel1: " + iLastSampleLevel1);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingActiveLevel1 = false;
bDisableBlockDraggingLevel1 = false;
// initPosCursorLevel2();
}
}
/**
* Function used for updating cursor position in case of dragging
*
* @param gl
*/
private void handleCursorDraggingLevel2(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iselElement;
int iNrSamples;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
float fTextureHeight = viewFrustum.getHeight() - 0.6f;
float fStep = fTextureHeight / iSamplesLevel2;
float fYPosMouse = fArTargetWorldCoordinates[1] - 0.4f;
// cursor for iFirstElement
if (iDraggedCursorLevel2 == 1) {
if (fYPosMouse > fPosCursorLastElementLevel2 && fYPosMouse <= viewFrustum.getHeight() - 0.6f) {
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
iNrSamples = iLastSampleLevel2 - iselElement + 1;
if (iNrSamples >= MIN_SAMPLES_PER_HEATMAP && iNrSamples < MAX_SAMPLES_PER_HEATMAP) {
fPosCursorFirstElementLevel2 = fYPosMouse;
iFirstSampleLevel2 = iselElement;
iSamplesPerHeatmap = iLastSampleLevel2 - iFirstSampleLevel2 + 1;
// update Preference store
generalManager.getPreferenceStore().setValue(
PreferenceConstants.HM_NUM_SAMPLES_PER_HEATMAP, iSamplesPerHeatmap);
}
}
}
// cursor for iLastElement
if (iDraggedCursorLevel2 == 2) {
if (fYPosMouse < fPosCursorFirstElementLevel2 && fYPosMouse >= 0.0f) {
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
iNrSamples = iselElement - iFirstSampleLevel2 + 1;
if (iNrSamples >= MIN_SAMPLES_PER_HEATMAP && iNrSamples < MAX_SAMPLES_PER_HEATMAP) {
fPosCursorLastElementLevel2 = fYPosMouse;
iLastSampleLevel2 = iselElement;
iSamplesPerHeatmap = iLastSampleLevel2 - iFirstSampleLevel2 + 1;
// update Preference store
generalManager.getPreferenceStore().setValue(
PreferenceConstants.HM_NUM_SAMPLES_PER_HEATMAP, iSamplesPerHeatmap);
}
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
if (glMouseListener.wasMouseReleased()) {
bIsDraggingActiveLevel2 = false;
bDisableBlockDraggingLevel2 = false;
}
}
@Override
protected void handleEvents(EPickingType ePickingType, EPickingMode pickingMode, int iExternalID,
Pick pick) {
if (detailLevel == EDetailLevel.VERY_LOW) {
return;
}
switch (ePickingType) {
// handling the groups/clusters of genes
case HIER_HEAT_MAP_GENES_GROUP:
switch (pickingMode) {
case CLICKED:
contentVA.getGroupList().get(iExternalID).toggleSelectionType();
// System.out.println(contentVA.getGroupList().get(iExternalID).getIdxExample());
// System.out.println(GeneticIDMappingHelper.get().getShortNameFromExpressionIndex(
// contentVA.getGroupList().get(iExternalID).getIdxExample()));
setDisplayListDirty();
break;
case DRAGGED:
// drag&drop for groups
if (bDragDropGeneGroup == false) {
bDragDropGeneGroup = true;
bDragDropExpGroup = false;
iGeneGroupToDrag = iExternalID;
}
// group splitting
// if (bSplitGroupGene == false) {
// bSplitGroupGene = true;
// bSplitGroupExp = false;
// iGroupToSplit = iExternalID;
// DraggingPoint = pick.getPickedPoint();
// }
setDisplayListDirty();
break;
case RIGHT_CLICKED:
boolean bEnableInterchange = false;
boolean bEnableMerge = false;
int iNrSelectedGroups = 0;
IGroupList tempGroupList = contentVA.getGroupList();
for (Group group : tempGroupList) {
if (group.getSelectionType() == ESelectionType.SELECTION)
iNrSelectedGroups++;
}
if (iNrSelectedGroups >= 2) {
bEnableMerge = true;
if (iNrSelectedGroups == 2)
bEnableInterchange = true;
GroupContextMenuItemContainer groupContextMenuItemContainer =
new GroupContextMenuItemContainer();
groupContextMenuItemContainer.setContextMenuFlags(true, bEnableMerge,
bEnableInterchange);
contextMenu.addItemContanier(groupContextMenuItemContainer);
// if (!isRenderedRemote()) {
contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas().getWidth(),
getParentGLCanvas().getHeight());
contextMenu.setMasterGLView(this);
// }
}
break;
case MOUSE_OVER:
// System.out.print("genes group " + iExternalID);
// System.out.print(" number elements in group: ");
// System.out.println(contentVA.getGroupList().get(iExternalID)
// .getNrElements());
// setDisplayListDirty();
break;
}
break;
// handling the groups/clusters of experiments
case HIER_HEAT_MAP_EXPERIMENTS_GROUP:
switch (pickingMode) {
case CLICKED:
storageVA.getGroupList().get(iExternalID).toggleSelectionType();
// System.out.println(storageVA.getGroupList().get(iExternalID).getIdxExample());
// System.out.println(set.get(storageVA.getGroupList().get(iExternalID).getIdxExample())
// .getLabel());
setDisplayListDirty();
break;
case DRAGGED:
// drag&drop for groups
if (bDragDropExpGroup == false) {
bDragDropExpGroup = true;
bDragDropGeneGroup = false;
iExpGroupToDrag = iExternalID;
}
// group splitting
// if (bSplitGroupExp == false) {
// bSplitGroupExp = true;
// bSplitGroupGene = false;
// iGroupToSplit = iExternalID;
// DraggingPoint = pick.getPickedPoint();
// }
setDisplayListDirty();
break;
case RIGHT_CLICKED:
boolean bEnableInterchange = false;
boolean bEnableMerge = false;
int iNrSelectedGroups = 0;
IGroupList tempGroupList = storageVA.getGroupList();
for (Group group : tempGroupList) {
if (group.getSelectionType() == ESelectionType.SELECTION)
iNrSelectedGroups++;
}
if (iNrSelectedGroups >= 2) {
bEnableMerge = true;
if (iNrSelectedGroups == 2)
bEnableInterchange = true;
GroupContextMenuItemContainer groupContextMenuItemContainer =
new GroupContextMenuItemContainer();
groupContextMenuItemContainer.setContextMenuFlags(false, bEnableMerge,
bEnableInterchange);
contextMenu.addItemContanier(groupContextMenuItemContainer);
// if (!isRenderedRemote()) {
contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas().getWidth(),
getParentGLCanvas().getHeight());
contextMenu.setMasterGLView(this);
// }
}
break;
case MOUSE_OVER:
// System.out.print("patients group " + iExternalID);
// System.out.print(" number elements in group: ");
// System.out.println(storageVA.getGroupList().get(iExternalID)
// .getNrElements());
// setDisplayListDirty();
break;
}
break;
// handle click on button for setting EHM in focus
case HIER_HEAT_MAP_INFOCUS_SELECTION:
switch (pickingMode) {
case CLICKED:
bIsHeatmapInFocus = bIsHeatmapInFocus == true ? false : true;
glHeatMapView.setDisplayListDirty();
setDisplayListDirty();
break;
case DRAGGED:
break;
case MOUSE_OVER:
break;
}
break;
// handle click on button for selecting next/previous texture in level 1 and 2
// case HIER_HEAT_MAP_TEXTURE_CURSOR:
// switch (pickingMode) {
// case CLICKED:
//
// if (bSkipLevel1 == false) {
//
// if (iExternalID == 1) {
// iSelectorBar--;
// initPosCursorLevel2();
// setEmbeddedHeatMapData();
// setDisplayListDirty();
// }
// if (iExternalID == 2) {
// iSelectorBar++;
// initPosCursorLevel2();
// setEmbeddedHeatMapData();
// setDisplayListDirty();
// }
//
// setDisplayListDirty();
// }
// break;
//
// case DRAGGED:
// break;
//
// case MOUSE_OVER:
// break;
// }
// break;
// handle dragging cursor for first and last element of block in level 1
case HIER_HEAT_MAP_CURSOR_LEVEL1:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
if (bDisableCursorDraggingLevel1)
return;
bIsDraggingActiveLevel1 = true;
bDisableBlockDraggingLevel1 = true;
iDraggedCursorLevel1 = iExternalID;
setDisplayListDirty();
break;
case MOUSE_OVER:
break;
}
break;
// handle dragging cursor for whole block in level 1
case HIER_HEAT_MAP_BLOCK_CURSOR_LEVEL1:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
if (bDisableBlockDraggingLevel1)
return;
bIsDraggingWholeBlockLevel1 = true;
bDisableCursorDraggingLevel1 = true;
iDraggedCursorLevel1 = iExternalID;
setDisplayListDirty();
break;
case MOUSE_OVER:
break;
}
break;
// handle dragging cursor for first and last element of block in level 2
case HIER_HEAT_MAP_CURSOR_LEVEL2:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
if (bDisableCursorDraggingLevel2)
return;
bIsDraggingActiveLevel2 = true;
bDisableBlockDraggingLevel2 = true;
iDraggedCursorLevel2 = iExternalID;
setDisplayListDirty();
break;
case MOUSE_OVER:
break;
}
break;
// handle dragging cursor for whole block in level 2
case HIER_HEAT_MAP_BLOCK_CURSOR_LEVEL2:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
if (bDisableBlockDraggingLevel2)
return;
bIsDraggingWholeBlockLevel2 = true;
bDisableCursorDraggingLevel2 = true;
iDraggedCursorLevel2 = iExternalID;
setDisplayListDirty();
break;
case MOUSE_OVER:
break;
}
break;
// handle click on level 1 (overview bar)
case HIER_HEAT_MAP_TEXTURE_SELECTION:
switch (pickingMode) {
case CLICKED:
// if (bSkipLevel1 == false) {
// iSelectorBar = iExternalID;
// // if (iSelectorBar == iNrSelBar) {
// // iSelectorBar--;
// // }
// initPosCursorLevel2();
// setEmbeddedHeatMapData();
// setDisplayListDirty();
// }
pickingPointLevel1 = pick.getPickedPoint();
setEmbeddedHeatMapData();
setDisplayListDirty();
break;
case DRAGGED:
break;
case MOUSE_OVER:
break;
}
break;
// handle click on level 2
case HIER_HEAT_MAP_FIELD_SELECTION:
switch (pickingMode) {
case CLICKED:
pickingPointLevel2 = pick.getPickedPoint();
setEmbeddedHeatMapData();
setDisplayListDirty();
break;
case DRAGGED:
break;
case MOUSE_OVER:
break;
}
break;
// handle click on level 3 (EHM)
case HIER_HEAT_MAP_VIEW_SELECTION:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
break;
case MOUSE_OVER:
break;
case RIGHT_CLICKED:
contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas().getWidth(),
getParentGLCanvas().getHeight());
contextMenu.setMasterGLView(this);
break;
}
break;
}
}
@Override
protected ArrayList<SelectedElementRep> createElementRep(EIDType idType, int iStorageIndex) {
return null;
}
@Override
public void renderContext(boolean bRenderOnlyContext) {
throw new IllegalStateException("Rendering only context not supported for the hierachical heat map");
}
@Override
public void clearAllSelections() {
contentSelectionManager.clearSelections();
storageSelectionManager.clearSelections();
iPickedSampleLevel1 = 0;
initPosCursorLevel1();
bRedrawTextures = true;
setDisplayListDirty();
setEmbeddedHeatMapData();
glHeatMapView.setDisplayListDirty();
glDendrogramView.setDisplayListDirty();
// group/cluster selections
if (storageVA.getGroupList() != null) {
IGroupList groupList = storageVA.getGroupList();
for (Group group : groupList)
group.setSelectionType(ESelectionType.NORMAL);
}
if (contentVA.getGroupList() != null) {
IGroupList groupList = contentVA.getGroupList();
for (Group group : groupList)
group.setSelectionType(ESelectionType.NORMAL);
}
}
@Override
public void changeOrientation(boolean defaultOrientation) {
renderHorizontally(defaultOrientation);
}
@Override
public boolean isInDefaultOrientation() {
return bRenderStorageHorizontally;
}
public void changeFocus(boolean bInFocus) {
bIsHeatmapInFocus = bIsHeatmapInFocus == true ? false : true;
setDisplayListDirty();
}
@SuppressWarnings("unused")
private void activateGroupHandling() {
if (contentVA.getGroupList() == null) {
GroupList groupList = new GroupList(0);
Group group = new Group(contentVA.size(), false, 0, ESelectionType.NORMAL);
groupList.append(group);
contentVA.setGroupList(groupList);
}
if (storageVA.getGroupList() == null) {
GroupList groupList = new GroupList(0);
Group group = new Group(storageVA.size(), false, 0, ESelectionType.NORMAL);
groupList.append(group);
storageVA.setGroupList(groupList);
}
setDisplayListDirty();
}
public boolean isInFocus() {
return bIsHeatmapInFocus;
}
private void handleWiiInput() {
float fHeadPositionX = generalManager.getWiiRemote().getCurrentSmoothHeadPosition()[0];
if (fHeadPositionX < -1.2f) {
bIsHeatmapInFocus = false;
}
else {
bIsHeatmapInFocus = true;
}
setDisplayListDirty();
}
private void handleTrackInput(final GL gl) {
// // TODO: very performance intensive - better solution needed (only in reshape)!
// getParentGLCanvas().getParentComposite().getDisplay().asyncExec(new Runnable() {
// @Override
// public void run() {
// upperLeftScreenPos = getParentGLCanvas().getParentComposite().toDisplay(1, 1);
// }
// });
//
// Rectangle screenRect = getParentGLCanvas().getBounds();
// float[] fArTrackPos = generalManager.getTrackDataProvider().getEyeTrackData();
//
// fArTrackPos[0] -= upperLeftScreenPos.x;
// fArTrackPos[1] -= upperLeftScreenPos.y;
//
// GLHelperFunctions.drawPointAt(gl, new Vec3f(fArTrackPos[0] / screenRect.width * 8f,
// (1f - fArTrackPos[1] / screenRect.height) * 8f * fAspectRatio, 0.01f));
//
// float fSwitchBorder = 200;
//
// if (!bIsHeatmapInFocus)
// fSwitchBorder = 450;
//
// if (fArTrackPos[0] < fSwitchBorder) {
// bIsHeatmapInFocus = false;
// }
// else {
// bIsHeatmapInFocus = true;
// }
//
// // Manipulate selected overview chunk (level 1)
// if (fArTrackPos[0] < 50) {
// int iNrPixelsPerSelectionBar = (int) (screenRect.getHeight() / iNrSelBar);
// iSelectorBar = (int) ((fArTrackPos[1] + 17) / iNrPixelsPerSelectionBar * 1.1f); // TODO: play with
// // these
// // correction
// // factors
//
// if (iSelectorBar <= 0)
// iSelectorBar = 1;
// else if (iSelectorBar > iNrSelBar)
// iSelectorBar = iNrSelBar;
// }
//
// // Manipulate selected level 2 chunk
// if (!bIsHeatmapInFocus && fArTrackPos[0] > 50 && fArTrackPos[0] < 450) {
// float fTextureHeight = viewFrustum.getHeight() - 0.6f;
// float fStep = fTextureHeight / (iAlNumberSamples.get(iSelectorBar - 1));// * 2);
// float fYPosMouse =
// ((1f - fArTrackPos[1] / (float) screenRect.getHeight())) * 8f * fAspectRatio - 0.4f;
//
// int iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
// if (iSamplesPerHeatmap % 2 == 0) {
// if ((iselElement - (int) Math.floor(iSamplesPerHeatmap / 2) + 1) >= 0
// && (iselElement + (int) Math.floor(iSamplesPerHeatmap / 2)) < iAlNumberSamples
// .get(iSelectorBar - 1)) {
// iFirstSampleLevel2 = iselElement - (int) Math.floor(iSamplesPerHeatmap / 2) + 1;
// fPosCursorFirstElementLevel3 = fTextureHeight - (iFirstSampleLevel2 * fStep);
// iLastSampleLevel2 = iselElement + (int) Math.floor(iSamplesPerHeatmap / 2);
// fPosCursorLastElementLevel3 = fTextureHeight - ((iLastSampleLevel2 + 1) * fStep);
// }
// }
// else {
// if ((iselElement - (int) Math.ceil(iSamplesPerHeatmap / 2)) >= 0
// && (iselElement + (int) Math.floor(iSamplesPerHeatmap / 2)) < iAlNumberSamples
// .get(iSelectorBar - 1)) {
// iFirstSampleLevel2 = iselElement - (int) Math.ceil(iSamplesPerHeatmap / 2);
// fPosCursorFirstElementLevel3 = fTextureHeight - (iFirstSampleLevel2 * fStep);
// iLastSampleLevel2 = iselElement + (int) Math.floor(iSamplesPerHeatmap / 2);
// fPosCursorLastElementLevel3 = fTextureHeight - ((iLastSampleLevel2 + 1) * fStep);
// }
// }
// }
//
// setDisplayListDirty();
}
@Override
public void initData() {
super.initData();
// FIXME
// contentVA.setGroupList(null);
// storageVA.setGroupList(null);
initHierarchy();
initPosCursorLevel1();
if (bSkipLevel2 == false) {
calculateTextures();
initPosCursorLevel2();
}
glHeatMapView.setSet(set);
glHeatMapView.setContentVAType(EVAType.CONTENT_EMBEDDED_HM);
glHeatMapView.initData();
glDendrogramView.setSet(set);
glDendrogramView.setContentVAType(EVAType.CONTENT_EMBEDDED_HM);
glDendrogramView.initData();
if (bSkipLevel2 == false)
bRedrawTextures = true;
}
@Override
public ASerializedView getSerializableRepresentation() {
SerializedHierarchicalHeatMapView serializedForm = new SerializedHierarchicalHeatMapView();
serializedForm.setViewID(this.getID());
serializedForm.setViewGUIID(getViewGUIID());
return serializedForm;
}
@Override
public void handleInterchangeGroups(boolean bGeneGroup) {
IVirtualArray va;
if (bGeneGroup)
va = contentVA;
else
va = storageVA;
IGroupList groupList = va.getGroupList();
ArrayList<Integer> selGroups = new ArrayList<Integer>();
if (groupList == null) {
System.out.println("No group assignment available!");
return;
}
for (Group iter : groupList) {
if (iter.getSelectionType() == ESelectionType.SELECTION)
selGroups.add(groupList.indexOf(iter));
}
if (selGroups.size() != 2) {
System.out.println("Number of selected elements has to be 2!!!");
return;
}
// interchange
if (groupList.interchange(va, selGroups.get(0), selGroups.get(1)) == false) {
System.out.println("Problem during interchange!!!");
return;
}
bRedrawTextures = true;
setDisplayListDirty();
}
@Override
public void handleMergeGroups(boolean bGeneGroup) {
IVirtualArray va;
if (bGeneGroup)
va = contentVA;
else
va = storageVA;
IGroupList groupList = va.getGroupList();
ArrayList<Integer> selGroups = new ArrayList<Integer>();
if (groupList == null) {
System.out.println("No group assignment available!");
return;
}
for (Group iter : groupList) {
if (iter.getSelectionType() == ESelectionType.SELECTION)
selGroups.add(groupList.indexOf(iter));
}
// merge
while (selGroups.size() >= 2) {
int iLastSelected = selGroups.size() - 1;
// merge last and the one before last
if (groupList.merge(va, selGroups.get(iLastSelected - 1), selGroups.get(iLastSelected)) == false) {
System.out.println("Problem during merge!!!");
return;
}
selGroups.remove(iLastSelected);
}
bRedrawTextures = true;
setDisplayListDirty();
}
@Override
public void registerEventListeners() {
super.registerEventListeners();
groupMergingActionListener = new GroupMergingActionListener();
groupMergingActionListener.setHandler(this);
eventPublisher.addListener(MergeGroupsEvent.class, groupMergingActionListener);
groupInterChangingActionListener = new GroupInterChangingActionListener();
groupInterChangingActionListener.setHandler(this);
eventPublisher.addListener(InterchangeGroupsEvent.class, groupInterChangingActionListener);
updateViewListener = new UpdateViewListener();
updateViewListener.setHandler(this);
eventPublisher.addListener(UpdateViewEvent.class, updateViewListener);
}
@Override
public void unregisterEventListeners() {
super.unregisterEventListeners();
if (groupMergingActionListener != null) {
eventPublisher.removeListener(groupMergingActionListener);
groupMergingActionListener = null;
}
if (groupInterChangingActionListener != null) {
eventPublisher.removeListener(groupInterChangingActionListener);
groupInterChangingActionListener = null;
}
if (updateViewListener != null) {
eventPublisher.removeListener(updateViewListener);
updateViewListener = null;
}
}
@Override
public void handleUpdateView() {
bRedrawTextures = true;
setDisplayListDirty();
}
public void handleArrowDownAltPressed() {
if (iLastSampleLevel2 < iSamplesLevel2 - 1) {
iLastSampleLevel2++;
iFirstSampleLevel2++;
setEmbeddedHeatMapData();
setDisplayListDirty();
glHeatMapView.upDownSelect(false);
}
}
public void handleArrowUpAltPressed() {
if (iFirstSampleLevel2 > 0) {
iFirstSampleLevel2--;
iLastSampleLevel2--;
setEmbeddedHeatMapData();
setDisplayListDirty();
glHeatMapView.upDownSelect(true);
}
}
public void handleArrowDownCtrlPressed() {
if (iLastSampleLevel1 < iNumberOfElements - 1) {
iFirstSampleLevel1++;
iLastSampleLevel1++;
setDisplayListDirty();
glHeatMapView.upDownSelect(false);
}
}
public void handleArrowUpCtrlPressed() {
if (iFirstSampleLevel1 > 0) {
iFirstSampleLevel1--;
iLastSampleLevel1--;
setDisplayListDirty();
glHeatMapView.upDownSelect(true);
}
}
public void handleArrowUpPressed() {
// glHeatMapView.upDownSelect(true);
}
public void handleArrowDownPressed() {
// glHeatMapView.upDownSelect(false);
}
public void handleArrowLeftShiftPressed() {
if (bIsHeatmapInFocus == false) {
bIsHeatmapInFocus = true;
setDisplayListDirty();
}
}
public void handleArrowRightShiftPressed() {
if (bIsHeatmapInFocus) {
bIsHeatmapInFocus = false;
setDisplayListDirty();
}
}
/**
* Set the number of samples which are shown in one texture
*
* @param iNumberOfSamplesPerTexture
* the number
*/
public final void setNumberOfSamplesPerTexture(int iNumberOfSamplesPerTexture) {
this.iNumberOfSamplesPerTexture = iNumberOfSamplesPerTexture;
}
/**
* Set the number of samples which are shown in one heat map
*
* @param iNumberOfSamplesPerHeatmap
* the number
*/
public final void setNumberOfSamplesPerHeatmap(int iNumberOfSamplesPerHeatmap) {
this.iNumberOfSamplesPerHeatmap = iNumberOfSamplesPerHeatmap;
}
}
| org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/storagebased/GLHierarchicalHeatMap.java | package org.caleydo.core.view.opengl.canvas.storagebased;
import static org.caleydo.core.view.opengl.canvas.storagebased.HeatMapRenderStyle.SELECTION_Z;
import static org.caleydo.core.view.opengl.renderstyle.GeneralRenderStyle.MOUSE_OVER_COLOR;
import static org.caleydo.core.view.opengl.renderstyle.GeneralRenderStyle.SELECTED_COLOR;
import gleem.linalg.Vec3f;
import java.awt.Point;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Set;
import javax.media.opengl.GL;
import org.caleydo.core.command.ECommandType;
import org.caleydo.core.command.view.opengl.CmdCreateGLEventListener;
import org.caleydo.core.data.collection.storage.EDataRepresentation;
import org.caleydo.core.data.mapping.EIDType;
import org.caleydo.core.data.selection.ESelectionCommandType;
import org.caleydo.core.data.selection.ESelectionType;
import org.caleydo.core.data.selection.Group;
import org.caleydo.core.data.selection.GroupList;
import org.caleydo.core.data.selection.IGroupList;
import org.caleydo.core.data.selection.IVirtualArray;
import org.caleydo.core.data.selection.SelectedElementRep;
import org.caleydo.core.data.selection.SelectionCommand;
import org.caleydo.core.data.selection.SelectionManager;
import org.caleydo.core.data.selection.delta.ISelectionDelta;
import org.caleydo.core.data.selection.delta.IVirtualArrayDelta;
import org.caleydo.core.data.selection.delta.SelectionDelta;
import org.caleydo.core.data.selection.delta.VADeltaItem;
import org.caleydo.core.data.selection.delta.VirtualArrayDelta;
import org.caleydo.core.manager.event.view.group.InterchangeGroupsEvent;
import org.caleydo.core.manager.event.view.group.MergeGroupsEvent;
import org.caleydo.core.manager.event.view.storagebased.UpdateViewEvent;
import org.caleydo.core.manager.general.GeneralManager;
import org.caleydo.core.manager.id.EManagedObjectType;
import org.caleydo.core.manager.picking.EPickingMode;
import org.caleydo.core.manager.picking.EPickingType;
import org.caleydo.core.manager.picking.Pick;
import org.caleydo.core.serialize.ASerializedView;
import org.caleydo.core.util.mapping.color.ColorMapping;
import org.caleydo.core.util.mapping.color.ColorMappingManager;
import org.caleydo.core.util.mapping.color.EColorMappingType;
import org.caleydo.core.util.preferences.PreferenceConstants;
import org.caleydo.core.view.opengl.camera.EProjectionMode;
import org.caleydo.core.view.opengl.camera.IViewFrustum;
import org.caleydo.core.view.opengl.canvas.AGLEventListener;
import org.caleydo.core.view.opengl.canvas.EDetailLevel;
import org.caleydo.core.view.opengl.canvas.GLCaleydoCanvas;
import org.caleydo.core.view.opengl.canvas.listener.UpdateViewListener;
import org.caleydo.core.view.opengl.canvas.remote.IGLCanvasRemoteRendering;
import org.caleydo.core.view.opengl.canvas.remote.listener.GroupInterChangingActionListener;
import org.caleydo.core.view.opengl.canvas.remote.listener.GroupMergingActionListener;
import org.caleydo.core.view.opengl.canvas.remote.receiver.IGroupsInterChangingActionReceiver;
import org.caleydo.core.view.opengl.canvas.remote.receiver.IGroupsMergingActionReceiver;
import org.caleydo.core.view.opengl.canvas.storagebased.listener.GLHierarchicalHeatMapKeyListener;
import org.caleydo.core.view.opengl.mouse.GLMouseListener;
import org.caleydo.core.view.opengl.util.GLCoordinateUtils;
import org.caleydo.core.view.opengl.util.overlay.contextmenu.container.GroupContextMenuItemContainer;
import org.caleydo.core.view.opengl.util.overlay.infoarea.GLInfoAreaManager;
import org.caleydo.core.view.opengl.util.texture.EIconTextures;
import com.sun.opengl.util.BufferUtil;
import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureCoords;
import com.sun.opengl.util.texture.TextureData;
import com.sun.opengl.util.texture.TextureIO;
/**
* Rendering the GLHierarchicalHeatMap with remote rendering support.
*
* @author Bernhard Schlegl
* @author Marc Streit
* @author Alexander Lex
*/
public class GLHierarchicalHeatMap
extends AStorageBasedView
implements IGroupsMergingActionReceiver, IGroupsInterChangingActionReceiver {
private final static float GAP_LEVEL1_2 = 0.6f;
private final static float GAP_LEVEL2_3 = 0.6f;
// private final static float MAX_NUM_SAMPLES = 8f;
private final static int MIN_SAMPLES_PER_TEXTURE = 200;
private final static int MAX_SAMPLES_PER_TEXTURE = 400;
private final static int MIN_SAMPLES_PER_HEATMAP = 14;
private final static int MAX_SAMPLES_PER_HEATMAP = 100;
private final static int MIN_SAMPLES_SKIP_LEVEL_1 = 200;
private final static int MIN_SAMPLES_SKIP_LEVEL_2 = 40;
private int iNumberOfElements = 0;
private int iSamplesPerTexture = 0;
private int iSamplesLevel2;
private int iSamplesPerHeatmap = 0;
private ColorMapping colorMapper;
private EIDType eFieldDataType = EIDType.EXPRESSION_INDEX;
private EIDType eExperimentDataType = EIDType.EXPERIMENT_INDEX;
// array of textures for holding the data samples
private int iNrTextures = 0;
private ArrayList<Texture> AlTextures = new ArrayList<Texture>();
private ArrayList<Integer> iAlNumberSamples = new ArrayList<Integer>();
private Point pickingPointLevel2 = null;
private int iPickedSampleLevel2 = 0;
private int iFirstSampleLevel2 = 0;
private int iLastSampleLevel2 = 0;
private Point pickingPointLevel1 = null;
private int iPickedSampleLevel1 = 0;
private int iFirstSampleLevel1 = 0;
private int iLastSampleLevel1 = 0;
private boolean bRenderCaption;
private float fAnimationScale = 1.0f;
// embedded heat map
private GLHeatMap glHeatMapView;
private boolean bIsHeatmapInFocus = false;
private float fWidthEHM = 0;
// embedded dendrogram
private GLDendrogram glDendrogramView;
private boolean bRedrawTextures = false;
// if only a small number (< 100) of genes is in the data set, level_1 (overViewBar) should not be
// rendered
private boolean bSkipLevel1 = false;
// if only a small number (< 30) of genes is in the data set, level_2 (textures) should not be rendered
private boolean bSkipLevel2 = false;
// dragging stuff level 2
private boolean bIsDraggingActiveLevel2 = false;
private boolean bIsDraggingWholeBlockLevel2 = false;
private boolean bDisableCursorDraggingLevel2 = false;
private boolean bDisableBlockDraggingLevel2 = false;
private int iDraggedCursorLevel2 = 0;
private float fPosCursorFirstElementLevel2 = 0;
private float fPosCursorLastElementLevel2 = 0;
// dragging stuff level 1
private boolean bIsDraggingActiveLevel1 = false;
private boolean bIsDraggingWholeBlockLevel1 = false;
private boolean bDisableCursorDraggingLevel1 = false;
private boolean bDisableBlockDraggingLevel1 = false;
private int iDraggedCursorLevel1 = 0;
private float fPosCursorFirstElementLevel1 = 0;
private float fPosCursorLastElementLevel1 = 0;
// clustering/grouping stuff
private boolean bSplitGroupExp = false;
private boolean bSplitGroupGene = false;
private int iGroupToSplit = 0;
private Point DraggingPoint = null;
// drag&drop stuff for clusters/groups
private boolean bDragDropExpGroup = false;
private boolean bDragDropGeneGroup = false;
private int iExpGroupToDrag = -1;
private int iGeneGroupToDrag = -1;
private GroupMergingActionListener groupMergingActionListener;
private GroupInterChangingActionListener groupInterChangingActionListener;
private UpdateViewListener updateViewListener;
private org.eclipse.swt.graphics.Point upperLeftScreenPos = new org.eclipse.swt.graphics.Point(0, 0);
/**
* Constructor.
*
* @param glCanvas
* @param sLabel
* @param viewFrustum
*/
public GLHierarchicalHeatMap(GLCaleydoCanvas glCanvas, final String sLabel, final IViewFrustum viewFrustum) {
super(glCanvas, sLabel, viewFrustum);
viewType = EManagedObjectType.GL_HIER_HEAT_MAP;
ArrayList<ESelectionType> alSelectionTypes = new ArrayList<ESelectionType>();
alSelectionTypes.add(ESelectionType.NORMAL);
alSelectionTypes.add(ESelectionType.MOUSE_OVER);
alSelectionTypes.add(ESelectionType.SELECTION);
contentSelectionManager = new SelectionManager.Builder(EIDType.EXPRESSION_INDEX).build();
storageSelectionManager = new SelectionManager.Builder(EIDType.EXPERIMENT_INDEX).build();
colorMapper = ColorMappingManager.get().getColorMapping(EColorMappingType.GENE_EXPRESSION);
glKeyListener = new GLHierarchicalHeatMapKeyListener(this);
createHeatMap();
createDendrogram();
}
/**
* Function used in keyListener to forward upDownselection to EHM
*
* @return embedded heat map
*/
public GLHeatMap getEmbeddedHeatMap() {
return glHeatMapView;
}
@Override
public void init(GL gl) {
glHeatMapView.initRemote(gl, this, glMouseListener, null, null);
glDendrogramView.initRemote(gl, this, glMouseListener, null, null);
initTextures(gl);
// activateGroupHandling();
}
/**
* Function responsible for initialization of hierarchy levels. Depending on the amount of samples in the
* data set 2 or 3 levels are used.
*/
private void initHierarchy() {
if (set == null)
return;
iNumberOfElements = contentVA.size();
if (iNumberOfElements < MIN_SAMPLES_SKIP_LEVEL_2) {
bSkipLevel1 = true;
bSkipLevel2 = true;
iSamplesPerHeatmap = iNumberOfElements;
iAlNumberSamples.clear();
iAlNumberSamples.add(iNumberOfElements);
}
else if (iNumberOfElements < MIN_SAMPLES_SKIP_LEVEL_1) {
bSkipLevel1 = true;
bSkipLevel2 = false;
iSamplesPerTexture = iNumberOfElements;
iSamplesLevel2 = iNumberOfElements;
iSamplesPerHeatmap = (int) Math.floor(iSamplesPerTexture / 3);
}
else {
bSkipLevel1 = false;
bSkipLevel2 = false;
iSamplesPerTexture = (int) Math.floor(iNumberOfElements / 5);
if (iSamplesPerTexture > 250)
iSamplesPerTexture = 250;
iSamplesLevel2 = iSamplesPerTexture;
iSamplesPerHeatmap = (int) Math.floor(iSamplesPerTexture / 3);
}
if (iSamplesPerHeatmap > MAX_SAMPLES_PER_HEATMAP)
iSamplesPerTexture = 100;
if (iSamplesPerHeatmap < MIN_SAMPLES_PER_HEATMAP)
iSamplesPerHeatmap = MIN_SAMPLES_PER_HEATMAP;
}
@Override
public void initLocal(GL gl) {
bRenderStorageHorizontally = false;
// Register keyboard listener to GL canvas
GeneralManager.get().getGUIBridge().getDisplay().asyncExec(new Runnable() {
public void run() {
parentGLCanvas.getParentComposite().addKeyListener(glKeyListener);
}
});
iGLDisplayListIndexLocal = gl.glGenLists(1);
iGLDisplayListToCall = iGLDisplayListIndexLocal;
init(gl);
}
@Override
public void initRemote(GL gl, final AGLEventListener glParentView, GLMouseListener glMouseListener,
IGLCanvasRemoteRendering remoteRenderingGLCanvas, GLInfoAreaManager infoAreaManager) {
this.remoteRenderingGLView = remoteRenderingGLCanvas;
// Register keyboard listener to GL canvas
glParentView.getParentGLCanvas().getParentComposite().getDisplay().asyncExec(new Runnable() {
public void run() {
glParentView.getParentGLCanvas().getParentComposite().addKeyListener(glKeyListener);
}
});
bRenderStorageHorizontally = false;
this.glMouseListener = glMouseListener;
iGLDisplayListIndexRemote = gl.glGenLists(1);
iGLDisplayListToCall = iGLDisplayListIndexRemote;
init(gl);
}
/**
* If no selected elements are in the current texture, the function switches the texture
*/
private void setTexture() {
boolean bSetCurrentTexture = true;
// if (AlSelection.size() > 0) {
// for (HeatMapSelection selection : AlSelection) {
//
// if (selection.getTexture() == iSelectorBar && selection.getPos() >= iFirstSampleLevel2
// && selection.getPos() <= iLastSampleLevel2 || selection.getTexture() == iSelectorBar - 1
// && selection.getPos() >= iFirstSampleLevel2 && selection.getPos() <= iLastSampleLevel2) {
// bSetCurrentTexture = false;
// break;
// }
// }
// if (bSetCurrentTexture) {
// iSelectorBar = AlSelection.get(0).getTexture() + 1;
// if (iSelectorBar == iNrSelBar) {
// iSelectorBar--;
// }
// initPosCursorLevel2();
// }
// }
}
private void initPosCursorLevel1() {
int iNumberSample = iNumberOfElements;
if (bSkipLevel1)
iSamplesLevel2 = iNumberSample;
if (iSamplesLevel2 % 2 == 0) {
iFirstSampleLevel1 = iPickedSampleLevel1 - (int) Math.floor(iSamplesLevel2 / 2) + 1;
iLastSampleLevel1 = iPickedSampleLevel1 + (int) Math.floor(iSamplesLevel2 / 2);
}
else {
iFirstSampleLevel1 = iPickedSampleLevel1 - (int) Math.ceil(iSamplesLevel2 / 2);
iLastSampleLevel1 = iPickedSampleLevel1 + (int) Math.floor(iSamplesLevel2 / 2);
}
if (iPickedSampleLevel1 < iSamplesLevel2 / 2) {
iPickedSampleLevel1 = (int) Math.floor(iSamplesLevel2 / 2);
iFirstSampleLevel1 = 0;
iLastSampleLevel1 = iSamplesLevel2 - 1;
}
else if (iPickedSampleLevel1 > iNumberSample - 1 - iSamplesLevel2 / 2) {
iPickedSampleLevel1 = (int) Math.ceil(iNumberSample - iSamplesLevel2 / 2);
iLastSampleLevel1 = iNumberSample - 1;
iFirstSampleLevel1 = iNumberSample - iSamplesLevel2;
}
}
/**
* Init (reset) the positions of cursors used for highlighting selected elements in stage 2 (texture)
*
* @param
*/
private void initPosCursorLevel2() {
if (bSkipLevel2) {
iSamplesPerHeatmap = (int) Math.floor(iSamplesPerTexture / 3);
if (iSamplesPerHeatmap % 2 == 0) {
iFirstSampleLevel2 = iPickedSampleLevel2 - (int) Math.floor(iSamplesPerHeatmap / 2) + 1;
iLastSampleLevel2 = iPickedSampleLevel2 + (int) Math.floor(iSamplesPerHeatmap / 2);
}
else {
iFirstSampleLevel2 = iPickedSampleLevel2 - (int) Math.ceil(iSamplesPerHeatmap / 2);
iLastSampleLevel2 = iPickedSampleLevel2 + (int) Math.floor(iSamplesPerHeatmap / 2);
}
}
iSamplesPerHeatmap = iSamplesLevel2 / 3;
if (iSamplesPerHeatmap >= 3 * MIN_SAMPLES_PER_HEATMAP)
iSamplesPerHeatmap = 2 * MIN_SAMPLES_PER_HEATMAP;
else if (iSamplesPerHeatmap > MIN_SAMPLES_PER_HEATMAP)
iSamplesPerHeatmap = MIN_SAMPLES_PER_HEATMAP;
iPickedSampleLevel2 = (int) Math.floor(iSamplesPerHeatmap / 2);
iFirstSampleLevel2 = 0;
iLastSampleLevel2 = iSamplesPerHeatmap - 1;
}
private void calculateTextures() {
// less than 100 elements in VA, level 1 (overview bar) will not be rendered
if (bSkipLevel1) {
iNrTextures = 1;
AlTextures.clear();
iAlNumberSamples.clear();
Texture tempTextur = null;
AlTextures.add(tempTextur);
iAlNumberSamples.add(iSamplesPerTexture);
}
else {
iNrTextures = (int) Math.ceil(contentVA.size() / iSamplesPerTexture);
AlTextures.clear();
iAlNumberSamples.clear();
Texture tempTextur = null;
for (int i = 0; i < iNrTextures; i++) {
AlTextures.add(tempTextur);
iAlNumberSamples.add(iSamplesPerTexture);
}
}
}
/**
* Init textures, build array of textures used for holding the whole examples from contentSelectionManager
*
* @param
*/
private void initTextures(final GL gl) {
if (bSkipLevel1 && bSkipLevel2)
return;
if (bSkipLevel1) {
AlTextures.clear();
iAlNumberSamples.clear();
Texture tempTextur;
int iTextureHeight = contentVA.size();
int iTextureWidth = storageVA.size();
float fLookupValue = 0;
float fOpacity = 0;
FloatBuffer FbTemp = BufferUtil.newFloatBuffer(iTextureWidth * iTextureHeight * 4);
for (Integer iContentIndex : contentVA) {
for (Integer iStorageIndex : storageVA) {
if (contentSelectionManager.checkStatus(ESelectionType.DESELECTED, iContentIndex)) {
fOpacity = 0.3f;
}
else {
fOpacity = 1.0f;
}
fLookupValue =
set.get(iStorageIndex).getFloat(EDataRepresentation.NORMALIZED, iContentIndex);
float[] fArMappingColor = colorMapper.getColor(fLookupValue);
float[] fArRgba =
{ fArMappingColor[0], fArMappingColor[1], fArMappingColor[2], fOpacity };
FbTemp.put(fArRgba);
}
}
FbTemp.rewind();
TextureData texData =
new TextureData(GL.GL_RGBA /* internalFormat */, iTextureWidth /* height */,
iTextureHeight /* width */, 0 /* border */, GL.GL_RGBA /* pixelFormat */,
GL.GL_FLOAT /* pixelType */, false /* mipmap */, false /* dataIsCompressed */,
false /* mustFlipVertically */, FbTemp, null);
tempTextur = TextureIO.newTexture(0);
tempTextur.updateImage(texData);
AlTextures.add(tempTextur);
iAlNumberSamples.add(iSamplesPerTexture);
}
else {
iNrTextures = (int) Math.ceil((contentVA.size() + 0.0001) / iSamplesPerTexture);
AlTextures.clear();
iAlNumberSamples.clear();
Texture tempTextur;
int iTextureHeight = contentVA.size();
int iTextureWidth = storageVA.size();
iSamplesPerTexture = (int) Math.ceil((iTextureHeight + 0.0001) / iNrTextures);
float fLookupValue = 0;
float fOpacity = 0;
FloatBuffer[] FbTemp = new FloatBuffer[iNrTextures];
for (int itextures = 0; itextures < iNrTextures; itextures++) {
if (itextures == iNrTextures - 1) {
iAlNumberSamples.add(iTextureHeight - iSamplesPerTexture * itextures);
FbTemp[itextures] =
BufferUtil.newFloatBuffer((iTextureHeight - iSamplesPerTexture * itextures)
* iTextureWidth * 4);
}
else {
iAlNumberSamples.add(iSamplesPerTexture);
FbTemp[itextures] = BufferUtil.newFloatBuffer(iSamplesPerTexture * iTextureWidth * 4);
}
}
int iCount = 0;
int iTextureCounter = 0;
for (Integer iContentIndex : contentVA) {
iCount++;
for (Integer iStorageIndex : storageVA) {
if (contentSelectionManager.checkStatus(ESelectionType.DESELECTED, iContentIndex)) {
fOpacity = 0.3f;
}
else {
fOpacity = 1.0f;
}
fLookupValue =
set.get(iStorageIndex).getFloat(EDataRepresentation.NORMALIZED, iContentIndex);
float[] fArMappingColor = colorMapper.getColor(fLookupValue);
float[] fArRgba =
{ fArMappingColor[0], fArMappingColor[1], fArMappingColor[2], fOpacity };
FbTemp[iTextureCounter].put(fArRgba);
}
if (iCount >= iAlNumberSamples.get(iTextureCounter)) {
FbTemp[iTextureCounter].rewind();
TextureData texData =
new TextureData(GL.GL_RGBA /* internalFormat */, iTextureWidth /* height */,
iAlNumberSamples.get(iTextureCounter) /* width */, 0 /* border */,
GL.GL_RGBA /* pixelFormat */, GL.GL_FLOAT /* pixelType */, false /* mipmap */,
false /* dataIsCompressed */, false /* mustFlipVertically */,
FbTemp[iTextureCounter], null);
tempTextur = TextureIO.newTexture(0);
tempTextur.updateImage(texData);
AlTextures.add(tempTextur);
iTextureCounter++;
iCount = 0;
}
}
}
}
/**
* Create embedded heat map
*
* @param
*/
private void createHeatMap() {
CmdCreateGLEventListener cmdView =
(CmdCreateGLEventListener) generalManager.getCommandManager().createCommandByType(
ECommandType.CREATE_GL_HEAT_MAP_3D);
float fHeatMapHeight = viewFrustum.getHeight();
float fHeatMapWidth = viewFrustum.getWidth();
cmdView.setAttributes(EProjectionMode.ORTHOGRAPHIC, 0, fHeatMapHeight, 0, fHeatMapWidth, -20, 20,
set, -1);
cmdView.doCommand();
glHeatMapView = (GLHeatMap) cmdView.getCreatedObject();
GeneralManager.get().getUseCase().addView(glHeatMapView);
glHeatMapView.setUseCase(GeneralManager.get().getUseCase());
glHeatMapView.setRenderedRemote(true);
}
private void createDendrogram() {
CmdCreateGLEventListener cmdView =
(CmdCreateGLEventListener) generalManager.getCommandManager().createCommandByType(
ECommandType.CREATE_GL_DENDROGRAM_HORIZONTAL);
float fHeatMapHeight = viewFrustum.getHeight();
float fHeatMapWidth = viewFrustum.getWidth();
cmdView.setAttributes(EProjectionMode.ORTHOGRAPHIC, 0, fHeatMapHeight, 0, fHeatMapWidth, -20, 20,
set, -1);
cmdView.doCommand();
glDendrogramView = (GLDendrogram) cmdView.getCreatedObject();
GeneralManager.get().getUseCase().addView(glDendrogramView);
glDendrogramView.setUseCase(GeneralManager.get().getUseCase());
glDendrogramView.setRenderedRemote(true);
}
@Override
public void setDetailLevel(EDetailLevel detailLevel) {
super.setDetailLevel(detailLevel);
}
@Override
public void displayLocal(GL gl) {
if (set == null)
return;
pickingManager.handlePicking(this, gl);
if (bIsDisplayListDirtyLocal) {
buildDisplayList(gl, iGLDisplayListIndexLocal);
bIsDisplayListDirtyLocal = false;
}
iGLDisplayListToCall = iGLDisplayListIndexLocal;
display(gl);
checkForHits(gl);
if (eBusyModeState != EBusyModeState.OFF) {
renderBusyMode(gl);
}
}
@Override
public void displayRemote(GL gl) {
if (set == null)
return;
if (bIsDisplayListDirtyRemote) {
buildDisplayList(gl, iGLDisplayListIndexRemote);
bIsDisplayListDirtyRemote = false;
}
iGLDisplayListToCall = iGLDisplayListIndexRemote;
display(gl);
checkForHits(gl);
}
/**
* Function called any time a update is triggered external
*
* @param
*/
@Override
protected void reactOnExternalSelection(boolean scrollToSelection) {
if (scrollToSelection && bSkipLevel1 == false && bSkipLevel2 == false) {
setTexture();
}
}
@Override
protected void reactOnVAChanges(IVirtualArrayDelta delta) {
glHeatMapView.handleVirtualArrayUpdate(delta, getShortInfo());
bRedrawTextures = true;
setDisplayListDirty();
}
/**
* Render caption, simplified version used in (original) heatmap
*
* @param gl
* @param sLabel
* @param fXOrigin
* @param fYOrigin
* @param fFontScaling
*/
private void renderCaption(GL gl, String sLabel, float fXOrigin, float fYOrigin, float fFontScaling) {
textRenderer.setColor(1, 1, 1, 1);
gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT);
gl.glTranslatef(fXOrigin, fYOrigin, 0);
textRenderer.begin3DRendering();
textRenderer.draw3D(sLabel, 0, 0, 0, fFontScaling);
textRenderer.end3DRendering();
gl.glTranslatef(-fXOrigin, -fYOrigin, 0);
gl.glPopAttrib();
}
/**
* Render a curved (nice looking) grey area between two views
*
* @param gl
* @param startpoint1
* @param endpoint1
* @param startpoint2
* @param endpoint2
*/
private void renderSelectedDomain(GL gl, Vec3f startpoint1, Vec3f endpoint1, Vec3f startpoint2,
Vec3f endpoint2) {
float fthickness = (endpoint1.x() - startpoint1.x()) / 4;
float fScalFactor1, fScalFactor2;
if (endpoint1.y() - startpoint1.y() < 0.2f) {
fScalFactor1 = (endpoint1.y() - startpoint1.y()) * 5f;
}
else {
fScalFactor1 = 1;
}
if (startpoint2.y() - endpoint2.y() < 0.2f) {
fScalFactor2 = (startpoint2.y() - endpoint2.y()) * 5f;
}
else {
fScalFactor2 = 1;
}
gl.glColor4f(0.5f, 0.5f, 0.5f, 1f);
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(startpoint1.x(), startpoint1.y(), startpoint1.z());
gl.glVertex3f(startpoint1.x() + 2 * fthickness, startpoint1.y(), startpoint1.z());
gl.glVertex3f(startpoint2.x() + 2 * fthickness, startpoint2.y(), startpoint2.z());
gl.glVertex3f(startpoint2.x(), startpoint2.y(), startpoint2.z());
gl.glEnd();
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(endpoint1.x(), endpoint1.y(), endpoint1.z());
gl.glVertex3f(endpoint1.x() - 1 * fthickness, endpoint1.y(), endpoint1.z());
gl.glVertex3f(endpoint2.x() - 1 * fthickness, endpoint2.y(), endpoint2.z());
gl.glVertex3f(endpoint2.x(), endpoint2.y(), endpoint2.z());
gl.glEnd();
// fill gap
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(endpoint1.x() - 1 * fthickness, endpoint1.y() - 0.1f * fScalFactor1, endpoint1.z());
gl.glVertex3f(endpoint1.x() - 2 * fthickness, endpoint1.y() - 0.1f * fScalFactor1, endpoint1.z());
gl.glVertex3f(endpoint2.x() - 2 * fthickness, endpoint2.y() + 0.1f * fScalFactor2, endpoint2.z());
gl.glVertex3f(endpoint2.x() - 1 * fthickness, endpoint2.y() + 0.1f * fScalFactor2, endpoint2.z());
gl.glEnd();
gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT);
gl.glColor4f(1, 1, 1, 1);
Texture TextureMask = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_MASK_CURVE);
TextureMask.enable();
TextureMask.bind();
TextureCoords texCoordsMask = TextureMask.getImageTexCoords();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoordsMask.right(), texCoordsMask.top());
gl.glVertex3f(startpoint1.x() + 2 * fthickness, startpoint1.y(), startpoint1.z());
gl.glTexCoord2f(texCoordsMask.left(), texCoordsMask.top());
gl.glVertex3f(startpoint1.x() + 1 * fthickness, startpoint1.y(), startpoint1.z());
gl.glTexCoord2f(texCoordsMask.left(), texCoordsMask.bottom());
gl.glVertex3f(startpoint1.x() + 1 * fthickness, startpoint1.y() + 0.1f * fScalFactor1, startpoint1
.z());
gl.glTexCoord2f(texCoordsMask.right(), texCoordsMask.bottom());
gl.glVertex3f(startpoint1.x() + 2 * fthickness, startpoint1.y() + 0.1f * fScalFactor1, startpoint1
.z());
gl.glEnd();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoordsMask.right(), texCoordsMask.top());
gl.glVertex3f(startpoint2.x() + 2 * fthickness, startpoint2.y(), startpoint2.z());
gl.glTexCoord2f(texCoordsMask.left(), texCoordsMask.top());
gl.glVertex3f(startpoint2.x() + 1 * fthickness, startpoint2.y(), startpoint2.z());
gl.glTexCoord2f(texCoordsMask.left(), texCoordsMask.bottom());
gl.glVertex3f(startpoint2.x() + 1 * fthickness, startpoint2.y() - 0.1f * fScalFactor2, startpoint2
.z());
gl.glTexCoord2f(texCoordsMask.right(), texCoordsMask.bottom());
gl.glVertex3f(startpoint2.x() + 2 * fthickness, startpoint2.y() - 0.1f * fScalFactor2, startpoint2
.z());
gl.glEnd();
TextureMask.disable();
Texture TextureMaskNeg = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_MASK_CURVE_NEG);
TextureMaskNeg.enable();
TextureMaskNeg.bind();
TextureCoords texCoordsMaskNeg = TextureMaskNeg.getImageTexCoords();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoordsMaskNeg.left(), texCoordsMaskNeg.bottom());
gl.glVertex3f(endpoint1.x() - 2 * fthickness, endpoint1.y() - 0.1f * fScalFactor1, endpoint1.z());
gl.glTexCoord2f(texCoordsMaskNeg.right(), texCoordsMaskNeg.bottom());
gl.glVertex3f(endpoint1.x() - 1 * fthickness, endpoint1.y() - 0.1f * fScalFactor1, endpoint1.z());
gl.glTexCoord2f(texCoordsMaskNeg.right(), texCoordsMaskNeg.top());
gl.glVertex3f(endpoint1.x() - 1 * fthickness, endpoint1.y(), endpoint1.z());
gl.glTexCoord2f(texCoordsMaskNeg.left(), texCoordsMaskNeg.top());
gl.glVertex3f(endpoint1.x() - 2 * fthickness, endpoint1.y(), endpoint1.z());
gl.glEnd();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoordsMaskNeg.left(), texCoordsMaskNeg.bottom());
gl.glVertex3f(endpoint2.x() - 2 * fthickness, endpoint2.y() + 0.1f * fScalFactor2, endpoint2.z());
gl.glTexCoord2f(texCoordsMaskNeg.right(), texCoordsMaskNeg.bottom());
gl.glVertex3f(endpoint2.x() - 1 * fthickness, endpoint2.y() + 0.1f * fScalFactor2, endpoint2.z());
gl.glTexCoord2f(texCoordsMaskNeg.right(), texCoordsMaskNeg.top());
gl.glVertex3f(endpoint2.x() - 1 * fthickness, endpoint2.y(), endpoint2.z());
gl.glTexCoord2f(texCoordsMaskNeg.left(), texCoordsMaskNeg.top());
gl.glVertex3f(endpoint2.x() - 2 * fthickness, endpoint2.y(), endpoint2.z());
gl.glEnd();
TextureMaskNeg.disable();
gl.glPopAttrib();
}
private void renderClassAssignmentsExperimentsLevel2(final GL gl) {
float fWidth = viewFrustum.getWidth() / 4.0f * fAnimationScale;
int iNrElements = storageVA.size();
float fWidthSamples = fWidth / iNrElements;
float fxpos = 0;
float fHeight = viewFrustum.getHeight();
IGroupList groupList = storageVA.getGroupList();
int iNrClasses = groupList.size();
gl.glLineWidth(1f);
for (int i = 0; i < iNrClasses; i++) {
float classWidth = groupList.get(i).getNrElements() * fWidthSamples;
if (groupList.get(i).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (groupList.get(i).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.HIER_HEAT_MAP_EXPERIMENTS_GROUP, i));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fxpos, fHeight, 0);
gl.glVertex3f(fxpos, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight, 0);
gl.glEnd();
gl.glPopName();
if (i == iNrClasses - 1)
return;
gl.glColor4f(0f, 0f, 1f, 1);
gl.glLineWidth(1f);
gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(fxpos, fHeight, 0);
// gl.glVertex3f(fxpos, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, 0, 0);
gl.glEnd();
fxpos = fxpos + classWidth;
}
}
private void renderClassAssignmentsExperimentsLevel3(final GL gl) {
float fWidth = viewFrustum.getWidth() / 4.0f * fAnimationScale;
int iNrElements = storageVA.size();
float fWidthSamples = fWidthEHM / iNrElements;
float fxpos = 0;
if (bSkipLevel2 == false)
fxpos = fWidth + GAP_LEVEL2_3;
float fHeight = viewFrustum.getHeight();
IGroupList groupList = storageVA.getGroupList();
int iNrClasses = groupList.size();
gl.glLineWidth(1f);
for (int i = 0; i < iNrClasses; i++) {
float classWidth = groupList.get(i).getNrElements() * fWidthSamples;
if (groupList.get(i).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (groupList.get(i).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.HIER_HEAT_MAP_EXPERIMENTS_GROUP, i));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fxpos, fHeight, 0);
gl.glVertex3f(fxpos, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight + 0.1f, 0);
gl.glVertex3f(fxpos + classWidth, fHeight, 0);
gl.glEnd();
gl.glPopName();
if (i == iNrClasses - 1)
return;
gl.glColor4f(0f, 0f, 1f, 1);
gl.glLineWidth(1f);
gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(fxpos, 0.1f, 0.1f);
// gl.glVertex3f(fxpos, fHeight + 0.1f, 0.1f);
gl.glVertex3f(fxpos + classWidth, fHeight + 0.1f, 0.1f);
gl.glVertex3f(fxpos + classWidth, 0, 0.1f);
gl.glEnd();
fxpos = fxpos + classWidth;
}
}
private void renderClassAssignmentsGenesLevel1(final GL gl) {
float fHeight = viewFrustum.getHeight();
int iNrElements = iNumberOfElements;
float fHeightSamples = fHeight / iNrElements;
float fyPos = fHeight;
IGroupList groupList = contentVA.getGroupList();
int iNrClasses = groupList.size();
gl.glLineWidth(1f);
for (int i = 0; i < iNrClasses; i++) {
float classHeight = groupList.get(i).getNrElements() * fHeightSamples;
if (groupList.get(i).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (groupList.get(i).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP, i));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(-0.1f, fyPos, 0);
gl.glVertex3f(0, fyPos, 0);
gl.glVertex3f(0, fyPos - classHeight, 0);
gl.glVertex3f(-0.1f, fyPos - classHeight, 0);
gl.glEnd();
gl.glPopName();
if (i == iNrClasses - 1)
return;
gl.glColor4f(0f, 0f, 1f, 1);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(-0.1f, fyPos - classHeight, 0.1f);
gl.glVertex3f(0.1f, fyPos - classHeight, 0.1f);
gl.glEnd();
fyPos = fyPos - classHeight;
}
}
private void renderClassAssignmentsGenesLevel2(final GL gl) {
float fHeight = viewFrustum.getHeight();
float fHeightSamples = fHeight / iSamplesLevel2;
float fFieldWith = viewFrustum.getWidth() / 4.0f * fAnimationScale;
// cluster border stuff
int iIdxCluster = 0;
int iCounter = iFirstSampleLevel1;
Group group = contentVA.getGroupList().get(iIdxCluster);
while (group.getNrElements() < iCounter) {
iIdxCluster++;
iCounter -= group.getNrElements();
group = contentVA.getGroupList().get(iIdxCluster);
}
int iCnt = 0;
for (int i = 0; i < iSamplesLevel2; i++) {
if (iCounter == contentVA.getGroupList().get(iIdxCluster).getNrElements()) {
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP,
iIdxCluster));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(-0.1f, fHeight, 0);
gl.glVertex3f(0, fHeight, 0);
gl.glVertex3f(0, fHeight - fHeightSamples * iCnt, 0);
gl.glVertex3f(-0.1f, fHeight - fHeightSamples * iCnt, 0);
gl.glEnd();
gl.glPopName();
gl.glColor4f(0f, 0f, 1f, 1);
gl.glLineWidth(1f);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(-0.1f, fHeight - fHeightSamples * iCnt, 0.1f);
gl.glVertex3f(fFieldWith, fHeight - fHeightSamples * iCnt, 0.1f);
gl.glEnd();
fHeight -= fHeightSamples * iCnt;
iIdxCluster++;
iCounter = 0;
iCnt = 0;
}
iCnt++;
iCounter++;
}
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP,
iIdxCluster));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(-0.1f, fHeight, 0);
gl.glVertex3f(0, fHeight, 0);
gl.glVertex3f(0, 0, 0);
gl.glVertex3f(-0.1f, 0, 0);
gl.glEnd();
gl.glPopName();
}
private void renderClassAssignmentsGenesLevel3(final GL gl) {
float fHeight = viewFrustum.getHeight();
float fHeightSamples = fHeight / iSamplesPerHeatmap;
float fOffsetX = 0;
if (bSkipLevel2 == false)
fOffsetX = GAP_LEVEL2_3;
// cluster border stuff
int iIdxCluster = 0;
int iCounter = iFirstSampleLevel1 + iFirstSampleLevel2;
Group group = contentVA.getGroupList().get(iIdxCluster);
while (group.getNrElements() < iCounter) {
iIdxCluster++;
iCounter -= group.getNrElements();
group = contentVA.getGroupList().get(iIdxCluster);
}
int iCnt = 0;
for (int i = 0; i < iSamplesPerHeatmap; i++) {
if (iCounter == contentVA.getGroupList().get(iIdxCluster).getNrElements()) {
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP,
iIdxCluster));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fOffsetX - 0.1f, fHeight, 0);
gl.glVertex3f(fOffsetX, fHeight, 0);
gl.glVertex3f(fOffsetX, fHeight - fHeightSamples * iCnt, 0);
gl.glVertex3f(fOffsetX - 0.1f, fHeight - fHeightSamples * iCnt, 0);
gl.glEnd();
gl.glPopName();
gl.glColor4f(0f, 0f, 1f, 1);
gl.glLineWidth(1f);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fOffsetX - 0.1f, fHeight - fHeightSamples * iCnt, 0.1f);
gl.glVertex3f(fOffsetX + fWidthEHM, fHeight - fHeightSamples * iCnt, 0.1f);
gl.glEnd();
fHeight -= fHeightSamples * iCnt;
iIdxCluster++;
iCounter = 0;
iCnt = 0;
}
iCnt++;
iCounter++;
}
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.NORMAL)
gl.glColor4f(0f, 0f, 1f, 0.5f);
if (contentVA.getGroupList().get(iIdxCluster).getSelectionType() == ESelectionType.SELECTION)
gl.glColor4f(0f, 1f, 0f, 0.5f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_GENES_GROUP,
iIdxCluster));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fOffsetX - 0.1f, fHeight, 0);
gl.glVertex3f(fOffsetX, fHeight, 0);
gl.glVertex3f(fOffsetX, 0, 0);
gl.glVertex3f(fOffsetX - 0.1f, 0, 0);
gl.glEnd();
gl.glPopName();
}
/**
* Render the first stage of the hierarchy (OverviewBar)
*
* @param gl
*/
private void renderOverviewBar(GL gl) {
float fHeight;
float fWidth;
float fyOffset = 0.0f;
fHeight = viewFrustum.getHeight();
fWidth = 0.1f;
float fHeightElem = fHeight / iNumberOfElements;
float fStep = 0;
gl.glColor4f(1f, 1f, 0f, 1f);
for (int i = 0; i < iNrTextures; i++) {
fStep = fHeightElem * iAlNumberSamples.get(iNrTextures - i - 1);
AlTextures.get(iNrTextures - i - 1).enable();
AlTextures.get(iNrTextures - i - 1).bind();
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
TextureCoords texCoords = AlTextures.get(iNrTextures - i - 1).getImageTexCoords();
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.HIER_HEAT_MAP_TEXTURE_SELECTION, iNrTextures - i));
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords.left(), texCoords.top());
gl.glVertex3f(0, fyOffset, 0);
gl.glTexCoord2d(texCoords.left(), texCoords.bottom());
gl.glVertex3f(0, fyOffset + fStep, 0);
gl.glTexCoord2d(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fWidth, fyOffset + fStep, 0);
gl.glTexCoord2d(texCoords.right(), texCoords.top());
gl.glVertex3f(fWidth, fyOffset, 0);
gl.glEnd();
gl.glPopName();
fyOffset += fStep;
AlTextures.get(iNrTextures - i - 1).disable();
}
}
/**
* Render marker in OverviewBar for visualization of the currently (in stage 2) rendered part
*
* @param gl
*/
private void renderMarkerOverviewBar(final GL gl) {
float fHeight = viewFrustum.getHeight();
float fFieldWith = 0.1f;
Vec3f startpoint1, endpoint1, startpoint2, endpoint2;
float fHeightElem = fHeight / iNumberOfElements;
int iStartElem = 0;
int iLastElem = 0;
boolean colorToggle = true;
gl.glLineWidth(2f);
if (bIsDraggingActiveLevel1 == false && bIsDraggingWholeBlockLevel1 == false) {
fPosCursorFirstElementLevel1 = viewFrustum.getHeight() - iFirstSampleLevel1 * fHeightElem;
fPosCursorLastElementLevel1 = viewFrustum.getHeight() - (iLastSampleLevel1 + 1) * fHeightElem;
}
for (int currentGroup = 0; currentGroup < iNrTextures; currentGroup++) {
iStartElem = iLastElem;
iLastElem += iAlNumberSamples.get(currentGroup);
if (colorToggle)
gl.glColor4f(0f, 0f, 0f, 1f);
else
gl.glColor4f(1f, 1f, 1f, 1f);
colorToggle = (colorToggle == true) ? false : true;
// TODO: find a better way to render cluster assignments (--> +0.01f is not a fine way)
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, fHeight - fHeightElem * iStartElem, 0);
gl.glVertex3f(fFieldWith, fHeight - fHeightElem * iStartElem, 0);
gl.glVertex3f(fFieldWith, (fHeight - fHeightElem * iLastElem) + 0.01f, 0);
gl.glVertex3f(0, (fHeight - fHeightElem * iLastElem) + 0.01f, 0);
gl.glEnd();
}
// selected domain level 1
startpoint1 = new Vec3f(fFieldWith, fPosCursorFirstElementLevel1, 0);
endpoint1 = new Vec3f(GAP_LEVEL1_2, fHeight, 0);
startpoint2 = new Vec3f(fFieldWith, fPosCursorLastElementLevel1, 0);
endpoint2 = new Vec3f(GAP_LEVEL1_2, 0, 0);
renderSelectedDomain(gl, startpoint1, endpoint1, startpoint2, endpoint2);
gl.glColor4fv(MOUSE_OVER_COLOR, 0);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, fPosCursorFirstElementLevel1, 0);
gl.glVertex3f(fFieldWith, fPosCursorFirstElementLevel1, 0);
gl.glVertex3f(fFieldWith, fPosCursorLastElementLevel1, 0);
gl.glVertex3f(0, fPosCursorLastElementLevel1, 0);
// gl.glVertex3f(0, viewFrustum.getHeight() - iFirstSampleLevel1 * fHeightElem, 0);
// gl.glVertex3f(fFieldWith, viewFrustum.getHeight() - iFirstSampleLevel1 * fHeightElem, 0);
// gl.glVertex3f(fFieldWith, viewFrustum.getHeight() - (iLastSampleLevel1 + 1) * fHeightElem, 0);
// gl.glVertex3f(0, viewFrustum.getHeight() - (iLastSampleLevel1 + 1) * fHeightElem, 0);
gl.glEnd();
gl.glBegin(GL.GL_LINE_LOOP);
gl
.glVertex3f(0, viewFrustum.getHeight() - (iFirstSampleLevel1 + iFirstSampleLevel2) * fHeightElem,
0);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight() - (iFirstSampleLevel1 + iFirstSampleLevel2)
* fHeightElem, 0);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- ((iFirstSampleLevel1 + iLastSampleLevel2) + 1) * fHeightElem, 0);
gl.glVertex3f(0, viewFrustum.getHeight() - ((iFirstSampleLevel1 + iLastSampleLevel2) + 1)
* fHeightElem, 0);
gl.glEnd();
if (bRenderCaption == true) {
renderCaption(gl, "nr:" + iSamplesLevel2, 0.0f, viewFrustum.getHeight() - iPickedSampleLevel1
* fHeightElem, 0.004f);
}
gl.glColor4f(1f, 1f, 1f, 1f);
}
/**
* Render marker next to OverviewBar for visualization of selected elements in the data set
*
* @param gl
*/
private void renderSelectedElementsOverviewBar(GL gl) {
float fHeight = viewFrustum.getHeight();
float fBarWidth = 0.1f;
float fHeightElem = fHeight / contentVA.size();
// for (HeatMapSelection selection : AlSelection) {
// if (selection.getSelectionType() == ESelectionType.MOUSE_OVER) {
// gl.glColor4fv(MOUSE_OVER_COLOR, 0);
// }
// else if (selection.getSelectionType() == ESelectionType.SELECTION) {
// gl.glColor4fv(SELECTED_COLOR, 0);
// }
// // else if (selection.getSelectionType() == ESelectionType.DESELECTED) {
// // gl.glColor4f(1, 1, 1, 0.5f);
// // }
// else
// continue;
//
// float fStartElem = 0;
//
// for (int i = 0; i < selection.getTexture(); i++)
// fStartElem += iAlNumberSamples.get(i);
//
// // elements in overview bar
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(fBarWidth, fHeight - fHeightElem * fStartElem, 0.001f);
// gl.glVertex3f(fBarWidth + 0.1f, fHeight - fHeightElem * fStartElem, 0.001f);
// gl.glVertex3f(fBarWidth + 0.1f, fHeight - fHeightElem
// * (fStartElem + iAlNumberSamples.get(selection.getTexture())), 0.001f);
// gl.glVertex3f(fBarWidth, fHeight - fHeightElem
// * (fStartElem + iAlNumberSamples.get(selection.getTexture())), 0.001f);
// gl.glEnd();
// }
// gl.glColor4f(1f, 1f, 0f, 1f);
}
/**
* Render the second stage of the hierarchy (Texture)
*
* @param gl
*/
private void renderTextureHeatMap(GL gl) {
float fHeight;
float fWidth;
fHeight = viewFrustum.getHeight();
fWidth = viewFrustum.getWidth() / 4.0f * fAnimationScale;
int iFirstTexture = 0;
int iLastTexture = 0;
int iFirstElementFirstTexture = iFirstSampleLevel1;
int iLastElementLastTexture = iLastSampleLevel1;
int iNrTexturesInUse = 0;
gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_FIELD_SELECTION, 1));
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
if (bSkipLevel1) {
Texture TexTemp1 = AlTextures.get(0);
TexTemp1.enable();
TexTemp1.bind();
TextureCoords texCoords1 = TexTemp1.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords1.left(), texCoords1.top());
gl.glVertex3f(0, 0, 0);
gl.glTexCoord2d(texCoords1.left(), texCoords1.bottom());
gl.glVertex3f(0, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.bottom());
gl.glVertex3f(fWidth, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.top());
gl.glVertex3f(fWidth, 0, 0);
gl.glEnd();
TexTemp1.disable();
}
else {
while (iAlNumberSamples.get(iFirstTexture) < iFirstElementFirstTexture) {
iFirstElementFirstTexture -= iAlNumberSamples.get(iFirstTexture);
if (iFirstTexture < iAlNumberSamples.size() - 1)
iFirstTexture++;
}
while (iLastElementLastTexture > iAlNumberSamples.get(iLastTexture)) {
iLastElementLastTexture -= iAlNumberSamples.get(iLastTexture);
iLastTexture++;
if (iLastTexture == iAlNumberSamples.size() - 1) {
if (iLastElementLastTexture > iSamplesPerTexture)
iLastElementLastTexture = iSamplesPerTexture;
break;
}
}
iNrTexturesInUse = iLastTexture - iFirstTexture + 1;
// System.out.println("\niSamplesPerTexture: " + iSamplesPerTexture + " isamplesLevel2: "
// + iSamplesLevel2);
// System.out.println("iFirstTexture: " + iFirstTexture);
// System.out.println("iFirstElementFirstTexture: " + iFirstElementFirstTexture);
// System.out.println("iLastTexture: " + iLastTexture);
// System.out.println("iLastElementLastTexture: " + iLastElementLastTexture);
// System.out.println("iNrTexturesInUse: " + iNrTexturesInUse);
if (iNrTexturesInUse == 1) {
double dScalingFirstElement = (iFirstElementFirstTexture + 0.001) / iSamplesLevel2;
double dScalingLastElement = (iLastElementLastTexture + 0.001) / iSamplesLevel2;
// System.out.println("dScalingFirstElement: " + dScalingFirstElement);
// System.out.println("dScalingLastElement: " + dScalingLastElement);
Texture TexTemp1 = AlTextures.get(iFirstTexture);
TexTemp1.enable();
TexTemp1.bind();
TextureCoords texCoords1 = TexTemp1.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords1.left(), texCoords1.top() * dScalingLastElement);
gl.glVertex3f(0, 0, 0);
gl.glTexCoord2d(texCoords1.left(), texCoords1.bottom() * dScalingFirstElement);
gl.glVertex3f(0, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.bottom() * dScalingFirstElement);
gl.glVertex3f(fWidth, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.top() * dScalingLastElement);
gl.glVertex3f(fWidth, 0, 0);
gl.glEnd();
TexTemp1.disable();
}
else if (iNrTexturesInUse == 2) {
// float fScalingFirstTexture =
// (iSamplesPerTexture - iFirstElementFirstTexture + 0.001f) / iSamplesLevel2;
float fScalingLastTexture = (iLastElementLastTexture + 0.001f) / iSamplesLevel2;
// float fRatioFirstTexture =
// (iSamplesPerTexture - iFirstElementFirstTexture + 0.001f) / iSamplesPerTexture;
// float fRatioLastTexture = (iLastElementLastTexture + 0.001f) / iSamplesPerTexture;
float fRatioFirstTexture =
(iSamplesPerTexture - iFirstElementFirstTexture + 0.001f)
/ iAlNumberSamples.get(iFirstTexture);
float fRatioLastTexture =
(iLastElementLastTexture + 0.001f) / iAlNumberSamples.get(iLastTexture);
// System.out.println("dScalingFirstElement: " + dScalingFirstElement);
// System.out.println("dScalingLastElement: " + dScalingLastElement);
// double sum = dScalingLastElement + dScalingFirstElement;
// System.out.println("sum : " + sum);
Texture TexTemp1 = AlTextures.get(iFirstTexture);
TexTemp1.enable();
TexTemp1.bind();
TextureCoords texCoords1 = TexTemp1.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords1.left(), texCoords1.top());
gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords1.left(), texCoords1.bottom() + (1 - fRatioFirstTexture));
gl.glVertex3f(0, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.bottom() + (1 - fRatioFirstTexture));
gl.glVertex3f(fWidth, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.top());
gl.glVertex3f(fWidth, fHeight * fScalingLastTexture, 0);
gl.glEnd();
TexTemp1.disable();
// gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(viewFrustum.getWidth(), fHeight * fScalingLastTexture, 0);
// gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
// gl.glEnd();
Texture TexTemp2 = AlTextures.get(iLastTexture);
TexTemp2.enable();
TexTemp2.bind();
TextureCoords texCoords2 = TexTemp2.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords2.left(), texCoords2.top() * fRatioLastTexture);
gl.glVertex3f(0, 0, 0);
gl.glTexCoord2d(texCoords2.left(), texCoords2.bottom());
gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords2.right(), texCoords2.bottom());
gl.glVertex3f(fWidth, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords2.right(), texCoords2.top() * fRatioLastTexture);
gl.glVertex3f(fWidth, 0, 0);
gl.glEnd();
TexTemp2.disable();
}
else if (iNrTexturesInUse == 3) {
float fScalingFirstTexture =
(iSamplesPerTexture - iFirstElementFirstTexture + 0.001f) / iSamplesLevel2;
float fScalingLastTexture = (iLastElementLastTexture + 0.001f) / iSamplesLevel2;
// float fRatioFirstTexture =
// (iSamplesPerTexture - iFirstElementFirstTexture + 0.001f) / iSamplesPerTexture;
// float fRatioLastTexture = (iLastElementLastTexture + 0.001f) / iSamplesPerTexture;
float fRatioFirstTexture =
(iSamplesPerTexture - iFirstElementFirstTexture + 0.001f)
/ iAlNumberSamples.get(iFirstTexture);
float fRatioLastTexture =
(iLastElementLastTexture + 0.001f) / iAlNumberSamples.get(iLastTexture);
Texture TexTemp1 = AlTextures.get(iFirstTexture);
TexTemp1.enable();
TexTemp1.bind();
TextureCoords texCoords1 = TexTemp1.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords1.left(), texCoords1.top());
gl.glVertex3f(0, fHeight * (1 - fScalingFirstTexture), 0);
gl.glTexCoord2d(texCoords1.left(), texCoords1.bottom() + (1 - fRatioFirstTexture));
gl.glVertex3f(0, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.bottom() + (1 - fRatioFirstTexture));
gl.glVertex3f(fWidth, fHeight, 0);
gl.glTexCoord2d(texCoords1.right(), texCoords1.top());
gl.glVertex3f(fWidth, fHeight * (1 - fScalingFirstTexture), 0);
gl.glEnd();
TexTemp1.disable();
// gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(viewFrustum.getWidth(), fHeight * (1 - fScalingFirstTexture), 0);
// gl.glVertex3f(0, fHeight * (1 - fScalingFirstTexture), 0);
// gl.glEnd();
Texture TexTemp2 = AlTextures.get(iFirstTexture + 1);
TexTemp2.enable();
TexTemp2.bind();
TextureCoords texCoords2 = TexTemp2.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords2.left(), texCoords2.top());
gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords2.left(), texCoords2.bottom());
gl.glVertex3f(0, fHeight * (1 - fScalingFirstTexture), 0);
gl.glTexCoord2d(texCoords2.right(), texCoords2.bottom());
gl.glVertex3f(fWidth, fHeight * (1 - fScalingFirstTexture), 0);
gl.glTexCoord2d(texCoords2.right(), texCoords2.top());
gl.glVertex3f(fWidth, fHeight * fScalingLastTexture, 0);
gl.glEnd();
TexTemp2.disable();
// gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(viewFrustum.getWidth(), fHeight * fScalingLastTexture, 0);
// gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
// gl.glEnd();
Texture TexTemp3 = AlTextures.get(iLastTexture);
TexTemp3.enable();
TexTemp3.bind();
TextureCoords texCoords3 = TexTemp3.getImageTexCoords();
gl.glBegin(GL.GL_QUADS);
gl.glTexCoord2d(texCoords3.left(), texCoords3.top() * fRatioLastTexture);
gl.glVertex3f(0, 0, 0);
gl.glTexCoord2d(texCoords3.left(), texCoords3.bottom());
gl.glVertex3f(0, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords3.right(), texCoords3.bottom());
gl.glVertex3f(fWidth, fHeight * fScalingLastTexture, 0);
gl.glTexCoord2d(texCoords3.right(), texCoords3.top() * fRatioLastTexture);
gl.glVertex3f(fWidth, 0, 0);
gl.glEnd();
TexTemp3.disable();
}
else {
// FIXME: do something smart
System.out.println("something went wrong !!");
}
}
gl.glPopName();
gl.glPopAttrib();
}
/**
* Render marker in Texture for visualization of the currently (in stage 3) rendered part
*
* @param gl
*/
private void renderMarkerTexture(final GL gl) {
float fFieldWith = viewFrustum.getWidth() / 4.0f * fAnimationScale;
// float fHeightSampleLevel2 = viewFrustum.getHeight() / (iAlNumberSamples.get(iSelectorBar - 1));// *
// 2);
float fHeightSampleLevel2 = viewFrustum.getHeight() / iSamplesLevel2;
Vec3f startpoint1, endpoint1, startpoint2, endpoint2;
gl.glColor4f(1, 1, 0, 1);
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, viewFrustum.getHeight() - iFirstSampleLevel2 * fHeightSampleLevel2, 0);
gl.glVertex3f(fFieldWith, viewFrustum.getHeight() - iFirstSampleLevel2 * fHeightSampleLevel2, 0);
gl.glVertex3f(fFieldWith, viewFrustum.getHeight() - (iLastSampleLevel2 + 1) * fHeightSampleLevel2, 0);
gl.glVertex3f(0, viewFrustum.getHeight() - (iLastSampleLevel2 + 1) * fHeightSampleLevel2, 0);
// gl.glVertex3f(0, fPosCursorFirstElementLevel3, 0);
// gl.glVertex3f(fFieldWith, fPosCursorFirstElementLevel3, 0);
// gl.glVertex3f(fFieldWith, fPosCursorLastElementLevel3, 0);
// gl.glVertex3f(0, fPosCursorLastElementLevel3, 0);
gl.glEnd();
if (bIsDraggingActiveLevel2 == false) {
fPosCursorFirstElementLevel2 = viewFrustum.getHeight() - iFirstSampleLevel2 * fHeightSampleLevel2;
fPosCursorLastElementLevel2 =
viewFrustum.getHeight() - (iLastSampleLevel2 + 1) * fHeightSampleLevel2;
}
startpoint1 =
new Vec3f(fFieldWith, viewFrustum.getHeight() - iFirstSampleLevel2 * fHeightSampleLevel2, 0);
endpoint1 = new Vec3f(fFieldWith + GAP_LEVEL2_3, viewFrustum.getHeight(), 0);
startpoint2 =
new Vec3f(fFieldWith, viewFrustum.getHeight() - (iLastSampleLevel2 + 1) * fHeightSampleLevel2, 0);
endpoint2 = new Vec3f(fFieldWith + GAP_LEVEL2_3, 0.0f, 0);
renderSelectedDomain(gl, startpoint1, endpoint1, startpoint2, endpoint2);
Texture tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_MIDDLE);
tempTexture.enable();
tempTexture.bind();
float fYCoord = viewFrustum.getHeight() / 2;
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl
.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_INFOCUS_SELECTION,
1));
if (bIsHeatmapInFocus) {
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(fFieldWith + 0.3f, fYCoord - 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fFieldWith + 0.3f, fYCoord + 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(fFieldWith + 0.4f, fYCoord + 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(fFieldWith + 0.4f, fYCoord - 0.3f, 0.1f);
gl.glEnd();
}
else {
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(fFieldWith + 0.3f, fYCoord - 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(fFieldWith + 0.3f, fYCoord + 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fFieldWith + 0.4f, fYCoord + 0.3f, 0.1f);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(fFieldWith + 0.4f, fYCoord - 0.3f, 0.1f);
gl.glEnd();
}
gl.glPopName();
tempTexture.disable();
if (bRenderCaption == true) {
renderCaption(gl, "Number Samples:" + iSamplesPerHeatmap, 0.0f, viewFrustum.getHeight()
- iPickedSampleLevel2 * fHeightSampleLevel2, 0.005f);
bRenderCaption = false;
}
}
/**
* Render marker in Texture (level 2) for visualization of selected elements in the data set
*
* @param gl
*/
private void renderSelectedElementsTexture(GL gl) {
float fFieldWith = viewFrustum.getWidth() / 4.0f * fAnimationScale;
float fHeightSample = viewFrustum.getHeight() / iSamplesLevel2;
float fExpWidth = fFieldWith / storageVA.size();
gl.glEnable(GL.GL_LINE_STIPPLE);
gl.glLineStipple(2, (short) 0xAAAA);
gl.glColor4fv(MOUSE_OVER_COLOR, 0);
Set<Integer> selectedSet = storageSelectionManager.getElements(ESelectionType.MOUSE_OVER);
int iColumnIndex = 0;
for (int iTempLine : storageVA) {
for (Integer iCurrentLine : selectedSet) {
if (iTempLine == iCurrentLine) {
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(iColumnIndex * fExpWidth, 0, SELECTION_Z);
gl.glVertex3f((iColumnIndex + 1) * fExpWidth, 0, SELECTION_Z);
gl.glVertex3f((iColumnIndex + 1) * fExpWidth, viewFrustum.getHeight(), SELECTION_Z);
gl.glVertex3f(iColumnIndex * fExpWidth, viewFrustum.getHeight(), SELECTION_Z);
gl.glEnd();
}
}
iColumnIndex++;
}
gl.glColor4fv(SELECTED_COLOR, 0);
selectedSet = storageSelectionManager.getElements(ESelectionType.SELECTION);
int iLineIndex = 0;
for (int iTempLine : storageVA) {
for (Integer iCurrentLine : selectedSet) {
if (iTempLine == iCurrentLine) {
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(iLineIndex * fExpWidth, 0, SELECTION_Z);
gl.glVertex3f((iLineIndex + 1) * fExpWidth, 0, SELECTION_Z);
gl.glVertex3f((iLineIndex + 1) * fExpWidth, viewFrustum.getHeight(), SELECTION_Z);
gl.glVertex3f(iLineIndex * fExpWidth, viewFrustum.getHeight(), SELECTION_Z);
gl.glEnd();
}
}
iLineIndex++;
}
gl.glDisable(GL.GL_LINE_STIPPLE);
Set<Integer> setMouseOverElements = contentSelectionManager.getElements(ESelectionType.MOUSE_OVER);
gl.glColor4fv(MOUSE_OVER_COLOR, 0);
for (Integer mouseOverElement : setMouseOverElements) {
int selectedElement = contentVA.indexOf(mouseOverElement.intValue());
if (selectedElement >= iFirstSampleLevel1 && selectedElement <= iLastSampleLevel1) {
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(-0.0f, viewFrustum.getHeight() - (selectedElement - iFirstSampleLevel1)
* fHeightSample, SELECTION_Z);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- (selectedElement - iFirstSampleLevel1) * fHeightSample, SELECTION_Z);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- (selectedElement + 1 - iFirstSampleLevel1) * fHeightSample, SELECTION_Z);
gl.glVertex3f(-0.0f, viewFrustum.getHeight() - (selectedElement + 1 - iFirstSampleLevel1)
* fHeightSample, SELECTION_Z);
gl.glEnd();
}
}
Set<Integer> setSelectedElements = contentSelectionManager.getElements(ESelectionType.SELECTION);
gl.glColor4fv(SELECTED_COLOR, 0);
for (Integer iSelectedElement : setSelectedElements) {
int selectedElement = contentVA.indexOf(iSelectedElement.intValue());
if (selectedElement >= iFirstSampleLevel1 && selectedElement <= iLastSampleLevel1) {
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(-0.0f, viewFrustum.getHeight() - (selectedElement - iFirstSampleLevel1)
* fHeightSample, SELECTION_Z);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- (selectedElement - iFirstSampleLevel1) * fHeightSample, SELECTION_Z);
gl.glVertex3f(fFieldWith + 0.1f, viewFrustum.getHeight()
- (selectedElement + 1 - iFirstSampleLevel1) * fHeightSample, SELECTION_Z);
gl.glVertex3f(-0.0f, viewFrustum.getHeight() - (selectedElement + 1 - iFirstSampleLevel1)
* fHeightSample, SELECTION_Z);
gl.glEnd();
}
}
}
/**
* Render cursor used for controlling level 1
*
* @param gl
*/
private void renderCursorLevel1(final GL gl) {
gl.glTranslatef(0.1f, 0, 0);
Texture tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_SMALL);
tempTexture.enable();
tempTexture.bind();
TextureCoords texCoords = tempTexture.getImageTexCoords();
// Polygon for iFirstElement-Cursor
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_CURSOR_LEVEL1, 1));
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel1, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel1, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel1 + 0.1f, 0);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel1 + 0.1f, 0);
gl.glEnd();
gl.glPopName();
// Polygon for iLastElement-Cursor
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_CURSOR_LEVEL1, 2));
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(0.0f, fPosCursorLastElementLevel1, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel1, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel1 - 0.1f, 0);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.0f, fPosCursorLastElementLevel1 - 0.1f, 0);
gl.glEnd();
gl.glPopName();
// fill gap between cursor
gl.glColor4f(0f, 0f, 0f, 0.45f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_BLOCK_CURSOR_LEVEL1,
1));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel1, 0);
gl.glVertex3f(0.0f, fPosCursorLastElementLevel1, 0);
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel1, 0);
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel1, 0);
gl.glEnd();
gl.glPopName();
gl.glPopAttrib();
tempTexture.disable();
gl.glTranslatef(-0.1f, 0, 0);
}
/**
* Render cursor used for controlling hierarchical heatmap (e.g. next Texture, previous Texture, set
* heatmap in focus)
*
* @param gl
*/
private void renderCursorLevel2(final GL gl) {
float fHeight = viewFrustum.getHeight();
float fWidth = viewFrustum.getWidth() / 4.0f;
Texture tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_SIDE);
tempTexture.enable();
tempTexture.bind();
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT);
gl.glColor4f(1f, 1, 1, 1f);
gl.glTranslatef(-viewFrustum.getWidth() / 4.0f * fAnimationScale, 0, 0);
// if (iSelectorBar != 1) {
// // Polygon for selecting previous texture
// gl.glPushName(pickingManager
// .getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_TEXTURE_CURSOR, 1));
// // left
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(0.0f, fHeight, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(0.1f, fHeight, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(0.1f, fHeight + 0.1f, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(0.0f, fHeight + 0.1f, 0);
// gl.glEnd();
//
// // right
// if (bIsHeatmapInFocus) {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 5 - 0.1f, fHeight, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 5, fHeight, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 5, fHeight + 0.1f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 5 - 0.1f, fHeight + 0.1f, 0);
// gl.glEnd();
// }
// else {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth - 0.1f, fHeight, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth, fHeight, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth, fHeight + 0.1f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth - 0.1f, fHeight + 0.1f, 0);
// gl.glEnd();
// }
//
// tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_MIDDLE);
// tempTexture.enable();
// tempTexture.bind();
//
// texCoords = tempTexture.getImageTexCoords();
// // middle
// if (bIsHeatmapInFocus) {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 10 - 0.15f, fHeight, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 10 + 0.15f, fHeight, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 10 + 0.15f, fHeight + 0.1f, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 10 - 0.15f, fHeight + 0.1f, 0);
// gl.glEnd();
// }
// else {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 2 - 0.15f, fHeight, 0.001f);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 2 + 0.15f, fHeight, 0.001f);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 2 + 0.15f, fHeight + 0.1f, 0.001f);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 2 - 0.15f, fHeight + 0.1f, 0.001f);
// gl.glEnd();
//
// // fill gap between middle and side
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(0.1f, fHeight, 0);
// gl.glVertex3f(fWidth / 2 - 0.15f, fHeight, 0);
// gl.glVertex3f(fWidth / 2 - 0.15f, fHeight + 0.1f, 0);
// gl.glVertex3f(0.1f, fHeight + 0.1f, 0);
// gl.glEnd();
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(fWidth - 0.1f, fHeight, 0);
// gl.glVertex3f(fWidth / 2 + 0.15f, fHeight, 0);
// gl.glVertex3f(fWidth / 2 + 0.15f, fHeight + 0.1f, 0);
// gl.glVertex3f(fWidth - 0.1f, fHeight + 0.1f, 0);
// gl.glEnd();
// }
// gl.glPopName();
// }
//
// tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_SIDE);
// tempTexture.enable();
// tempTexture.bind();
//
// texCoords = tempTexture.getImageTexCoords();
//
// // if (iSelectorBar != iNrSelBar - 1) {
// if (iSelectorBar != iNrSelBar) {
// // Polygon for selecting next texture
// gl.glPushName(pickingManager
// .getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_TEXTURE_CURSOR, 2));
// // left
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(0.0f, 0.0f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(0.1f, 0.0f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(0.1f, -0.1f, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(0.0f, -0.1f, 0);
// gl.glEnd();
//
// // right
// if (bIsHeatmapInFocus) {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 5 - 0.1f, 0, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 5, 0, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 5, -0.1f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 5 - 0.1f, -0.1f, 0);
// gl.glEnd();
// }
// else {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth - 0.1f, 0, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth, 0, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth, -0.1f, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth - 0.1f, -0.1f, 0);
// gl.glEnd();
// }
//
// tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_BIG_MIDDLE);
// tempTexture.enable();
// tempTexture.bind();
//
// texCoords = tempTexture.getImageTexCoords();
// // middle
// if (bIsHeatmapInFocus) {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 10 - 0.15f, 0, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 10 + 0.15f, 0, 0);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 10 + 0.15f, -0.1f, 0);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 10 - 0.15f, -0.1f, 0);
// gl.glEnd();
// }
// else {
// gl.glBegin(GL.GL_POLYGON);
// gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
// gl.glVertex3f(fWidth / 2 - 0.15f, 0, 0.001f);
// gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
// gl.glVertex3f(fWidth / 2 + 0.15f, 0, 0.001f);
// gl.glTexCoord2f(texCoords.right(), texCoords.top());
// gl.glVertex3f(fWidth / 2 + 0.15f, -0.1f, 0.001f);
// gl.glTexCoord2f(texCoords.left(), texCoords.top());
// gl.glVertex3f(fWidth / 2 - 0.15f, -0.1f, 0.001f);
// gl.glEnd();
//
// // fill gap between middle and side
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(0.1f, 0, 0);
// gl.glVertex3f(fWidth / 2 - 0.15f, 0, 0);
// gl.glVertex3f(fWidth / 2 - 0.15f, -0.1f, 0);
// gl.glVertex3f(0.1f, -0.1f, 0);
// gl.glEnd();
// gl.glBegin(GL.GL_QUADS);
// gl.glVertex3f(fWidth - 0.1f, 0, 0);
// gl.glVertex3f(fWidth / 2 + 0.15f, 0, 0);
// gl.glVertex3f(fWidth / 2 + 0.15f, -0.1f, 0);
// gl.glVertex3f(fWidth - 0.1f, -0.1f, 0);
// gl.glEnd();
// }
// gl.glPopName();
// }
//
gl.glTranslatef(viewFrustum.getWidth() / 4.0f * fAnimationScale, 0, 0);
tempTexture = textureManager.getIconTexture(gl, EIconTextures.NAVIGATION_NEXT_SMALL);
tempTexture.enable();
tempTexture.bind();
texCoords = tempTexture.getImageTexCoords();
// Polygon for iFirstElement-Cursor
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_CURSOR_LEVEL2, 1));
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel2, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel2, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel2 + 0.1f, 0);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel2 + 0.1f, 0);
gl.glEnd();
gl.glPopName();
// Polygon for iLastElement-Cursor
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_CURSOR_LEVEL2, 2));
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(0.0f, fPosCursorLastElementLevel2, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel2, 0);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel2 - 0.1f, 0);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.0f, fPosCursorLastElementLevel2 - 0.1f, 0);
gl.glEnd();
gl.glPopName();
// fill gap between cursor
gl.glColor4f(0f, 0f, 0f, 0.45f);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_BLOCK_CURSOR_LEVEL2,
1));
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorLastElementLevel2, 0);
gl.glVertex3f(0.0f, fPosCursorLastElementLevel2, 0);
gl.glVertex3f(0.0f, fPosCursorFirstElementLevel2, 0);
gl.glVertex3f(GAP_LEVEL1_2 / 4, fPosCursorFirstElementLevel2, 0);
gl.glEnd();
gl.glPopName();
gl.glPopAttrib();
tempTexture.disable();
}
@Override
public void display(GL gl) {
processEvents();
if (generalManager.isWiiModeActive()) {
handleWiiInput();
}
if (generalManager.getTrackDataProvider().isTrackModeActive()) {
handleTrackInput(gl);
}
if (bIsDraggingActiveLevel2) {
handleCursorDraggingLevel2(gl);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingActiveLevel2 = false;
}
}
if (bIsDraggingWholeBlockLevel2) {
handleBlockDraggingLevel2(gl);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingWholeBlockLevel2 = false;
}
}
if (bIsDraggingActiveLevel1) {
handleCursorDraggingLevel1(gl);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingActiveLevel1 = false;
}
}
if (bIsDraggingWholeBlockLevel1) {
handleBlockDraggingLevel1(gl);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingWholeBlockLevel1 = false;
}
}
if (bDragDropExpGroup) {
handleDragDropGroupExperiments(gl);
if (glMouseListener.wasMouseReleased()) {
bDragDropExpGroup = false;
}
}
if (bDragDropGeneGroup) {
handleDragDropGroupGenes(gl);
if (glMouseListener.wasMouseReleased()) {
bDragDropGeneGroup = false;
}
}
// if (bSplitGroupExp) {
// handleGroupSplitExperiments(gl);
// if (glMouseListener.wasMouseReleased()) {
// bSplitGroupExp = false;
// }
// }
// if (bSplitGroupGene) {
// handleGroupSplitGenes(gl);
// if (glMouseListener.wasMouseReleased()) {
// bSplitGroupGene = false;
// }
// }
gl.glCallList(iGLDisplayListToCall);
float fright = 0.0f;
float ftop = viewFrustum.getTop();
float fleftOffset = 0;
if (bSkipLevel1 == false) {
gl.glTranslatef(GAP_LEVEL2_3, 0, 0);
}
if (bSkipLevel2 == false) {
if (bIsHeatmapInFocus) {
fright = viewFrustum.getWidth() - 1.2f;
fleftOffset = 0.095f + // width level 1 + boarder
GAP_LEVEL1_2 + // width gap between level 1 and 2
viewFrustum.getWidth() / 4f * 0.2f;
}
else {
fright = viewFrustum.getWidth() - 2.75f;
fleftOffset = 0.075f + // width level 1
GAP_LEVEL1_2 + // width gap between level 1 and 2
viewFrustum.getWidth() / 4f;
}
if (glHeatMapView.isInDefaultOrientation()) {
gl.glTranslatef(fleftOffset, +0.4f, 0);
}
else {
gl.glTranslatef(fleftOffset, -0.2f, 0);
}
}
else {
ftop = viewFrustum.getTop();
fright = viewFrustum.getWidth();
gl.glTranslatef(0.1f, -0.2f, 0);
}
// render embedded heat map
glHeatMapView.getViewFrustum().setTop(ftop);
glHeatMapView.getViewFrustum().setRight(fright);
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.HIER_HEAT_MAP_VIEW_SELECTION,
glHeatMapView.getID()));
glHeatMapView.displayRemote(gl);
gl.glPopName();
fWidthEHM = glHeatMapView.getViewFrustum().getWidth() - 0.95f;
// render embedded dendrogram
glDendrogramView.getViewFrustum().setTop(ftop);
glDendrogramView.getViewFrustum().setRight(fright);
glDendrogramView.setDisplayListDirty();
// glDendrogramView.displayRemote(gl);
if (bSkipLevel2 == false) {
if (glHeatMapView.isInDefaultOrientation()) {
gl.glTranslatef(-fleftOffset, -0.4f, 0);
}
else {
gl.glTranslatef(-fleftOffset, +0.2f, 0);
}
}
else
gl.glTranslatef(-0.1f, 0.2f, 0);
if (bSkipLevel1 == false) {
gl.glTranslatef(-GAP_LEVEL2_3, 0, 0);
}
contextMenu.render(gl, this);
}
private void buildDisplayList(final GL gl, int iGLDisplayListIndex) {
if (bRedrawTextures) {
initTextures(gl);
bRedrawTextures = false;
}
if (bHasFrustumChanged) {
glHeatMapView.setDisplayListDirty();
glDendrogramView.setDisplayListDirty();
bHasFrustumChanged = false;
}
gl.glNewList(iGLDisplayListIndex, GL.GL_COMPILE);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glLoadIdentity();
// background color
gl.glColor4f(0, 0, 0, 0.15f);
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(0, 0, -0.1f);
gl.glVertex3f(viewFrustum.getRight(), 0, -0.1f);
gl.glVertex3f(viewFrustum.getRight(), viewFrustum.getHeight(), -0.1f);
gl.glVertex3f(0, viewFrustum.getHeight(), -0.1f);
gl.glEnd();
// padding along borders
viewFrustum.setTop(viewFrustum.getTop() - 0.6f);
viewFrustum.setLeft(viewFrustum.getLeft() + 0.1f);
gl.glTranslatef(0.1f, 0.4f, 0);
if (contentVA.getGroupList() != null && bSkipLevel1 == false)
renderClassAssignmentsGenesLevel1(gl);
if (bSkipLevel1 == false) {
handleTexturePickingLevel1(gl);
}
if (bSkipLevel2 == false) {
handleTexturePickingLevel2(gl);
}
// all stuff for rendering level 1 (overview bar)
if (bSkipLevel1 == false) {
renderOverviewBar(gl);
renderMarkerOverviewBar(gl);
// renderSelectedElementsOverviewBar(gl);
renderCursorLevel1(gl);
gl.glTranslatef(GAP_LEVEL2_3, 0, 0);
}
else {
gl.glColor4f(1f, 1f, 0f, 1f);
}
if (bIsHeatmapInFocus) {
fAnimationScale = 0.2f;
}
else {
fAnimationScale = 1.0f;
}
// all stuff for rendering level 2 (textures)
if (bSkipLevel2 == false) {
gl.glColor4f(1f, 1f, 1f, 1f);
renderTextureHeatMap(gl);
renderMarkerTexture(gl);
renderSelectedElementsTexture(gl);
if (contentVA.getGroupList() != null)
renderClassAssignmentsGenesLevel2(gl);
if (storageVA.getGroupList() != null)
renderClassAssignmentsExperimentsLevel2(gl);
}
else {
initHierarchy();
setEmbeddedHeatMapData();
}
if (bSkipLevel2 == false) {
gl.glTranslatef(viewFrustum.getWidth() / 4.0f * fAnimationScale, 0, 0);
renderCursorLevel2(gl);
}
if (contentVA.getGroupList() != null)
renderClassAssignmentsGenesLevel3(gl);
if (bSkipLevel2 == false)
gl.glTranslatef(-(viewFrustum.getWidth() / 4.0f * fAnimationScale), 0, 0);
if (storageVA.getGroupList() != null) {
renderClassAssignmentsExperimentsLevel3(gl);
}
viewFrustum.setTop(viewFrustum.getTop() + 0.6f);
viewFrustum.setLeft(viewFrustum.getLeft() - 0.1f);
gl.glTranslatef(-0.1f, -0.4f, 0);
if (bSkipLevel1 == false) {
gl.glTranslatef(-GAP_LEVEL1_2, 0, 0);
}
gl.glEndList();
}
/**
* Function responsible for handling SelectionDelta for embedded heatmap
*/
private void setEmbeddedHeatMapData() {
int iCount = iFirstSampleLevel1 + iFirstSampleLevel2;
// SelectionCommand command = new SelectionCommand(ESelectionCommandType.RESET);
// commands.add(command);
// glHeatMapView.handleContentTriggerSelectionCommand(eFieldDataType, command);
glHeatMapView.resetView();
IVirtualArrayDelta delta = new VirtualArrayDelta(EVAType.CONTENT_EMBEDDED_HM, eFieldDataType);
ISelectionDelta selectionDelta = new SelectionDelta(eFieldDataType);
IVirtualArray currentVirtualArray = contentVA;
int iIndex = 0;
int iContentIndex = 0;
int iStorageIndex = 0;
Set<Integer> setMouseOverElements = contentSelectionManager.getElements(ESelectionType.MOUSE_OVER);
Set<Integer> setSelectedElements = contentSelectionManager.getElements(ESelectionType.SELECTION);
Set<Integer> setDeselectedElements = contentSelectionManager.getElements(ESelectionType.DESELECTED);
for (int index = 0; index < iSamplesPerHeatmap; index++) {
iIndex = iCount + index;
if (iIndex < currentVirtualArray.size()) {
iContentIndex = currentVirtualArray.get(iIndex);
}
delta.add(VADeltaItem.append(iContentIndex));
// set elements mouse over in embedded heat Map
for (Integer iSelectedID : setMouseOverElements) {
if (iSelectedID == iContentIndex)
selectionDelta.addSelection(iContentIndex, ESelectionType.MOUSE_OVER);
}
// set elements selected in embedded heat Map
for (Integer iSelectedID : setSelectedElements) {
if (iSelectedID == iContentIndex)
selectionDelta.addSelection(iContentIndex, ESelectionType.SELECTION);
}
// set elements deselected in embedded heat Map
for (Integer iSelectedID : setDeselectedElements) {
if (iSelectedID == iContentIndex)
selectionDelta.addSelection(iContentIndex, ESelectionType.DESELECTED);
}
}
glHeatMapView.handleVirtualArrayUpdate(delta, getShortInfo());
if (selectionDelta.size() > 0) {
glHeatMapView.handleSelectionUpdate(selectionDelta, true, null);
}
// selected experiments
SelectionCommand command = new SelectionCommand(ESelectionCommandType.RESET);
glHeatMapView.handleStorageTriggerSelectionCommand(eExperimentDataType, command);
IVirtualArrayDelta deltaExp = new VirtualArrayDelta(storageVAType, eExperimentDataType);
ISelectionDelta selectionDeltaEx = new SelectionDelta(eExperimentDataType);
IVirtualArray currentVirtualArrayEx = storageVA;
setMouseOverElements = storageSelectionManager.getElements(ESelectionType.MOUSE_OVER);
setSelectedElements = storageSelectionManager.getElements(ESelectionType.SELECTION);
for (int index = 0; index < currentVirtualArrayEx.size(); index++) {
iStorageIndex = currentVirtualArrayEx.get(index);
deltaExp.add(VADeltaItem.append(iStorageIndex));
// set elements mouse over in embedded heat Map
for (Integer iSelectedID : setMouseOverElements) {
if (iSelectedID == iStorageIndex)
selectionDeltaEx.addSelection(iStorageIndex, ESelectionType.MOUSE_OVER);
}
// set elements selected in embedded heat Map
for (Integer iSelectedID : setSelectedElements) {
if (iSelectedID == iStorageIndex)
selectionDeltaEx.addSelection(iStorageIndex, ESelectionType.SELECTION);
}
}
glHeatMapView.handleVirtualArrayUpdate(deltaExp, getShortInfo());
if (selectionDeltaEx.size() > 0) {
glHeatMapView.handleSelectionUpdate(selectionDeltaEx, true, null);
}
}
public void renderHorizontally(boolean bRenderStorageHorizontally) {
if (glHeatMapView.isInDefaultOrientation()) {
glHeatMapView.changeOrientation(false);
}
else {
glHeatMapView.changeOrientation(true);
}
setDisplayListDirty();
}
@Override
protected void initLists() {
if (bRenderOnlyContext)
contentVAType = EVAType.CONTENT_CONTEXT;
else
contentVAType = EVAType.CONTENT;
contentVA = useCase.getVA(contentVAType);
storageVA = useCase.getVA(EVAType.STORAGE);
// In case of importing group info
if (set.isGeneClusterInfo())
contentVA.setGroupList(set.getGroupListGenes());
if (set.isExperimentClusterInfo())
storageVA.setGroupList(set.getGroupListExperiments());
contentSelectionManager.resetSelectionManager();
storageSelectionManager.resetSelectionManager();
contentSelectionManager.setVA(contentVA);
storageSelectionManager.setVA(storageVA);
int iNumberOfColumns = contentVA.size();
int iNumberOfRows = storageVA.size();
for (int iRowCount = 0; iRowCount < iNumberOfRows; iRowCount++) {
storageSelectionManager.initialAdd(storageVA.get(iRowCount));
}
// this for loop executes one per axis
for (int iColumnCount = 0; iColumnCount < iNumberOfColumns; iColumnCount++) {
contentSelectionManager.initialAdd(contentVA.get(iColumnCount));
}
setDisplayListDirty();
}
@Override
public String getShortInfo() {
return "Hierarchical Heat Map (" + contentVA.size() + useCase.getContentLabel(false, true) + " / "
+ storageVA.size() + " experiments)";
}
@Override
public String getDetailedInfo() {
StringBuffer sInfoText = new StringBuffer();
sInfoText.append("<b>Type:</b> Hierarchical Heat Map\n");
if (bRenderStorageHorizontally) {
sInfoText.append(contentVA.size() + " " + useCase.getContentLabel(false, true)
+ " in columns and " + storageVA.size() + " experiments in rows.\n");
}
else {
sInfoText.append(contentVA.size() + " " + useCase.getContentLabel(true, true) + " in rows and "
+ storageVA.size() + " experiments in columns.\n");
}
if (bRenderOnlyContext) {
sInfoText.append("Showing only " + " " + useCase.getContentLabel(false, true)
+ " which occur in one of the other views in focus\n");
}
else {
if (dataFilterLevel == EDataFilterLevel.COMPLETE) {
sInfoText.append("Showing all " + useCase.getContentLabel(false, true) + " in the dataset\n");
}
else if (dataFilterLevel == EDataFilterLevel.ONLY_MAPPING) {
sInfoText.append("Showing all " + useCase.getContentLabel(false, true)
+ " that have a known DAVID ID mapping\n");
}
else if (dataFilterLevel == EDataFilterLevel.ONLY_CONTEXT) {
sInfoText
.append("Showing all genes that are contained in any of the KEGG or Biocarta pathways\n");
}
}
return sInfoText.toString();
}
/**
* Determine selected element in stage 1 (overview bar)
*
* @param gl
*/
private void handleTexturePickingLevel1(GL gl) {
int iNumberSample = iNumberOfElements;
float fOffsety;
float fHeightSample = (viewFrustum.getHeight() - 0.4f) / iNumberSample;
float[] fArPickingCoords = new float[3];
if (pickingPointLevel1 != null) {
fArPickingCoords =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, pickingPointLevel1.x,
pickingPointLevel1.y);
fOffsety = viewFrustum.getHeight() - fArPickingCoords[1] + 0.4f;
iPickedSampleLevel1 = (int) Math.ceil(fOffsety / fHeightSample);
pickingPointLevel1 = null;
if (iSamplesLevel2 % 2 == 0) {
iFirstSampleLevel1 = iPickedSampleLevel1 - (int) Math.floor(iSamplesLevel2 / 2) + 1;
iLastSampleLevel1 = iPickedSampleLevel1 + (int) Math.floor(iSamplesLevel2 / 2);
}
else {
iFirstSampleLevel1 = iPickedSampleLevel1 - (int) Math.ceil(iSamplesLevel2 / 2);
iLastSampleLevel1 = iPickedSampleLevel1 + (int) Math.floor(iSamplesLevel2 / 2);
}
if (iPickedSampleLevel1 < iSamplesLevel2 / 2) {
iPickedSampleLevel1 = (int) Math.floor(iSamplesLevel2 / 2);
iFirstSampleLevel1 = 0;
iLastSampleLevel1 = iSamplesLevel2 - 1;
}
else if (iPickedSampleLevel1 > iNumberSample - 1 - iSamplesLevel2 / 2) {
iPickedSampleLevel1 = (int) Math.ceil(iNumberSample - iSamplesLevel2 / 2);
iLastSampleLevel1 = iNumberSample - 1;
iFirstSampleLevel1 = iNumberSample - iSamplesLevel2;
}
}
// initPosCursorLevel2();
setDisplayListDirty();
setEmbeddedHeatMapData();
}
/**
* Determine selected element in stage 2 (texture)
*
* @param gl
*/
private void handleTexturePickingLevel2(GL gl) {
int iNumberSample = iSamplesLevel2;
float fOffsety;
float fHeightSample = viewFrustum.getHeight() / iNumberSample;
float[] fArPickingCoords = new float[3];
if (pickingPointLevel2 != null) {
fArPickingCoords =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, pickingPointLevel2.x,
pickingPointLevel2.y);
fOffsety = viewFrustum.getHeight() - fArPickingCoords[1] + 0.4f;
iPickedSampleLevel2 = (int) Math.ceil(fOffsety / fHeightSample);
pickingPointLevel2 = null;
if (iSamplesLevel2 % 2 == 0) {
iFirstSampleLevel2 = iPickedSampleLevel2 - (int) Math.floor(iSamplesPerHeatmap / 2) + 1;
iLastSampleLevel2 = iPickedSampleLevel2 + (int) Math.floor(iSamplesPerHeatmap / 2);
}
else {
iFirstSampleLevel2 = iPickedSampleLevel2 - (int) Math.ceil(iSamplesPerHeatmap / 2);
iLastSampleLevel2 = iPickedSampleLevel2 + (int) Math.floor(iSamplesPerHeatmap / 2);
}
if (iPickedSampleLevel2 < iSamplesPerHeatmap / 2) {
iPickedSampleLevel2 = (int) Math.floor(iSamplesPerHeatmap / 2);
iFirstSampleLevel2 = 0;
iLastSampleLevel2 = iSamplesPerHeatmap - 1;
}
else if (iPickedSampleLevel2 > iNumberSample - 1 - iSamplesPerHeatmap / 2) {
iPickedSampleLevel2 = (int) Math.ceil(iNumberSample - iSamplesPerHeatmap / 2);
iLastSampleLevel2 = iNumberSample - 1;
iFirstSampleLevel2 = iNumberSample - iSamplesPerHeatmap;
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
}
/**
* Handles drag&drop of groups in experiment dimension
*
* @param gl
*/
private void handleDragDropGroupExperiments(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iTargetIdx = 0;
int iNrSamples = storageVA.size();
float fgaps = 0;
if (bSkipLevel1)
fgaps = GAP_LEVEL2_3 + 0.2f;
else
fgaps = GAP_LEVEL1_2 + GAP_LEVEL2_3;
float fleftOffset = 0.075f + // width level 1
fgaps + viewFrustum.getWidth() / 4f * fAnimationScale;
float fWidthSample = fWidthEHM / iNrSamples;
int currentElement;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
IGroupList groupList = storageVA.getGroupList();
int iNrElementsInGroup = groupList.get(iExpGroupToDrag).getNrElements();
float currentWidth = fWidthSample * iNrElementsInGroup;
float fHeight = viewFrustum.getHeight();
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(fArTargetWorldCoordinates[0], fHeight, 0);
gl.glVertex3f(fArTargetWorldCoordinates[0], fHeight - 0.1f, 0);
gl.glVertex3f(fArTargetWorldCoordinates[0] + currentWidth, fHeight - 0.1f, 0);
gl.glVertex3f(fArTargetWorldCoordinates[0] + currentWidth, fHeight, 0);
gl.glEnd();
float fXPosRelease = fArTargetWorldCoordinates[0] - fleftOffset;
currentElement = (int) Math.ceil(fXPosRelease / fWidthSample);
int iElemOffset = 0;
int cnt = 0;
if (groupList == null) {
System.out.println("No group assignment available!");
return;
}
for (Group currentGroup : groupList) {
if (currentElement < (iElemOffset + currentGroup.getNrElements())) {
iTargetIdx = cnt;
break;
}
cnt++;
iElemOffset += currentGroup.getNrElements();
}
float fPosDropMarker = fleftOffset + fWidthSample * iElemOffset;
gl.glLineWidth(6f);
gl.glColor3f(1, 0, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fPosDropMarker, fHeight, 0);
gl.glVertex3f(fPosDropMarker, fHeight - 0.2f, 0);
gl.glEnd();
if (glMouseListener.wasMouseReleased()) {
if (groupList.move(storageVA, iExpGroupToDrag, iTargetIdx) == false)
System.out.println("Move operation not allowed!");
bDragDropExpGroup = false;
bRedrawTextures = true;
setDisplayListDirty();
}
}
/**
* Handles drag&drop of groups in gene dimension
*
* @param gl
*/
private void handleDragDropGroupGenes(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iTargetIdx = 0;
int iNumberSample = iNumberOfElements;
float fOffsety;
int currentElement;
float fHeight = viewFrustum.getHeight() - 0.2f;
float fHeightSample = (fHeight - 0.4f) / iNumberSample;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
IGroupList groupList = contentVA.getGroupList();
int iNrElementsInGroup = groupList.get(iGeneGroupToDrag).getNrElements();
float currentHeight = fHeightSample * iNrElementsInGroup;
gl.glBegin(GL.GL_QUADS);
gl.glVertex3f(0f, fArTargetWorldCoordinates[1], 0);
gl.glVertex3f(0f, fArTargetWorldCoordinates[1] + currentHeight, 0);
gl.glVertex3f(0.1f, fArTargetWorldCoordinates[1] + currentHeight, 0);
gl.glVertex3f(0.1f, fArTargetWorldCoordinates[1], 0);
gl.glEnd();
fOffsety = viewFrustum.getHeight() - fArTargetWorldCoordinates[1] - 0.4f;
currentElement = (int) Math.ceil(fOffsety / fHeightSample);
int iElemOffset = 0;
int cnt = 0;
if (groupList == null) {
System.out.println("No group assignment available!");
return;
}
for (Group currentGroup : groupList) {
if (currentElement < (iElemOffset + currentGroup.getNrElements())) {
iTargetIdx = cnt;
break;
}
cnt++;
iElemOffset += currentGroup.getNrElements();
}
float fPosDropMarker = fHeight - (fHeightSample * iElemOffset);
gl.glLineWidth(6f);
gl.glColor3f(1, 0, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(0, fPosDropMarker, 0);
gl.glVertex3f(0.2f, fPosDropMarker, 0);
gl.glEnd();
if (glMouseListener.wasMouseReleased()) {
if (groupList.move(contentVA, iGeneGroupToDrag, iTargetIdx) == false)
System.out.println("Move operation not allowed!");
bDragDropGeneGroup = false;
bRedrawTextures = true;
setDisplayListDirty();
}
}
/**
* Handles the dragging cursor for gene groups
*
* @param gl
*/
private void handleGroupSplitGenes(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
float[] fArDraggedPoint = new float[3];
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
if (glMouseListener.wasMouseReleased()) {
bSplitGroupGene = false;
fArDraggedPoint =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, DraggingPoint.x,
DraggingPoint.y);
float fYPosDrag = fArDraggedPoint[1] - 0.4f;
float fYPosRelease = fArTargetWorldCoordinates[1] - 0.4f;
float fHeight = viewFrustum.getHeight() - 0.6f;
int iNrSamples = contentVA.size();
float fHeightSample = fHeight / iNrSamples;
int iFirstSample = iNrSamples - (int) Math.floor(fYPosDrag / fHeightSample);
int iLastSample = iNrSamples - (int) Math.ceil(fYPosRelease / fHeightSample);
// System.out.println("von: " + fYPosDrag + " bis: " + fYPosRelease);
// System.out.println("von: " + iFirstSample + " bis: " + iLastSample);
if (contentVA.getGroupList().split(iGroupToSplit, iFirstSample, iLastSample) == false)
System.out.println("Operation not allowed!!");
}
}
/**
* Handles the dragging cursor for experiments groups
*
* @param gl
*/
private void handleGroupSplitExperiments(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
float[] fArDraggedPoint = new float[3];
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
if (glMouseListener.wasMouseReleased()) {
bSplitGroupExp = false;
fArDraggedPoint =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, DraggingPoint.x,
DraggingPoint.y);
float fXPosDrag = fArDraggedPoint[0] - 0.7f;
float fXPosRelease = fArTargetWorldCoordinates[0] - 0.7f;
float fWidth = viewFrustum.getWidth() / 4.0f * fAnimationScale;
int iNrSamples = storageVA.size();
float fWidthSample = fWidth / iNrSamples;
int iFirstSample = (int) Math.floor(fXPosDrag / fWidthSample);
int iLastSample = (int) Math.ceil(fXPosRelease / fWidthSample);
if (storageVA.getGroupList().split(iGroupToSplit, iLastSample, iFirstSample) == false)
System.out.println("Operation not allowed!!");
}
}
private void handleBlockDraggingLevel1(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iselElement;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
float fTextureHeight = viewFrustum.getHeight() - 0.6f;
float fStep = fTextureHeight / iNumberOfElements;
float fYPosMouse = fArTargetWorldCoordinates[1] - 0.4f;
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
if (iSamplesLevel2 % 2 == 0) {
if ((iselElement - (int) Math.floor(iSamplesLevel2 / 2) + 1) >= 0
&& (iselElement + (int) Math.floor(iSamplesLevel2 / 2)) < iNumberOfElements) {
iFirstSampleLevel1 = iselElement - (int) Math.floor(iSamplesLevel2 / 2) + 1;
fPosCursorFirstElementLevel1 = fTextureHeight - (iFirstSampleLevel1 * fStep);
iLastSampleLevel1 = iselElement + (int) Math.floor(iSamplesLevel2 / 2);
fPosCursorLastElementLevel1 = fTextureHeight - ((iLastSampleLevel1 + 1) * fStep);
}
}
else {
if ((iselElement - (int) Math.ceil(iSamplesLevel2 / 2)) >= 0
&& (iselElement + (int) Math.floor(iSamplesLevel2 / 2)) < iNumberOfElements) {
iFirstSampleLevel1 = iselElement - (int) Math.ceil(iSamplesLevel2 / 2);
fPosCursorFirstElementLevel1 = fTextureHeight - (iFirstSampleLevel1 * fStep);
iLastSampleLevel1 = iselElement + (int) Math.floor(iSamplesLevel2 / 2);
fPosCursorLastElementLevel1 = fTextureHeight - ((iLastSampleLevel1 + 1) * fStep);
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
// System.out.println(" iSamplesPerTexture: " + iSamplesPerTexture + " iFirstSampleLevel1: "
// + iFirstSampleLevel1 + " iLastSampleLevel1: " + iLastSampleLevel1);
// System.out.println("fPosCursorFirstElementLevel2: " + fPosCursorFirstElementLevel2
// + " fPosCursorLastElementLevel2: " + fPosCursorLastElementLevel2);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingWholeBlockLevel1 = false;
bDisableCursorDraggingLevel1 = false;
// initPosCursorLevel2();
}
}
/**
* Function used for updating position of block (block of elements rendered in EHM) in case of dragging
*
* @param gl
*/
private void handleBlockDraggingLevel2(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iselElement;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
float fTextureHeight = viewFrustum.getHeight() - 0.6f;
float fStep = fTextureHeight / iSamplesLevel2;
float fYPosMouse = fArTargetWorldCoordinates[1] - 0.4f;
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
if (iSamplesPerHeatmap % 2 == 0) {
if ((iselElement - (int) Math.floor(iSamplesPerHeatmap / 2) + 1) >= 0
&& (iselElement + (int) Math.floor(iSamplesPerHeatmap / 2)) < iSamplesLevel2) {
iFirstSampleLevel2 = iselElement - (int) Math.floor(iSamplesPerHeatmap / 2) + 1;
fPosCursorFirstElementLevel2 = fTextureHeight - (iFirstSampleLevel2 * fStep);
iLastSampleLevel2 = iselElement + (int) Math.floor(iSamplesPerHeatmap / 2);
fPosCursorLastElementLevel2 = fTextureHeight - ((iLastSampleLevel2 + 1) * fStep);
}
}
else {
if ((iselElement - (int) Math.ceil(iSamplesPerHeatmap / 2)) >= 0
&& (iselElement + (int) Math.floor(iSamplesPerHeatmap / 2)) < iSamplesLevel2) {
iFirstSampleLevel2 = iselElement - (int) Math.ceil(iSamplesPerHeatmap / 2);
fPosCursorFirstElementLevel2 = fTextureHeight - (iFirstSampleLevel2 * fStep);
iLastSampleLevel2 = iselElement + (int) Math.floor(iSamplesPerHeatmap / 2);
fPosCursorLastElementLevel2 = fTextureHeight - ((iLastSampleLevel2 + 1) * fStep);
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
if (glMouseListener.wasMouseReleased()) {
bIsDraggingWholeBlockLevel2 = false;
bDisableCursorDraggingLevel2 = false;
}
}
private void handleCursorDraggingLevel1(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iselElement;
int iNrSamples;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
float fTextureHeight = viewFrustum.getHeight() - 0.6f;
float fStep = fTextureHeight / iNumberOfElements;
float fYPosMouse = fArTargetWorldCoordinates[1] - 0.4f;
// cursor for iFirstElement
if (iDraggedCursorLevel1 == 1) {
if (fYPosMouse > fPosCursorLastElementLevel1 && fYPosMouse <= viewFrustum.getHeight() - 0.6f) {
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
iNrSamples = iLastSampleLevel1 - iselElement + 1;
if (iNrSamples >= MIN_SAMPLES_PER_TEXTURE && iNrSamples < MAX_SAMPLES_PER_TEXTURE) {
fPosCursorFirstElementLevel1 = fYPosMouse;
iFirstSampleLevel1 = iselElement;
iSamplesLevel2 = iLastSampleLevel1 - iFirstSampleLevel1 + 1;
// // update Preference store
// generalManager.getPreferenceStore().setValue(
// PreferenceConstants.HM_NUM_SAMPLES_PER_TEXTURE, iSamplesPerTexture);
}
}
}
// cursor for iLastElement
if (iDraggedCursorLevel1 == 2) {
if (fYPosMouse < fPosCursorFirstElementLevel1 && fYPosMouse >= 0.0f) {
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
iNrSamples = iselElement - iFirstSampleLevel1 + 1;
if (iNrSamples >= MIN_SAMPLES_PER_TEXTURE && iNrSamples < MAX_SAMPLES_PER_TEXTURE) {
fPosCursorLastElementLevel1 = fYPosMouse;
iLastSampleLevel1 = iselElement;
iSamplesLevel2 = iLastSampleLevel1 - iFirstSampleLevel1 + 1;
// // update Preference store
// generalManager.getPreferenceStore().setValue(
// PreferenceConstants.HM_NUM_SAMPLES_PER_TEXTURE, iSamplesPerTexture);
}
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
// System.out.println(" iSamplesPerTexture: " + iSamplesPerTexture + " iFirstSampleLevel1: "
// + iFirstSampleLevel1 + " iLastSampleLevel1: " + iLastSampleLevel1);
if (glMouseListener.wasMouseReleased()) {
bIsDraggingActiveLevel1 = false;
bDisableBlockDraggingLevel1 = false;
// initPosCursorLevel2();
}
}
/**
* Function used for updating cursor position in case of dragging
*
* @param gl
*/
private void handleCursorDraggingLevel2(final GL gl) {
Point currentPoint = glMouseListener.getPickedPoint();
float[] fArTargetWorldCoordinates = new float[3];
int iselElement;
int iNrSamples;
fArTargetWorldCoordinates =
GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y);
float fTextureHeight = viewFrustum.getHeight() - 0.6f;
float fStep = fTextureHeight / iSamplesLevel2;
float fYPosMouse = fArTargetWorldCoordinates[1] - 0.4f;
// cursor for iFirstElement
if (iDraggedCursorLevel2 == 1) {
if (fYPosMouse > fPosCursorLastElementLevel2 && fYPosMouse <= viewFrustum.getHeight() - 0.6f) {
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
iNrSamples = iLastSampleLevel2 - iselElement + 1;
if (iNrSamples >= MIN_SAMPLES_PER_HEATMAP && iNrSamples < MAX_SAMPLES_PER_HEATMAP) {
fPosCursorFirstElementLevel2 = fYPosMouse;
iFirstSampleLevel2 = iselElement;
iSamplesPerHeatmap = iLastSampleLevel2 - iFirstSampleLevel2 + 1;
// update Preference store
generalManager.getPreferenceStore().setValue(
PreferenceConstants.HM_NUM_SAMPLES_PER_HEATMAP, iSamplesPerHeatmap);
}
}
}
// cursor for iLastElement
if (iDraggedCursorLevel2 == 2) {
if (fYPosMouse < fPosCursorFirstElementLevel2 && fYPosMouse >= 0.0f) {
iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
iNrSamples = iselElement - iFirstSampleLevel2 + 1;
if (iNrSamples >= MIN_SAMPLES_PER_HEATMAP && iNrSamples < MAX_SAMPLES_PER_HEATMAP) {
fPosCursorLastElementLevel2 = fYPosMouse;
iLastSampleLevel2 = iselElement;
iSamplesPerHeatmap = iLastSampleLevel2 - iFirstSampleLevel2 + 1;
// update Preference store
generalManager.getPreferenceStore().setValue(
PreferenceConstants.HM_NUM_SAMPLES_PER_HEATMAP, iSamplesPerHeatmap);
}
}
}
setDisplayListDirty();
setEmbeddedHeatMapData();
if (glMouseListener.wasMouseReleased()) {
bIsDraggingActiveLevel2 = false;
bDisableBlockDraggingLevel2 = false;
}
}
@Override
protected void handleEvents(EPickingType ePickingType, EPickingMode pickingMode, int iExternalID,
Pick pick) {
if (detailLevel == EDetailLevel.VERY_LOW) {
return;
}
switch (ePickingType) {
// handling the groups/clusters of genes
case HIER_HEAT_MAP_GENES_GROUP:
switch (pickingMode) {
case CLICKED:
contentVA.getGroupList().get(iExternalID).toggleSelectionType();
// System.out.println(contentVA.getGroupList().get(iExternalID).getIdxExample());
// System.out.println(GeneticIDMappingHelper.get().getShortNameFromExpressionIndex(
// contentVA.getGroupList().get(iExternalID).getIdxExample()));
setDisplayListDirty();
break;
case DRAGGED:
// drag&drop for groups
if (bDragDropGeneGroup == false) {
bDragDropGeneGroup = true;
bDragDropExpGroup = false;
iGeneGroupToDrag = iExternalID;
}
// group splitting
// if (bSplitGroupGene == false) {
// bSplitGroupGene = true;
// bSplitGroupExp = false;
// iGroupToSplit = iExternalID;
// DraggingPoint = pick.getPickedPoint();
// }
setDisplayListDirty();
break;
case RIGHT_CLICKED:
boolean bEnableInterchange = false;
boolean bEnableMerge = false;
int iNrSelectedGroups = 0;
IGroupList tempGroupList = contentVA.getGroupList();
for (Group group : tempGroupList) {
if (group.getSelectionType() == ESelectionType.SELECTION)
iNrSelectedGroups++;
}
if (iNrSelectedGroups >= 2) {
bEnableMerge = true;
if (iNrSelectedGroups == 2)
bEnableInterchange = true;
GroupContextMenuItemContainer groupContextMenuItemContainer =
new GroupContextMenuItemContainer();
groupContextMenuItemContainer.setContextMenuFlags(true, bEnableMerge,
bEnableInterchange);
contextMenu.addItemContanier(groupContextMenuItemContainer);
// if (!isRenderedRemote()) {
contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas().getWidth(),
getParentGLCanvas().getHeight());
contextMenu.setMasterGLView(this);
// }
}
break;
case MOUSE_OVER:
// System.out.print("genes group " + iExternalID);
// System.out.print(" number elements in group: ");
// System.out.println(contentVA.getGroupList().get(iExternalID)
// .getNrElements());
// setDisplayListDirty();
break;
}
break;
// handling the groups/clusters of experiments
case HIER_HEAT_MAP_EXPERIMENTS_GROUP:
switch (pickingMode) {
case CLICKED:
storageVA.getGroupList().get(iExternalID).toggleSelectionType();
// System.out.println(storageVA.getGroupList().get(iExternalID).getIdxExample());
// System.out.println(set.get(storageVA.getGroupList().get(iExternalID).getIdxExample())
// .getLabel());
setDisplayListDirty();
break;
case DRAGGED:
// drag&drop for groups
if (bDragDropExpGroup == false) {
bDragDropExpGroup = true;
bDragDropGeneGroup = false;
iExpGroupToDrag = iExternalID;
}
// group splitting
// if (bSplitGroupExp == false) {
// bSplitGroupExp = true;
// bSplitGroupGene = false;
// iGroupToSplit = iExternalID;
// DraggingPoint = pick.getPickedPoint();
// }
setDisplayListDirty();
break;
case RIGHT_CLICKED:
boolean bEnableInterchange = false;
boolean bEnableMerge = false;
int iNrSelectedGroups = 0;
IGroupList tempGroupList = storageVA.getGroupList();
for (Group group : tempGroupList) {
if (group.getSelectionType() == ESelectionType.SELECTION)
iNrSelectedGroups++;
}
if (iNrSelectedGroups >= 2) {
bEnableMerge = true;
if (iNrSelectedGroups == 2)
bEnableInterchange = true;
GroupContextMenuItemContainer groupContextMenuItemContainer =
new GroupContextMenuItemContainer();
groupContextMenuItemContainer.setContextMenuFlags(false, bEnableMerge,
bEnableInterchange);
contextMenu.addItemContanier(groupContextMenuItemContainer);
// if (!isRenderedRemote()) {
contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas().getWidth(),
getParentGLCanvas().getHeight());
contextMenu.setMasterGLView(this);
// }
}
break;
case MOUSE_OVER:
// System.out.print("patients group " + iExternalID);
// System.out.print(" number elements in group: ");
// System.out.println(storageVA.getGroupList().get(iExternalID)
// .getNrElements());
// setDisplayListDirty();
break;
}
break;
// handle click on button for setting EHM in focus
case HIER_HEAT_MAP_INFOCUS_SELECTION:
switch (pickingMode) {
case CLICKED:
bIsHeatmapInFocus = bIsHeatmapInFocus == true ? false : true;
glHeatMapView.setDisplayListDirty();
setDisplayListDirty();
break;
case DRAGGED:
break;
case MOUSE_OVER:
break;
}
break;
// handle click on button for selecting next/previous texture in level 1 and 2
// case HIER_HEAT_MAP_TEXTURE_CURSOR:
// switch (pickingMode) {
// case CLICKED:
//
// if (bSkipLevel1 == false) {
//
// if (iExternalID == 1) {
// iSelectorBar--;
// initPosCursorLevel2();
// setEmbeddedHeatMapData();
// setDisplayListDirty();
// }
// if (iExternalID == 2) {
// iSelectorBar++;
// initPosCursorLevel2();
// setEmbeddedHeatMapData();
// setDisplayListDirty();
// }
//
// setDisplayListDirty();
// }
// break;
//
// case DRAGGED:
// break;
//
// case MOUSE_OVER:
// break;
// }
// break;
// handle dragging cursor for first and last element of block in level 1
case HIER_HEAT_MAP_CURSOR_LEVEL1:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
if (bDisableCursorDraggingLevel1)
return;
bIsDraggingActiveLevel1 = true;
bDisableBlockDraggingLevel1 = true;
iDraggedCursorLevel1 = iExternalID;
setDisplayListDirty();
break;
case MOUSE_OVER:
break;
}
break;
// handle dragging cursor for whole block in level 1
case HIER_HEAT_MAP_BLOCK_CURSOR_LEVEL1:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
if (bDisableBlockDraggingLevel1)
return;
bIsDraggingWholeBlockLevel1 = true;
bDisableCursorDraggingLevel1 = true;
iDraggedCursorLevel1 = iExternalID;
setDisplayListDirty();
break;
case MOUSE_OVER:
break;
}
break;
// handle dragging cursor for first and last element of block in level 2
case HIER_HEAT_MAP_CURSOR_LEVEL2:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
if (bDisableCursorDraggingLevel2)
return;
bIsDraggingActiveLevel2 = true;
bDisableBlockDraggingLevel2 = true;
iDraggedCursorLevel2 = iExternalID;
setDisplayListDirty();
break;
case MOUSE_OVER:
break;
}
break;
// handle dragging cursor for whole block in level 2
case HIER_HEAT_MAP_BLOCK_CURSOR_LEVEL2:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
if (bDisableBlockDraggingLevel2)
return;
bIsDraggingWholeBlockLevel2 = true;
bDisableCursorDraggingLevel2 = true;
iDraggedCursorLevel2 = iExternalID;
setDisplayListDirty();
break;
case MOUSE_OVER:
break;
}
break;
// handle click on level 1 (overview bar)
case HIER_HEAT_MAP_TEXTURE_SELECTION:
switch (pickingMode) {
case CLICKED:
// if (bSkipLevel1 == false) {
// iSelectorBar = iExternalID;
// // if (iSelectorBar == iNrSelBar) {
// // iSelectorBar--;
// // }
// initPosCursorLevel2();
// setEmbeddedHeatMapData();
// setDisplayListDirty();
// }
pickingPointLevel1 = pick.getPickedPoint();
setEmbeddedHeatMapData();
setDisplayListDirty();
break;
case DRAGGED:
break;
case MOUSE_OVER:
break;
}
break;
// handle click on level 2
case HIER_HEAT_MAP_FIELD_SELECTION:
switch (pickingMode) {
case CLICKED:
pickingPointLevel2 = pick.getPickedPoint();
setEmbeddedHeatMapData();
setDisplayListDirty();
break;
case DRAGGED:
break;
case MOUSE_OVER:
break;
}
break;
// handle click on level 3 (EHM)
case HIER_HEAT_MAP_VIEW_SELECTION:
switch (pickingMode) {
case CLICKED:
break;
case DRAGGED:
break;
case MOUSE_OVER:
break;
case RIGHT_CLICKED:
contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas().getWidth(),
getParentGLCanvas().getHeight());
contextMenu.setMasterGLView(this);
break;
}
break;
}
}
@Override
protected ArrayList<SelectedElementRep> createElementRep(EIDType idType, int iStorageIndex) {
return null;
}
@Override
public void renderContext(boolean bRenderOnlyContext) {
throw new IllegalStateException("Rendering only context not supported for the hierachical heat map");
}
@Override
public void clearAllSelections() {
contentSelectionManager.clearSelections();
storageSelectionManager.clearSelections();
iPickedSampleLevel1 = 0;
initPosCursorLevel1();
bRedrawTextures = true;
setDisplayListDirty();
setEmbeddedHeatMapData();
glHeatMapView.setDisplayListDirty();
glDendrogramView.setDisplayListDirty();
// group/cluster selections
if (storageVA.getGroupList() != null) {
IGroupList groupList = storageVA.getGroupList();
for (Group group : groupList)
group.setSelectionType(ESelectionType.NORMAL);
}
if (contentVA.getGroupList() != null) {
IGroupList groupList = contentVA.getGroupList();
for (Group group : groupList)
group.setSelectionType(ESelectionType.NORMAL);
}
}
@Override
public void changeOrientation(boolean defaultOrientation) {
renderHorizontally(defaultOrientation);
}
@Override
public boolean isInDefaultOrientation() {
return bRenderStorageHorizontally;
}
public void changeFocus(boolean bInFocus) {
bIsHeatmapInFocus = bIsHeatmapInFocus == true ? false : true;
setDisplayListDirty();
}
@SuppressWarnings("unused")
private void activateGroupHandling() {
if (contentVA.getGroupList() == null) {
GroupList groupList = new GroupList(0);
Group group = new Group(contentVA.size(), false, 0, ESelectionType.NORMAL);
groupList.append(group);
contentVA.setGroupList(groupList);
}
if (storageVA.getGroupList() == null) {
GroupList groupList = new GroupList(0);
Group group = new Group(storageVA.size(), false, 0, ESelectionType.NORMAL);
groupList.append(group);
storageVA.setGroupList(groupList);
}
setDisplayListDirty();
}
public boolean isInFocus() {
return bIsHeatmapInFocus;
}
private void handleWiiInput() {
float fHeadPositionX = generalManager.getWiiRemote().getCurrentSmoothHeadPosition()[0];
if (fHeadPositionX < -1.2f) {
bIsHeatmapInFocus = false;
}
else {
bIsHeatmapInFocus = true;
}
setDisplayListDirty();
}
private void handleTrackInput(final GL gl) {
// // TODO: very performance intensive - better solution needed (only in reshape)!
// getParentGLCanvas().getParentComposite().getDisplay().asyncExec(new Runnable() {
// @Override
// public void run() {
// upperLeftScreenPos = getParentGLCanvas().getParentComposite().toDisplay(1, 1);
// }
// });
//
// Rectangle screenRect = getParentGLCanvas().getBounds();
// float[] fArTrackPos = generalManager.getTrackDataProvider().getEyeTrackData();
//
// fArTrackPos[0] -= upperLeftScreenPos.x;
// fArTrackPos[1] -= upperLeftScreenPos.y;
//
// GLHelperFunctions.drawPointAt(gl, new Vec3f(fArTrackPos[0] / screenRect.width * 8f,
// (1f - fArTrackPos[1] / screenRect.height) * 8f * fAspectRatio, 0.01f));
//
// float fSwitchBorder = 200;
//
// if (!bIsHeatmapInFocus)
// fSwitchBorder = 450;
//
// if (fArTrackPos[0] < fSwitchBorder) {
// bIsHeatmapInFocus = false;
// }
// else {
// bIsHeatmapInFocus = true;
// }
//
// // Manipulate selected overview chunk (level 1)
// if (fArTrackPos[0] < 50) {
// int iNrPixelsPerSelectionBar = (int) (screenRect.getHeight() / iNrSelBar);
// iSelectorBar = (int) ((fArTrackPos[1] + 17) / iNrPixelsPerSelectionBar * 1.1f); // TODO: play with
// // these
// // correction
// // factors
//
// if (iSelectorBar <= 0)
// iSelectorBar = 1;
// else if (iSelectorBar > iNrSelBar)
// iSelectorBar = iNrSelBar;
// }
//
// // Manipulate selected level 2 chunk
// if (!bIsHeatmapInFocus && fArTrackPos[0] > 50 && fArTrackPos[0] < 450) {
// float fTextureHeight = viewFrustum.getHeight() - 0.6f;
// float fStep = fTextureHeight / (iAlNumberSamples.get(iSelectorBar - 1));// * 2);
// float fYPosMouse =
// ((1f - fArTrackPos[1] / (float) screenRect.getHeight())) * 8f * fAspectRatio - 0.4f;
//
// int iselElement = (int) Math.floor((fTextureHeight - fYPosMouse) / fStep);
// if (iSamplesPerHeatmap % 2 == 0) {
// if ((iselElement - (int) Math.floor(iSamplesPerHeatmap / 2) + 1) >= 0
// && (iselElement + (int) Math.floor(iSamplesPerHeatmap / 2)) < iAlNumberSamples
// .get(iSelectorBar - 1)) {
// iFirstSampleLevel2 = iselElement - (int) Math.floor(iSamplesPerHeatmap / 2) + 1;
// fPosCursorFirstElementLevel3 = fTextureHeight - (iFirstSampleLevel2 * fStep);
// iLastSampleLevel2 = iselElement + (int) Math.floor(iSamplesPerHeatmap / 2);
// fPosCursorLastElementLevel3 = fTextureHeight - ((iLastSampleLevel2 + 1) * fStep);
// }
// }
// else {
// if ((iselElement - (int) Math.ceil(iSamplesPerHeatmap / 2)) >= 0
// && (iselElement + (int) Math.floor(iSamplesPerHeatmap / 2)) < iAlNumberSamples
// .get(iSelectorBar - 1)) {
// iFirstSampleLevel2 = iselElement - (int) Math.ceil(iSamplesPerHeatmap / 2);
// fPosCursorFirstElementLevel3 = fTextureHeight - (iFirstSampleLevel2 * fStep);
// iLastSampleLevel2 = iselElement + (int) Math.floor(iSamplesPerHeatmap / 2);
// fPosCursorLastElementLevel3 = fTextureHeight - ((iLastSampleLevel2 + 1) * fStep);
// }
// }
// }
//
// setDisplayListDirty();
}
@Override
public void initData() {
super.initData();
// FIXME
// contentVA.setGroupList(null);
// storageVA.setGroupList(null);
initHierarchy();
initPosCursorLevel1();
if (bSkipLevel2 == false) {
calculateTextures();
initPosCursorLevel2();
}
glHeatMapView.setSet(set);
glHeatMapView.setContentVAType(EVAType.CONTENT_EMBEDDED_HM);
glHeatMapView.initData();
glDendrogramView.setSet(set);
glDendrogramView.setContentVAType(EVAType.CONTENT_EMBEDDED_HM);
glDendrogramView.initData();
if (bSkipLevel2 == false)
bRedrawTextures = true;
}
@Override
public ASerializedView getSerializableRepresentation() {
SerializedHierarchicalHeatMapView serializedForm = new SerializedHierarchicalHeatMapView();
serializedForm.setViewID(this.getID());
serializedForm.setViewGUIID(getViewGUIID());
return serializedForm;
}
@Override
public void handleInterchangeGroups(boolean bGeneGroup) {
IVirtualArray va;
if (bGeneGroup)
va = contentVA;
else
va = storageVA;
IGroupList groupList = va.getGroupList();
ArrayList<Integer> selGroups = new ArrayList<Integer>();
if (groupList == null) {
System.out.println("No group assignment available!");
return;
}
for (Group iter : groupList) {
if (iter.getSelectionType() == ESelectionType.SELECTION)
selGroups.add(groupList.indexOf(iter));
}
if (selGroups.size() != 2) {
System.out.println("Number of selected elements has to be 2!!!");
return;
}
// interchange
if (groupList.interchange(va, selGroups.get(0), selGroups.get(1)) == false) {
System.out.println("Problem during interchange!!!");
return;
}
bRedrawTextures = true;
setDisplayListDirty();
}
@Override
public void handleMergeGroups(boolean bGeneGroup) {
IVirtualArray va;
if (bGeneGroup)
va = contentVA;
else
va = storageVA;
IGroupList groupList = va.getGroupList();
ArrayList<Integer> selGroups = new ArrayList<Integer>();
if (groupList == null) {
System.out.println("No group assignment available!");
return;
}
for (Group iter : groupList) {
if (iter.getSelectionType() == ESelectionType.SELECTION)
selGroups.add(groupList.indexOf(iter));
}
// merge
while (selGroups.size() >= 2) {
int iLastSelected = selGroups.size() - 1;
// merge last and the one before last
if (groupList.merge(va, selGroups.get(iLastSelected - 1), selGroups.get(iLastSelected)) == false) {
System.out.println("Problem during merge!!!");
return;
}
selGroups.remove(iLastSelected);
}
bRedrawTextures = true;
setDisplayListDirty();
}
@Override
public void registerEventListeners() {
super.registerEventListeners();
groupMergingActionListener = new GroupMergingActionListener();
groupMergingActionListener.setHandler(this);
eventPublisher.addListener(MergeGroupsEvent.class, groupMergingActionListener);
groupInterChangingActionListener = new GroupInterChangingActionListener();
groupInterChangingActionListener.setHandler(this);
eventPublisher.addListener(InterchangeGroupsEvent.class, groupInterChangingActionListener);
updateViewListener = new UpdateViewListener();
updateViewListener.setHandler(this);
eventPublisher.addListener(UpdateViewEvent.class, updateViewListener);
}
@Override
public void unregisterEventListeners() {
super.unregisterEventListeners();
if (groupMergingActionListener != null) {
eventPublisher.removeListener(groupMergingActionListener);
groupMergingActionListener = null;
}
if (groupInterChangingActionListener != null) {
eventPublisher.removeListener(groupInterChangingActionListener);
groupInterChangingActionListener = null;
}
if (updateViewListener != null) {
eventPublisher.removeListener(updateViewListener);
updateViewListener = null;
}
}
@Override
public void handleUpdateView() {
bRedrawTextures = true;
setDisplayListDirty();
}
public void handleArrowDownAltPressed() {
if (iLastSampleLevel2 < iSamplesLevel2 - 1) {
iLastSampleLevel2++;
iFirstSampleLevel2++;
setEmbeddedHeatMapData();
setDisplayListDirty();
}
}
public void handleArrowUpAltPressed() {
if (iFirstSampleLevel2 > 0) {
iFirstSampleLevel2--;
iLastSampleLevel2--;
setEmbeddedHeatMapData();
setDisplayListDirty();
}
}
public void handleArrowDownCtrlPressed() {
if (iLastSampleLevel1 < iNumberOfElements - 1) {
iFirstSampleLevel1++;
iLastSampleLevel1++;
setDisplayListDirty();
}
}
public void handleArrowUpCtrlPressed() {
if (iFirstSampleLevel1 > 0) {
iFirstSampleLevel1--;
iLastSampleLevel1--;
setDisplayListDirty();
}
}
public void handleArrowUpPressed() {
// glHeatMapView.upDownSelect(true);
}
public void handleArrowDownPressed() {
// glHeatMapView.upDownSelect(false);
}
public void handleArrowLeftShiftPressed() {
if (bIsHeatmapInFocus == false) {
bIsHeatmapInFocus = true;
setDisplayListDirty();
}
}
public void handleArrowRightShiftPressed() {
if (bIsHeatmapInFocus) {
bIsHeatmapInFocus = false;
setDisplayListDirty();
}
}
/**
* Set the number of samples which are shown in one texture
*
* @param iNumberOfSamplesPerTexture
* the number
*/
public final void setNumberOfSamplesPerTexture(int iNumberOfSamplesPerTexture) {
this.iNumberOfSamplesPerTexture = iNumberOfSamplesPerTexture;
}
/**
* Set the number of samples which are shown in one heat map
*
* @param iNumberOfSamplesPerHeatmap
* the number
*/
public final void setNumberOfSamplesPerHeatmap(int iNumberOfSamplesPerHeatmap) {
this.iNumberOfSamplesPerHeatmap = iNumberOfSamplesPerHeatmap;
}
}
| Fixed a bug with picking in level 1 of HHM.
Removed visualization of texture borders in level 1 of HHM. This feature is not needful with the new approach.
Modified behavior of key events in HHM.
git-svn-id: 149221363d454b9399d51e0b24a857a738336ca8@2287 1f7349ae-fd9f-0d40-aeb8-9798e6c0fce3
| org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/storagebased/GLHierarchicalHeatMap.java | Fixed a bug with picking in level 1 of HHM. Removed visualization of texture borders in level 1 of HHM. This feature is not needful with the new approach. Modified behavior of key events in HHM. | <ide><path>rg.caleydo.core/src/org/caleydo/core/view/opengl/canvas/storagebased/GLHierarchicalHeatMap.java
<ide>
<ide> float fHeightElem = fHeight / iNumberOfElements;
<ide>
<del> int iStartElem = 0;
<del> int iLastElem = 0;
<del>
<del> boolean colorToggle = true;
<del>
<del> gl.glLineWidth(2f);
<del>
<ide> if (bIsDraggingActiveLevel1 == false && bIsDraggingWholeBlockLevel1 == false) {
<ide> fPosCursorFirstElementLevel1 = viewFrustum.getHeight() - iFirstSampleLevel1 * fHeightElem;
<ide> fPosCursorLastElementLevel1 = viewFrustum.getHeight() - (iLastSampleLevel1 + 1) * fHeightElem;
<ide> }
<ide>
<del> for (int currentGroup = 0; currentGroup < iNrTextures; currentGroup++) {
<del>
<del> iStartElem = iLastElem;
<del> iLastElem += iAlNumberSamples.get(currentGroup);
<del>
<del> if (colorToggle)
<del> gl.glColor4f(0f, 0f, 0f, 1f);
<del> else
<del> gl.glColor4f(1f, 1f, 1f, 1f);
<del>
<del> colorToggle = (colorToggle == true) ? false : true;
<del>
<del> // TODO: find a better way to render cluster assignments (--> +0.01f is not a fine way)
<del> gl.glBegin(GL.GL_LINE_LOOP);
<del> gl.glVertex3f(0, fHeight - fHeightElem * iStartElem, 0);
<del> gl.glVertex3f(fFieldWith, fHeight - fHeightElem * iStartElem, 0);
<del> gl.glVertex3f(fFieldWith, (fHeight - fHeightElem * iLastElem) + 0.01f, 0);
<del> gl.glVertex3f(0, (fHeight - fHeightElem * iLastElem) + 0.01f, 0);
<del> gl.glEnd();
<del> }
<add> // int iStartElem = 0;
<add> // int iLastElem = 0;
<add> //
<add> // boolean colorToggle = true;
<add> //
<add> // gl.glLineWidth(2f);
<add> // for (int currentTextureIdx = 0; currentTextureIdx < iNrTextures; currentTextureIdx++) {
<add> //
<add> // iStartElem = iLastElem;
<add> // iLastElem += iAlNumberSamples.get(currentTextureIdx);
<add> //
<add> // if (colorToggle)
<add> // gl.glColor4f(0f, 0f, 0f, 1f);
<add> // else
<add> // gl.glColor4f(1f, 1f, 1f, 1f);
<add> //
<add> // colorToggle = (colorToggle == true) ? false : true;
<add> //
<add> // gl.glBegin(GL.GL_LINE_LOOP);
<add> // gl.glVertex3f(0, fHeight - fHeightElem * iStartElem, 0);
<add> // gl.glVertex3f(fFieldWith, fHeight - fHeightElem * iStartElem, 0);
<add> // // Different handling for last texture. To avoid problems with visualization.
<add> // if (currentTextureIdx == iNrTextures - 1) {
<add> // gl.glVertex3f(fFieldWith, (fHeight - fHeightElem * iLastElem), 0);
<add> // gl.glVertex3f(0, (fHeight - fHeightElem * iLastElem), 0);
<add> // }
<add> // else {
<add> // gl.glVertex3f(fFieldWith, (fHeight - fHeightElem * iLastElem) + 0.01f, 0);
<add> // gl.glVertex3f(0, (fHeight - fHeightElem * iLastElem) + 0.01f, 0);
<add> // }
<add> // gl.glEnd();
<add> // }
<ide>
<ide> // selected domain level 1
<ide> startpoint1 = new Vec3f(fFieldWith, fPosCursorFirstElementLevel1, 0);
<ide>
<ide> int iNumberSample = iNumberOfElements;
<ide> float fOffsety;
<del> float fHeightSample = (viewFrustum.getHeight() - 0.4f) / iNumberSample;
<add> float fHeightSample = viewFrustum.getHeight() / iNumberSample;
<ide> float[] fArPickingCoords = new float[3];
<ide>
<ide> if (pickingPointLevel1 != null) {
<ide> iFirstSampleLevel2++;
<ide> setEmbeddedHeatMapData();
<ide> setDisplayListDirty();
<add> glHeatMapView.upDownSelect(false);
<ide> }
<ide> }
<ide>
<ide> iLastSampleLevel2--;
<ide> setEmbeddedHeatMapData();
<ide> setDisplayListDirty();
<add> glHeatMapView.upDownSelect(true);
<ide> }
<ide> }
<ide>
<ide> iFirstSampleLevel1++;
<ide> iLastSampleLevel1++;
<ide> setDisplayListDirty();
<add> glHeatMapView.upDownSelect(false);
<ide> }
<ide> }
<ide>
<ide> iFirstSampleLevel1--;
<ide> iLastSampleLevel1--;
<ide> setDisplayListDirty();
<add> glHeatMapView.upDownSelect(true);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 7db99f8277f4bb1936ddbe1e6f453fd242cfe7c6 | 0 | s4u/pgpverify-maven-plugin | /*
* Copyright 2016 Slawomir Jaranowski
*
* 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.github.s4u.plugins;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
/**
* Implementation of PGPKeysServerClient for HTTPS protocol.
*/
public class PGPKeysServerClientHttps extends PGPKeysServerClient {
private final SSLSocketFactory sslSocketFactory;
protected PGPKeysServerClientHttps(URI uri)
throws URISyntaxException, CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
super(uri);
if ("hkps.pool.sks-keyservers.net".equalsIgnoreCase(uri.getHost())) {
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
final Certificate ca = cf.generateCertificate(getClass().getClassLoader().getResourceAsStream("sks-keyservers.netCA.pem"));
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
final SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
this.sslSocketFactory = context.getSocketFactory();
} else {
this.sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
}
}
@Override
protected URI prepareKeyServerURI(URI keyserver) throws URISyntaxException {
return new URI("https", keyserver.getUserInfo(), keyserver.getHost(), keyserver.getPort(), null, null, null);
}
@Override
protected InputStream getInputStreamForKey(URL keyURL) throws IOException {
// standard support by Java - can be extended eg. to support custom CA certs
final HttpsURLConnection keyServerUrlConnection = (HttpsURLConnection) keyURL.openConnection();
keyServerUrlConnection.setSSLSocketFactory(sslSocketFactory);
return keyServerUrlConnection.getInputStream();
}
}
| src/main/java/com/github/s4u/plugins/PGPKeysServerClientHttps.java | /*
* Copyright 2016 Slawomir Jaranowski
*
* 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.github.s4u.plugins;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
/**
* Implementation of PGPKeysServerClient for HTTPS protocol.
*/
public class PGPKeysServerClientHttps extends PGPKeysServerClient {
private final SSLSocketFactory sslSocketFactory;
protected PGPKeysServerClientHttps(URI uri)
throws URISyntaxException, CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
super(uri);
if ("hkps://hkps.pool.sks-keyservers.net".equalsIgnoreCase(uri.toString())) {
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
final Certificate ca = cf.generateCertificate(getClass().getClassLoader().getResourceAsStream("sks-keyservers.netCA.pem"));
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
final SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
this.sslSocketFactory = context.getSocketFactory();
} else {
this.sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
}
}
@Override
protected URI prepareKeyServerURI(URI keyserver) throws URISyntaxException {
return new URI("https", keyserver.getUserInfo(), keyserver.getHost(), keyserver.getPort(), null, null, null);
}
@Override
protected InputStream getInputStreamForKey(URL keyURL) throws IOException {
// standard support by Java - can be extended eg. to support custom CA certs
final HttpsURLConnection keyServerUrlConnection = (HttpsURLConnection) keyURL.openConnection();
keyServerUrlConnection.setSSLSocketFactory(sslSocketFactory);
return keyServerUrlConnection.getInputStream();
}
}
| Matching on host instead of entire URI
| src/main/java/com/github/s4u/plugins/PGPKeysServerClientHttps.java | Matching on host instead of entire URI | <ide><path>rc/main/java/com/github/s4u/plugins/PGPKeysServerClientHttps.java
<ide> protected PGPKeysServerClientHttps(URI uri)
<ide> throws URISyntaxException, CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
<ide> super(uri);
<del> if ("hkps://hkps.pool.sks-keyservers.net".equalsIgnoreCase(uri.toString())) {
<add> if ("hkps.pool.sks-keyservers.net".equalsIgnoreCase(uri.getHost())) {
<ide> final CertificateFactory cf = CertificateFactory.getInstance("X.509");
<ide> final Certificate ca = cf.generateCertificate(getClass().getClassLoader().getResourceAsStream("sks-keyservers.netCA.pem"));
<ide> final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); |
|
Java | mit | c8a280e45fd0012e254ebb7a8a8df17d1a62d735 | 0 | openforis/collect,openforis/collect,openforis/collect,openforis/collect | /**
*
*/
package org.openforis.collect.remoting.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.openforis.collect.manager.RecordManager;
import org.openforis.collect.manager.RecordPromoteException;
import org.openforis.collect.manager.SessionManager;
import org.openforis.collect.metamodel.proxy.CodeListItemProxy;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.model.FieldSymbol;
import org.openforis.collect.model.RecordSummarySortField;
import org.openforis.collect.model.User;
import org.openforis.collect.model.proxy.RecordProxy;
import org.openforis.collect.persistence.RecordPersistenceException;
import org.openforis.collect.remoting.service.UpdateRequestOperation.Method;
import org.openforis.collect.web.session.SessionState;
import org.openforis.collect.web.session.SessionState.RecordState;
import org.openforis.idm.metamodel.AttributeDefinition;
import org.openforis.idm.metamodel.BooleanAttributeDefinition;
import org.openforis.idm.metamodel.CodeAttributeDefinition;
import org.openforis.idm.metamodel.CodeListItem;
import org.openforis.idm.metamodel.CoordinateAttributeDefinition;
import org.openforis.idm.metamodel.DateAttributeDefinition;
import org.openforis.idm.metamodel.EntityDefinition;
import org.openforis.idm.metamodel.ModelVersion;
import org.openforis.idm.metamodel.NodeDefinition;
import org.openforis.idm.metamodel.NumberAttributeDefinition;
import org.openforis.idm.metamodel.NumberAttributeDefinition.Type;
import org.openforis.idm.metamodel.RangeAttributeDefinition;
import org.openforis.idm.metamodel.Schema;
import org.openforis.idm.metamodel.TimeAttributeDefinition;
import org.openforis.idm.metamodel.validation.ValidationResults;
import org.openforis.idm.model.Attribute;
import org.openforis.idm.model.Code;
import org.openforis.idm.model.CodeAttribute;
import org.openforis.idm.model.Entity;
import org.openforis.idm.model.Field;
import org.openforis.idm.model.IntegerRange;
import org.openforis.idm.model.Node;
import org.openforis.idm.model.NodePointer;
import org.openforis.idm.model.NumericRange;
import org.openforis.idm.model.RealRange;
import org.openforis.idm.model.Record;
import org.openforis.idm.model.expression.ExpressionFactory;
import org.openforis.idm.model.expression.ModelPathExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* @author M. Togna
* @author S. Ricci
*
*/
public class DataService {
@Autowired
private SessionManager sessionManager;
@Autowired
private RecordManager recordManager;
@Transactional
public RecordProxy loadRecord(int id, int step) throws RecordPersistenceException {
CollectSurvey survey = getActiveSurvey();
User user = getUserInSession();
CollectRecord record = recordManager.checkout(survey, user, id, step);
//record.updateNodeStates();
Entity rootEntity = record.getRootEntity();
recordManager.addEmptyNodes(rootEntity);
SessionState sessionState = sessionManager.getSessionState();
sessionState.setActiveRecord(record);
sessionState.setActiveRecordState(RecordState.SAVED);
return new RecordProxy(record);
}
/**
*
* @param rootEntityName
* @param offset
* @param toIndex
* @param orderByFieldName
* @param filter
*
* @return map with "count" and "records" items
*/
@Transactional
public Map<String, Object> getRecordSummaries(String rootEntityName, int offset, int maxNumberOfRows, List<RecordSummarySortField> sortFields, String filter) {
Map<String, Object> result = new HashMap<String, Object>();
SessionState sessionState = sessionManager.getSessionState();
CollectSurvey activeSurvey = sessionState.getActiveSurvey();
Schema schema = activeSurvey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntityName);
String rootEntityDefinitionName = rootEntityDefinition.getName();
int count = recordManager.getCountRecords(activeSurvey, rootEntityDefinitionName);
List<CollectRecord> summaries = recordManager.getSummaries(activeSurvey, rootEntityDefinitionName, offset, maxNumberOfRows, sortFields, filter);
List<RecordProxy> proxies = new ArrayList<RecordProxy>();
for (CollectRecord summary : summaries) {
proxies.add(new RecordProxy(summary));
}
result.put("count", count);
result.put("records", proxies);
return result;
}
@Transactional
public RecordProxy createRecord(String rootEntityName, String versionName) throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
CollectSurvey activeSurvey = sessionState.getActiveSurvey();
ModelVersion version = activeSurvey.getVersion(versionName);
Schema schema = activeSurvey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntityName);
CollectRecord record = recordManager.create(activeSurvey, rootEntityDefinition, user, version.getName());
Entity rootEntity = record.getRootEntity();
recordManager.addEmptyNodes(rootEntity);
sessionState.setActiveRecord((CollectRecord) record);
sessionState.setActiveRecordState(RecordState.NEW);
RecordProxy recordProxy = new RecordProxy(record);
return recordProxy;
}
@Transactional
public void deleteRecord(int id) throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
recordManager.delete(id, user);
sessionManager.clearActiveRecord();
}
@Transactional
public void saveActiveRecord() throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
User user = sessionState.getUser();
record.setModifiedDate(new Date());
record.setModifiedBy(user);
recordManager.save(record);
sessionState.setActiveRecordState(RecordState.SAVED);
}
@Transactional
public void deleteActiveRecord() throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
Record record = sessionState.getActiveRecord();
recordManager.delete(record.getId(), user);
sessionManager.clearActiveRecord();
}
public List<UpdateResponse> updateActiveRecord(UpdateRequest request) {
List<UpdateRequestOperation> operations = request.getOperations();
List<UpdateResponse> updateResponses = new ArrayList<UpdateResponse>();
for (UpdateRequestOperation operation : operations) {
Collection<UpdateResponse> responses = processUpdateRequestOperation(operation);
updateResponses.addAll(responses);
}
return updateResponses;
}
@SuppressWarnings("unchecked")
private Collection<UpdateResponse> processUpdateRequestOperation(UpdateRequestOperation operation) {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
Integer parentEntityId = operation.getParentEntityId();
Entity parentEntity = (Entity) record.getNodeByInternalId(parentEntityId);
Integer nodeId = operation.getNodeId();
Integer fieldIndex = operation.getFieldIndex();
String nodeName = operation.getNodeName();
Node<?> node = null;
if(nodeId != null) {
node = record.getNodeByInternalId(nodeId);
}
NodeDefinition nodeDef = ((EntityDefinition) parentEntity.getDefinition()).getChildDefinition(nodeName);
String requestValue = operation.getValue();
String remarks = operation.getRemarks();
FieldSymbol symbol = operation.getSymbol();
Method method = operation.getMethod();
Map<Integer, UpdateResponse> responseMap = new HashMap<Integer, UpdateResponse>();
Set<NodePointer> relReqDependencies = null;
Set<Attribute<?,?>> checkDependencies = null;
List<NodePointer> cardinalityNodePointers = null;
Attribute<? extends AttributeDefinition, ?> attribute = null;
switch (method) {
case CONFIRM_ERROR:
attribute = (Attribute<AttributeDefinition, ?>) node;
record.setErrorConfirmed(attribute, true);
//checkDependencies = recordManager.clearValidationResults(attribute);
checkDependencies = new HashSet<Attribute<?,?>>();
attribute.clearValidationResults();
checkDependencies.add(attribute);
UpdateResponse response = getUpdateResponse(responseMap, attribute.getInternalId());
break;
case APPROVE_MISSING:
record.setMissingApproved(parentEntity, nodeName, true);
cardinalityNodePointers = getCardinalityNodePointers(node);
break;
case UPDATE_REMARKS:
attribute = (Attribute<AttributeDefinition, ?>) node;
Field<?> fld = attribute.getField(fieldIndex);
fld.setRemarks(remarks);
getUpdateResponse(responseMap, nodeId);
break;
case ADD :
Node<?> createdNode = addNode(parentEntity, nodeDef, requestValue, symbol, remarks);
response = getUpdateResponse(responseMap, createdNode.getInternalId());
response.setCreatedNode(createdNode);
relReqDependencies = recordManager. clearRelevanceRequiredStates(createdNode);
if(createdNode instanceof Attribute){
attribute = (Attribute<? extends AttributeDefinition, ?>) createdNode;
checkDependencies = recordManager.clearValidationResults(attribute);
checkDependencies.add(attribute);
}
relReqDependencies.add(new NodePointer(createdNode.getParent(), createdNode.getName()));
cardinalityNodePointers = getCardinalityNodePointers(createdNode);
break;
case UPDATE:
attribute = (Attribute<AttributeDefinition, ?>) node;
record.setErrorConfirmed(attribute, false);
record.setMissingApproved(parentEntity, node.getName(), false);
cardinalityNodePointers = getCardinalityNodePointers(attribute);
response = getUpdateResponse(responseMap, attribute.getInternalId());
Map<Integer, Object> updatedFieldValues = new HashMap<Integer, Object>();
if (fieldIndex < 0) {
Object value = null;
if (requestValue != null) {
value = parseCompositeAttributeValue(parentEntity, attribute.getDefinition(), requestValue);
}
recordManager.setAttributeValue(attribute, value, remarks);
for (int idx = 0; idx < attribute.getFieldCount(); idx++) {
Field<?> field = attribute.getField(idx);
Object fieldValue = field.getValue();
updatedFieldValues.put(idx, fieldValue);
recordManager.setFieldValue(attribute, fieldValue, remarks, symbol, idx);
}
} else {
Object value = parseFieldValue(parentEntity, attribute.getDefinition(), requestValue, fieldIndex);
recordManager.setFieldValue(attribute, value, remarks, symbol, fieldIndex);
Field<?> field = attribute.getField(fieldIndex);
updatedFieldValues.put(fieldIndex, field.getValue());
}
response.setUpdatedFieldValues(updatedFieldValues);
relReqDependencies = recordManager.clearRelevanceRequiredStates(attribute);
checkDependencies = recordManager.clearValidationResults(attribute);
relReqDependencies.add(new NodePointer(attribute.getParent(), attribute.getName()));
checkDependencies.add(attribute);
break;
case DELETE:
relReqDependencies = new HashSet<NodePointer>();
checkDependencies = new HashSet<Attribute<?,?>>();
cardinalityNodePointers = getCardinalityNodePointers(node);
deleteNode(node, relReqDependencies, checkDependencies, responseMap);
break;
}
prepareUpdateResponse(responseMap, relReqDependencies, checkDependencies, cardinalityNodePointers);
return responseMap.values();
}
private List<NodePointer> getCardinalityNodePointers(Node<?> node){
List<NodePointer> nodePointers = new ArrayList<NodePointer>();
Entity parent = node.getParent();
String childName = node.getName();
while(parent != null){
NodePointer nodePointer = new NodePointer(parent, childName );
nodePointers.add(nodePointer);
childName = parent.getName();
parent = parent.getParent();
}
return nodePointers;
}
private void deleteNode(Node<?> node,Set<NodePointer> relevanceRequiredDependencies, Set<Attribute<?,?>> checkDependencies, Map<Integer, UpdateResponse> responseMap){
Stack<Node<?>> dependenciesStack = new Stack<Node<?>>();
Stack<Node<?>> nodesToRemove = new Stack<Node<?>>();
dependenciesStack.push(node);
Set<NodePointer> relevantDependencies = new HashSet<NodePointer>();
Set<NodePointer> requiredDependencies = new HashSet<NodePointer>();
while(!dependenciesStack.isEmpty()){
Node<?> n = dependenciesStack.pop();
nodesToRemove.push(n);
relevantDependencies.addAll(n.getRelevantDependencies());
requiredDependencies.addAll(n.getRequiredDependencies());
if(n instanceof Entity){
Entity entity = (Entity) n;
List<Node<? extends NodeDefinition>> children = entity.getChildren();
for (Node<? extends NodeDefinition> child : children) {
dependenciesStack.push(child);
}
} else {
Attribute<?,?> attr = (Attribute<?, ?>) n;
checkDependencies.addAll(attr.getCheckDependencies());
}
}
while(!nodesToRemove.isEmpty()){
Node<?> n = nodesToRemove.pop();
recordManager.deleteNode(n);
UpdateResponse resp = getUpdateResponse(responseMap, node.getInternalId());
resp.setDeletedNodeId(node.getInternalId());
}
//clear dependencies
recordManager.clearRelevantDependencies(relevantDependencies);
requiredDependencies.addAll(relevantDependencies);
recordManager.clearRequiredDependencies(requiredDependencies);
recordManager.clearValidationResults(checkDependencies);
relevanceRequiredDependencies.addAll(requiredDependencies);
}
private void prepareUpdateResponse(Map<Integer, UpdateResponse> responseMap, Set<NodePointer> relevanceRequiredDependencies, Set<Attribute<?, ?>> validtionResultsDependencies, List<NodePointer> cardinalityNodePointers) {
if (cardinalityNodePointers != null) {
for (NodePointer nodePointer : cardinalityNodePointers) {
// entity could be root definition
Entity parent = nodePointer.getEntity();
if (parent != null && !parent.isDetached()) {
String childName = nodePointer.getChildName();
UpdateResponse response = getUpdateResponse(responseMap, parent.getInternalId());
response.setRelevant(childName, parent.isRelevant(childName));
response.setRequired(childName, parent.isRequired(childName));
response.setMinCountValid(childName, parent.validateMinCount(childName));
response.setMaxCountValid(childName, parent.validateMaxCount(childName));
}
}
}
if (relevanceRequiredDependencies != null) {
for (NodePointer nodePointer : relevanceRequiredDependencies) {
Entity entity = nodePointer.getEntity();
if (!entity.isDetached()) {
String childName = nodePointer.getChildName();
UpdateResponse response = getUpdateResponse(responseMap, entity.getInternalId());
response.setRelevant(childName, entity.isRelevant(childName));
response.setRequired(childName, entity.isRequired(childName));
response.setMinCountValid(childName, entity.validateMinCount(childName));
response.setMaxCountValid(childName, entity.validateMaxCount(childName));
}
}
}
if (validtionResultsDependencies != null) {
for (Attribute<?, ?> checkDepAttr : validtionResultsDependencies) {
if (!checkDepAttr.isDetached()) {
checkDepAttr.clearValidationResults();
ValidationResults results = checkDepAttr.validateValue();
UpdateResponse response = getUpdateResponse(responseMap, checkDepAttr.getInternalId());
response.setAttributeValidationResults(results);
}
}
}
}
private UpdateResponse getUpdateResponse(Map<Integer, UpdateResponse> responseMap, int nodeId){
UpdateResponse response = responseMap.get(nodeId);
if(response == null){
response = new UpdateResponse(nodeId);
responseMap.put(nodeId, response);
}
return response;
}
@SuppressWarnings("unchecked")
private Node<?> addNode(Entity parentEntity, NodeDefinition nodeDef, String requestValue, FieldSymbol symbol, String remarks) {
if(nodeDef instanceof AttributeDefinition) {
AttributeDefinition def = (AttributeDefinition) nodeDef;
Attribute<?, ?> attribute = (Attribute<?, ?>) def.createNode();
parentEntity.add(attribute);
if(StringUtils.isNotBlank(requestValue)) {
Object value = parseCompositeAttributeValue(parentEntity, (AttributeDefinition) nodeDef, requestValue);
((Attribute<?, Object>) attribute).setValue(value);
}
if(symbol != null || remarks != null) {
Character symbolChar = null;
if(symbol != null) {
symbolChar = symbol.getCode();
}
Field<?> firstField = attribute.getField(0);
firstField.setSymbol(symbolChar);
firstField.setRemarks(remarks);
}
return attribute;
} else {
Entity e = recordManager.addEntity(parentEntity, nodeDef.getName());
return e;
}
}
private Object parseFieldValue(Entity parentEntity, AttributeDefinition def, String value, Integer fieldIndex) {
Object fieldValue = null;
if(StringUtils.isBlank(value)) {
return null;
}
if(def instanceof BooleanAttributeDefinition) {
fieldValue = Boolean.parseBoolean(value);
} else if(def instanceof CoordinateAttributeDefinition) {
if(fieldIndex != null) {
if(fieldIndex == 2) {
fieldValue = value;
} else {
fieldValue = Double.valueOf(value);
}
}
} else if(def instanceof DateAttributeDefinition) {
Integer val = Integer.valueOf(value);
fieldValue = val;
} else if(def instanceof NumberAttributeDefinition) {
NumberAttributeDefinition numberDef = (NumberAttributeDefinition) def;
Type type = numberDef.getType();
Number number = null;
switch(type) {
case INTEGER:
number = Integer.valueOf(value);
break;
case REAL:
number = Double.valueOf(value);
break;
}
if(number != null) {
fieldValue = number;
}
} else if(def instanceof RangeAttributeDefinition) {
RangeAttributeDefinition.Type type = ((RangeAttributeDefinition) def).getType();
Number number = null;
switch(type) {
case INTEGER:
number = Integer.valueOf(value);
break;
case REAL:
number = Double.valueOf(value);
break;
}
if(number != null) {
fieldValue = number;
}
} else if(def instanceof TimeAttributeDefinition) {
fieldValue = Integer.valueOf(value);
} else {
fieldValue = value;
}
return fieldValue;
}
private Object parseCompositeAttributeValue(Entity parentEntity, AttributeDefinition defn, String value) {
Object result;
if(defn instanceof CodeAttributeDefinition) {
Record record = parentEntity.getRecord();
ModelVersion version = record .getVersion();
result = parseCode(parentEntity, (CodeAttributeDefinition) defn, value, version );
} else if(defn instanceof RangeAttributeDefinition) {
RangeAttributeDefinition rangeDef = (RangeAttributeDefinition) defn;
RangeAttributeDefinition.Type type = rangeDef.getType();
NumericRange<?> range = null;
switch(type) {
case INTEGER:
range = IntegerRange.parseIntegerRange(value);
break;
case REAL:
range = RealRange.parseRealRange(value);
break;
}
result = range;
} else {
throw new IllegalArgumentException("Invalid AttributeDefinition: expected CodeAttributeDefinition or RangeAttributeDefinition");
}
return result;
}
@Transactional
public void promoteActiveRecord() throws RecordPersistenceException, RecordPromoteException {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
User user = sessionState.getUser();
recordManager.promote(record, user);
recordManager.unlock(record, user);
sessionManager.clearActiveRecord();
}
@Transactional
public void demoteActiveRecord() throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
CollectSurvey survey = sessionState.getActiveSurvey();
CollectRecord record = sessionState.getActiveRecord();
User user = sessionState.getUser();
recordManager.demote(survey, record.getId(), record.getStep(), user);
recordManager.unlock(record, user);
sessionManager.clearActiveRecord();
}
public void updateNodeHierarchy(Node<? extends NodeDefinition> node, int newPosition) {
}
public List<String> find(String context, String query) {
return null;
}
/**
* remove the active record from the current session
* @throws RecordPersistenceException
*/
public void clearActiveRecord() throws RecordPersistenceException {
SessionState sessionState = this.sessionManager.getSessionState();
CollectRecord activeRecord = sessionState.getActiveRecord();
User user = sessionState.getUser();
if(RecordState.SAVED == sessionState.getActiveRecordState()) {
this.recordManager.unlock(activeRecord, user);
}
this.sessionManager.clearActiveRecord();
}
/**
* Gets the code list items assignable to the specified attribute and matching the specified codes.
*
* @param parentEntityId
* @param attrName
* @param codes
* @return
*/
public List<CodeListItemProxy> getCodeListItems(int parentEntityId, String attrName, String[] codes){
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attrName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItem> filteredItems = new ArrayList<CodeListItem>();
if(codes != null && codes.length > 0) {
//filter by specified codes
for (CodeListItem item : items) {
for (String code : codes) {
if(item.getCode().equals(code)) {
filteredItems.add(item);
}
}
}
}
List<CodeListItemProxy> result = CodeListItemProxy.fromList(filteredItems);
return result;
}
/**
* Gets the code list items assignable to the specified attribute.
*
* @param parentEntityId
* @param attrName
* @return
*/
public List<CodeListItemProxy> findAssignableCodeListItems(int parentEntityId, String attrName){
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attrName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItemProxy> result = CodeListItemProxy.fromList(items);
List<Node<?>> selectedCodes = parent.getAll(attrName);
CodeListItemProxy.setSelectedItems(result, selectedCodes);
return result;
}
/**
* Finds a list of code list items assignable to the specified attribute and matching the passed codes
*
* @param parentEntityId
* @param attributeName
* @param codes
* @return
*/
public List<CodeListItemProxy> findAssignableCodeListItems(int parentEntityId, String attributeName, String[] codes) {
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attributeName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItemProxy> result = new ArrayList<CodeListItemProxy>();
for (String code : codes) {
CodeListItem item = findCodeListItem(items, code);
if(item != null) {
CodeListItemProxy proxy = new CodeListItemProxy(item);
result.add(proxy);
}
}
return result;
}
private User getUserInSession() {
SessionState sessionState = getSessionManager().getSessionState();
User user = sessionState.getUser();
return user;
}
private CollectSurvey getActiveSurvey() {
SessionState sessionState = getSessionManager().getSessionState();
CollectSurvey activeSurvey = sessionState.getActiveSurvey();
return activeSurvey;
}
protected CollectRecord getActiveRecord() {
SessionState sessionState = getSessionManager().getSessionState();
CollectRecord activeRecord = sessionState.getActiveRecord();
return activeRecord;
}
protected SessionManager getSessionManager() {
return sessionManager;
}
protected RecordManager getRecordManager() {
return recordManager;
}
/**
* Start of CodeList utility methods
*
* TODO move them to a better location
*/
private List<CodeListItem> getAssignableCodeListItems(Entity parent, CodeAttributeDefinition def) {
CollectRecord record = getActiveRecord();
ModelVersion version = record.getVersion();
List<CodeListItem> items = null;
if(StringUtils.isEmpty(def.getParentExpression())){
items = def.getList().getItems();
} else {
CodeAttribute parentCodeAttribute = getCodeParent(parent, def);
if(parentCodeAttribute!=null){
CodeListItem parentCodeListItem = parentCodeAttribute.getCodeListItem();
if(parentCodeListItem != null) {
//TODO exception if parent not specified
items = parentCodeListItem.getChildItems();
}
}
}
List<CodeListItem> result = new ArrayList<CodeListItem>();
if(items != null) {
for (CodeListItem item : items) {
if(version.isApplicable(item)) {
result.add(item);
}
}
}
return result;
}
private CodeAttribute getCodeParent(Entity context, CodeAttributeDefinition def) {
try {
String parentExpr = def.getParentExpression();
ExpressionFactory expressionFactory = context.getRecord().getSurveyContext().getExpressionFactory();
ModelPathExpression expression = expressionFactory.createModelPathExpression(parentExpr);
Node<?> parentNode = expression.evaluate(context, null);
if (parentNode != null && parentNode instanceof CodeAttribute) {
return (CodeAttribute) parentNode;
}
} catch (Exception e) {
// return null;
}
return null;
}
private CodeListItem findCodeListItem(List<CodeListItem> siblings, String code) {
String adaptedCode = code.trim();
adaptedCode = adaptedCode.toUpperCase();
//remove initial zeros
adaptedCode = adaptedCode.replaceFirst("^0+", "");
adaptedCode = Pattern.quote(adaptedCode);
for (CodeListItem item : siblings) {
String itemCode = item.getCode();
Pattern pattern = Pattern.compile("^[0]*" + adaptedCode + "$");
Matcher matcher = pattern.matcher(itemCode);
if(matcher.find()) {
return item;
}
}
return null;
}
private Code parseCode(Entity parent, CodeAttributeDefinition def, String value, ModelVersion version) {
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
Code code = parseCode(value, items, version);
return code;
}
private Code parseCode(String value, List<CodeListItem> codeList, ModelVersion version) {
Code code = null;
String[] strings = value.split(":");
String codeStr = null;
String qualifier = null;
switch(strings.length) {
case 2:
qualifier = strings[1].trim();
case 1:
codeStr = strings[0].trim();
break;
default:
//TODO throw error: invalid parameter
}
CodeListItem codeListItem = findCodeListItem(codeList, codeStr);
if(codeListItem != null) {
code = new Code(codeListItem.getCode(), qualifier);
}
if (code == null) {
code = new Code(codeStr, qualifier);
}
return code;
}
}
| collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java | /**
*
*/
package org.openforis.collect.remoting.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.openforis.collect.manager.RecordManager;
import org.openforis.collect.manager.RecordPromoteException;
import org.openforis.collect.manager.SessionManager;
import org.openforis.collect.metamodel.proxy.CodeListItemProxy;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.model.FieldSymbol;
import org.openforis.collect.model.RecordSummarySortField;
import org.openforis.collect.model.User;
import org.openforis.collect.model.proxy.RecordProxy;
import org.openforis.collect.persistence.RecordPersistenceException;
import org.openforis.collect.remoting.service.UpdateRequestOperation.Method;
import org.openforis.collect.web.session.SessionState;
import org.openforis.collect.web.session.SessionState.RecordState;
import org.openforis.idm.metamodel.AttributeDefinition;
import org.openforis.idm.metamodel.BooleanAttributeDefinition;
import org.openforis.idm.metamodel.CodeAttributeDefinition;
import org.openforis.idm.metamodel.CodeListItem;
import org.openforis.idm.metamodel.CoordinateAttributeDefinition;
import org.openforis.idm.metamodel.DateAttributeDefinition;
import org.openforis.idm.metamodel.EntityDefinition;
import org.openforis.idm.metamodel.ModelVersion;
import org.openforis.idm.metamodel.NodeDefinition;
import org.openforis.idm.metamodel.NumberAttributeDefinition;
import org.openforis.idm.metamodel.NumberAttributeDefinition.Type;
import org.openforis.idm.metamodel.RangeAttributeDefinition;
import org.openforis.idm.metamodel.Schema;
import org.openforis.idm.metamodel.TimeAttributeDefinition;
import org.openforis.idm.metamodel.validation.ValidationResults;
import org.openforis.idm.model.Attribute;
import org.openforis.idm.model.Code;
import org.openforis.idm.model.CodeAttribute;
import org.openforis.idm.model.Entity;
import org.openforis.idm.model.Field;
import org.openforis.idm.model.IntegerRange;
import org.openforis.idm.model.Node;
import org.openforis.idm.model.NodePointer;
import org.openforis.idm.model.NumericRange;
import org.openforis.idm.model.RealRange;
import org.openforis.idm.model.Record;
import org.openforis.idm.model.expression.ExpressionFactory;
import org.openforis.idm.model.expression.ModelPathExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* @author M. Togna
* @author S. Ricci
*
*/
public class DataService {
@Autowired
private SessionManager sessionManager;
@Autowired
private RecordManager recordManager;
@Transactional
public RecordProxy loadRecord(int id, int step) throws RecordPersistenceException {
CollectSurvey survey = getActiveSurvey();
User user = getUserInSession();
CollectRecord record = recordManager.checkout(survey, user, id, step);
//record.updateNodeStates();
Entity rootEntity = record.getRootEntity();
recordManager.addEmptyNodes(rootEntity);
SessionState sessionState = sessionManager.getSessionState();
sessionState.setActiveRecord(record);
sessionState.setActiveRecordState(RecordState.SAVED);
return new RecordProxy(record);
}
/**
*
* @param rootEntityName
* @param offset
* @param toIndex
* @param orderByFieldName
* @param filter
*
* @return map with "count" and "records" items
*/
@Transactional
public Map<String, Object> getRecordSummaries(String rootEntityName, int offset, int maxNumberOfRows, List<RecordSummarySortField> sortFields, String filter) {
Map<String, Object> result = new HashMap<String, Object>();
SessionState sessionState = sessionManager.getSessionState();
CollectSurvey activeSurvey = sessionState.getActiveSurvey();
Schema schema = activeSurvey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntityName);
String rootEntityDefinitionName = rootEntityDefinition.getName();
int count = recordManager.getCountRecords(activeSurvey, rootEntityDefinitionName);
List<CollectRecord> summaries = recordManager.getSummaries(activeSurvey, rootEntityDefinitionName, offset, maxNumberOfRows, sortFields, filter);
List<RecordProxy> proxies = new ArrayList<RecordProxy>();
for (CollectRecord summary : summaries) {
proxies.add(new RecordProxy(summary));
}
result.put("count", count);
result.put("records", proxies);
return result;
}
@Transactional
public RecordProxy createRecord(String rootEntityName, String versionName) throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
CollectSurvey activeSurvey = sessionState.getActiveSurvey();
ModelVersion version = activeSurvey.getVersion(versionName);
Schema schema = activeSurvey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntityName);
CollectRecord record = recordManager.create(activeSurvey, rootEntityDefinition, user, version.getName());
Entity rootEntity = record.getRootEntity();
recordManager.addEmptyNodes(rootEntity);
sessionState.setActiveRecord((CollectRecord) record);
sessionState.setActiveRecordState(RecordState.NEW);
RecordProxy recordProxy = new RecordProxy(record);
return recordProxy;
}
@Transactional
public void deleteRecord(int id) throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
recordManager.delete(id, user);
sessionManager.clearActiveRecord();
}
@Transactional
public void saveActiveRecord() throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
User user = sessionState.getUser();
record.setModifiedDate(new Date());
record.setModifiedBy(user);
recordManager.save(record);
sessionState.setActiveRecordState(RecordState.SAVED);
}
@Transactional
public void deleteActiveRecord() throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
Record record = sessionState.getActiveRecord();
recordManager.delete(record.getId(), user);
sessionManager.clearActiveRecord();
}
public List<UpdateResponse> updateActiveRecord(UpdateRequest request) {
List<UpdateRequestOperation> operations = request.getOperations();
List<UpdateResponse> updateResponses = new ArrayList<UpdateResponse>();
for (UpdateRequestOperation operation : operations) {
Collection<UpdateResponse> responses = processUpdateRequestOperation(operation);
updateResponses.addAll(responses);
}
return updateResponses;
}
@SuppressWarnings("unchecked")
private Collection<UpdateResponse> processUpdateRequestOperation(UpdateRequestOperation operation) {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
Integer parentEntityId = operation.getParentEntityId();
Entity parentEntity = (Entity) record.getNodeByInternalId(parentEntityId);
Integer nodeId = operation.getNodeId();
Integer fieldIndex = operation.getFieldIndex();
String nodeName = operation.getNodeName();
Node<?> node = null;
if(nodeId != null) {
node = record.getNodeByInternalId(nodeId);
}
NodeDefinition nodeDef = ((EntityDefinition) parentEntity.getDefinition()).getChildDefinition(nodeName);
String requestValue = operation.getValue();
String remarks = operation.getRemarks();
FieldSymbol symbol = operation.getSymbol();
Method method = operation.getMethod();
Map<Integer, UpdateResponse> responseMap = new HashMap<Integer, UpdateResponse>();
Set<NodePointer> relReqDependencies = null;
Set<Attribute<?,?>> checkDependencies = null;
List<NodePointer> cardinalityNodePointers = null;
Attribute<? extends AttributeDefinition, ?> attribute = null;
switch (method) {
case CONFIRM_ERROR:
attribute = (Attribute<AttributeDefinition, ?>) node;
record.setErrorConfirmed(attribute, true);
//checkDependencies = recordManager.clearValidationResults(attribute);
checkDependencies = new HashSet<Attribute<?,?>>();
attribute.clearValidationResults();
checkDependencies.add(attribute);
UpdateResponse response = getUpdateResponse(responseMap, attribute.getInternalId());
break;
case APPROVE_MISSING:
record.setMissingApproved(parentEntity, node.getName(), true);
cardinalityNodePointers = getCardinalityNodePointers(node);
break;
case UPDATE_REMARKS:
attribute = (Attribute<AttributeDefinition, ?>) node;
Field<?> fld = attribute.getField(fieldIndex);
fld.setRemarks(remarks);
getUpdateResponse(responseMap, nodeId);
break;
case ADD :
Node<?> createdNode = addNode(parentEntity, nodeDef, requestValue, symbol, remarks);
response = getUpdateResponse(responseMap, createdNode.getInternalId());
response.setCreatedNode(createdNode);
relReqDependencies = recordManager. clearRelevanceRequiredStates(createdNode);
if(createdNode instanceof Attribute){
attribute = (Attribute<? extends AttributeDefinition, ?>) createdNode;
checkDependencies = recordManager.clearValidationResults(attribute);
checkDependencies.add(attribute);
}
relReqDependencies.add(new NodePointer(createdNode.getParent(), createdNode.getName()));
cardinalityNodePointers = getCardinalityNodePointers(createdNode);
break;
case UPDATE:
attribute = (Attribute<AttributeDefinition, ?>) node;
record.setErrorConfirmed(attribute, false);
record.setMissingApproved(parentEntity, node.getName(), false);
cardinalityNodePointers = getCardinalityNodePointers(attribute);
response = getUpdateResponse(responseMap, attribute.getInternalId());
Map<Integer, Object> updatedFieldValues = new HashMap<Integer, Object>();
if (fieldIndex < 0) {
Object value = null;
if (requestValue != null) {
value = parseCompositeAttributeValue(parentEntity, attribute.getDefinition(), requestValue);
}
recordManager.setAttributeValue(attribute, value, remarks);
for (int idx = 0; idx < attribute.getFieldCount(); idx++) {
Field<?> field = attribute.getField(idx);
Object fieldValue = field.getValue();
updatedFieldValues.put(idx, fieldValue);
recordManager.setFieldValue(attribute, fieldValue, remarks, symbol, idx);
}
} else {
Object value = parseFieldValue(parentEntity, attribute.getDefinition(), requestValue, fieldIndex);
recordManager.setFieldValue(attribute, value, remarks, symbol, fieldIndex);
Field<?> field = attribute.getField(fieldIndex);
updatedFieldValues.put(fieldIndex, field.getValue());
}
response.setUpdatedFieldValues(updatedFieldValues);
relReqDependencies = recordManager.clearRelevanceRequiredStates(attribute);
checkDependencies = recordManager.clearValidationResults(attribute);
relReqDependencies.add(new NodePointer(attribute.getParent(), attribute.getName()));
checkDependencies.add(attribute);
break;
case DELETE:
relReqDependencies = new HashSet<NodePointer>();
checkDependencies = new HashSet<Attribute<?,?>>();
cardinalityNodePointers = getCardinalityNodePointers(node);
deleteNode(node, relReqDependencies, checkDependencies, responseMap);
break;
}
prepareUpdateResponse(responseMap, relReqDependencies, checkDependencies, cardinalityNodePointers);
return responseMap.values();
}
private List<NodePointer> getCardinalityNodePointers(Node<?> node){
List<NodePointer> nodePointers = new ArrayList<NodePointer>();
Entity parent = node.getParent();
String childName = node.getName();
while(parent != null){
NodePointer nodePointer = new NodePointer(parent, childName );
nodePointers.add(nodePointer);
childName = parent.getName();
parent = parent.getParent();
}
return nodePointers;
}
private void deleteNode(Node<?> node,Set<NodePointer> relevanceRequiredDependencies, Set<Attribute<?,?>> checkDependencies, Map<Integer, UpdateResponse> responseMap){
Stack<Node<?>> dependenciesStack = new Stack<Node<?>>();
Stack<Node<?>> nodesToRemove = new Stack<Node<?>>();
dependenciesStack.push(node);
Set<NodePointer> relevantDependencies = new HashSet<NodePointer>();
Set<NodePointer> requiredDependencies = new HashSet<NodePointer>();
while(!dependenciesStack.isEmpty()){
Node<?> n = dependenciesStack.pop();
nodesToRemove.push(n);
relevantDependencies.addAll(n.getRelevantDependencies());
requiredDependencies.addAll(n.getRequiredDependencies());
if(n instanceof Entity){
Entity entity = (Entity) n;
List<Node<? extends NodeDefinition>> children = entity.getChildren();
for (Node<? extends NodeDefinition> child : children) {
dependenciesStack.push(child);
}
} else {
Attribute<?,?> attr = (Attribute<?, ?>) n;
checkDependencies.addAll(attr.getCheckDependencies());
}
}
while(!nodesToRemove.isEmpty()){
Node<?> n = nodesToRemove.pop();
recordManager.deleteNode(n);
UpdateResponse resp = getUpdateResponse(responseMap, node.getInternalId());
resp.setDeletedNodeId(node.getInternalId());
}
//clear dependencies
recordManager.clearRelevantDependencies(relevantDependencies);
requiredDependencies.addAll(relevantDependencies);
recordManager.clearRequiredDependencies(requiredDependencies);
recordManager.clearValidationResults(checkDependencies);
relevanceRequiredDependencies.addAll(requiredDependencies);
}
private void prepareUpdateResponse(Map<Integer, UpdateResponse> responseMap, Set<NodePointer> relevanceRequiredDependencies, Set<Attribute<?, ?>> validtionResultsDependencies, List<NodePointer> cardinalityNodePointers) {
if (cardinalityNodePointers != null) {
for (NodePointer nodePointer : cardinalityNodePointers) {
// entity could be root definition
Entity parent = nodePointer.getEntity();
if (parent != null && !parent.isDetached()) {
String childName = nodePointer.getChildName();
UpdateResponse response = getUpdateResponse(responseMap, parent.getInternalId());
response.setRelevant(childName, parent.isRelevant(childName));
response.setRequired(childName, parent.isRequired(childName));
response.setMinCountValid(childName, parent.validateMinCount(childName));
response.setMaxCountValid(childName, parent.validateMaxCount(childName));
}
}
}
if (relevanceRequiredDependencies != null) {
for (NodePointer nodePointer : relevanceRequiredDependencies) {
Entity entity = nodePointer.getEntity();
if (!entity.isDetached()) {
String childName = nodePointer.getChildName();
UpdateResponse response = getUpdateResponse(responseMap, entity.getInternalId());
response.setRelevant(childName, entity.isRelevant(childName));
response.setRequired(childName, entity.isRequired(childName));
response.setMinCountValid(childName, entity.validateMinCount(childName));
response.setMaxCountValid(childName, entity.validateMaxCount(childName));
}
}
}
if (validtionResultsDependencies != null) {
for (Attribute<?, ?> checkDepAttr : validtionResultsDependencies) {
if (!checkDepAttr.isDetached()) {
checkDepAttr.clearValidationResults();
ValidationResults results = checkDepAttr.validateValue();
UpdateResponse response = getUpdateResponse(responseMap, checkDepAttr.getInternalId());
response.setAttributeValidationResults(results);
}
}
}
}
private UpdateResponse getUpdateResponse(Map<Integer, UpdateResponse> responseMap, int nodeId){
UpdateResponse response = responseMap.get(nodeId);
if(response == null){
response = new UpdateResponse(nodeId);
responseMap.put(nodeId, response);
}
return response;
}
@SuppressWarnings("unchecked")
private Node<?> addNode(Entity parentEntity, NodeDefinition nodeDef, String requestValue, FieldSymbol symbol, String remarks) {
if(nodeDef instanceof AttributeDefinition) {
AttributeDefinition def = (AttributeDefinition) nodeDef;
Attribute<?, ?> attribute = (Attribute<?, ?>) def.createNode();
parentEntity.add(attribute);
if(StringUtils.isNotBlank(requestValue)) {
Object value = parseCompositeAttributeValue(parentEntity, (AttributeDefinition) nodeDef, requestValue);
((Attribute<?, Object>) attribute).setValue(value);
}
if(symbol != null || remarks != null) {
Character symbolChar = null;
if(symbol != null) {
symbolChar = symbol.getCode();
}
Field<?> firstField = attribute.getField(0);
firstField.setSymbol(symbolChar);
firstField.setRemarks(remarks);
}
return attribute;
} else {
Entity e = recordManager.addEntity(parentEntity, nodeDef.getName());
return e;
}
}
private Object parseFieldValue(Entity parentEntity, AttributeDefinition def, String value, Integer fieldIndex) {
Object fieldValue = null;
if(StringUtils.isBlank(value)) {
return null;
}
if(def instanceof BooleanAttributeDefinition) {
fieldValue = Boolean.parseBoolean(value);
} else if(def instanceof CoordinateAttributeDefinition) {
if(fieldIndex != null) {
if(fieldIndex == 2) {
fieldValue = value;
} else {
fieldValue = Double.valueOf(value);
}
}
} else if(def instanceof DateAttributeDefinition) {
Integer val = Integer.valueOf(value);
fieldValue = val;
} else if(def instanceof NumberAttributeDefinition) {
NumberAttributeDefinition numberDef = (NumberAttributeDefinition) def;
Type type = numberDef.getType();
Number number = null;
switch(type) {
case INTEGER:
number = Integer.valueOf(value);
break;
case REAL:
number = Double.valueOf(value);
break;
}
if(number != null) {
fieldValue = number;
}
} else if(def instanceof RangeAttributeDefinition) {
RangeAttributeDefinition.Type type = ((RangeAttributeDefinition) def).getType();
Number number = null;
switch(type) {
case INTEGER:
number = Integer.valueOf(value);
break;
case REAL:
number = Double.valueOf(value);
break;
}
if(number != null) {
fieldValue = number;
}
} else if(def instanceof TimeAttributeDefinition) {
fieldValue = Integer.valueOf(value);
} else {
fieldValue = value;
}
return fieldValue;
}
private Object parseCompositeAttributeValue(Entity parentEntity, AttributeDefinition defn, String value) {
Object result;
if(defn instanceof CodeAttributeDefinition) {
Record record = parentEntity.getRecord();
ModelVersion version = record .getVersion();
result = parseCode(parentEntity, (CodeAttributeDefinition) defn, value, version );
} else if(defn instanceof RangeAttributeDefinition) {
RangeAttributeDefinition rangeDef = (RangeAttributeDefinition) defn;
RangeAttributeDefinition.Type type = rangeDef.getType();
NumericRange<?> range = null;
switch(type) {
case INTEGER:
range = IntegerRange.parseIntegerRange(value);
break;
case REAL:
range = RealRange.parseRealRange(value);
break;
}
result = range;
} else {
throw new IllegalArgumentException("Invalid AttributeDefinition: expected CodeAttributeDefinition or RangeAttributeDefinition");
}
return result;
}
@Transactional
public void promoteActiveRecord() throws RecordPersistenceException, RecordPromoteException {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
User user = sessionState.getUser();
recordManager.promote(record, user);
recordManager.unlock(record, user);
sessionManager.clearActiveRecord();
}
@Transactional
public void demoteActiveRecord() throws RecordPersistenceException {
SessionState sessionState = sessionManager.getSessionState();
CollectSurvey survey = sessionState.getActiveSurvey();
CollectRecord record = sessionState.getActiveRecord();
User user = sessionState.getUser();
recordManager.demote(survey, record.getId(), record.getStep(), user);
recordManager.unlock(record, user);
sessionManager.clearActiveRecord();
}
public void updateNodeHierarchy(Node<? extends NodeDefinition> node, int newPosition) {
}
public List<String> find(String context, String query) {
return null;
}
/**
* remove the active record from the current session
* @throws RecordPersistenceException
*/
public void clearActiveRecord() throws RecordPersistenceException {
SessionState sessionState = this.sessionManager.getSessionState();
CollectRecord activeRecord = sessionState.getActiveRecord();
User user = sessionState.getUser();
if(RecordState.SAVED == sessionState.getActiveRecordState()) {
this.recordManager.unlock(activeRecord, user);
}
this.sessionManager.clearActiveRecord();
}
/**
* Gets the code list items assignable to the specified attribute and matching the specified codes.
*
* @param parentEntityId
* @param attrName
* @param codes
* @return
*/
public List<CodeListItemProxy> getCodeListItems(int parentEntityId, String attrName, String[] codes){
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attrName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItem> filteredItems = new ArrayList<CodeListItem>();
if(codes != null && codes.length > 0) {
//filter by specified codes
for (CodeListItem item : items) {
for (String code : codes) {
if(item.getCode().equals(code)) {
filteredItems.add(item);
}
}
}
}
List<CodeListItemProxy> result = CodeListItemProxy.fromList(filteredItems);
return result;
}
/**
* Gets the code list items assignable to the specified attribute.
*
* @param parentEntityId
* @param attrName
* @return
*/
public List<CodeListItemProxy> findAssignableCodeListItems(int parentEntityId, String attrName){
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attrName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItemProxy> result = CodeListItemProxy.fromList(items);
List<Node<?>> selectedCodes = parent.getAll(attrName);
CodeListItemProxy.setSelectedItems(result, selectedCodes);
return result;
}
/**
* Finds a list of code list items assignable to the specified attribute and matching the passed codes
*
* @param parentEntityId
* @param attributeName
* @param codes
* @return
*/
public List<CodeListItemProxy> findAssignableCodeListItems(int parentEntityId, String attributeName, String[] codes) {
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attributeName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItemProxy> result = new ArrayList<CodeListItemProxy>();
for (String code : codes) {
CodeListItem item = findCodeListItem(items, code);
if(item != null) {
CodeListItemProxy proxy = new CodeListItemProxy(item);
result.add(proxy);
}
}
return result;
}
private User getUserInSession() {
SessionState sessionState = getSessionManager().getSessionState();
User user = sessionState.getUser();
return user;
}
private CollectSurvey getActiveSurvey() {
SessionState sessionState = getSessionManager().getSessionState();
CollectSurvey activeSurvey = sessionState.getActiveSurvey();
return activeSurvey;
}
protected CollectRecord getActiveRecord() {
SessionState sessionState = getSessionManager().getSessionState();
CollectRecord activeRecord = sessionState.getActiveRecord();
return activeRecord;
}
protected SessionManager getSessionManager() {
return sessionManager;
}
protected RecordManager getRecordManager() {
return recordManager;
}
/**
* Start of CodeList utility methods
*
* TODO move them to a better location
*/
private List<CodeListItem> getAssignableCodeListItems(Entity parent, CodeAttributeDefinition def) {
CollectRecord record = getActiveRecord();
ModelVersion version = record.getVersion();
List<CodeListItem> items = null;
if(StringUtils.isEmpty(def.getParentExpression())){
items = def.getList().getItems();
} else {
CodeAttribute parentCodeAttribute = getCodeParent(parent, def);
if(parentCodeAttribute!=null){
CodeListItem parentCodeListItem = parentCodeAttribute.getCodeListItem();
if(parentCodeListItem != null) {
//TODO exception if parent not specified
items = parentCodeListItem.getChildItems();
}
}
}
List<CodeListItem> result = new ArrayList<CodeListItem>();
if(items != null) {
for (CodeListItem item : items) {
if(version.isApplicable(item)) {
result.add(item);
}
}
}
return result;
}
private CodeAttribute getCodeParent(Entity context, CodeAttributeDefinition def) {
try {
String parentExpr = def.getParentExpression();
ExpressionFactory expressionFactory = context.getRecord().getSurveyContext().getExpressionFactory();
ModelPathExpression expression = expressionFactory.createModelPathExpression(parentExpr);
Node<?> parentNode = expression.evaluate(context, null);
if (parentNode != null && parentNode instanceof CodeAttribute) {
return (CodeAttribute) parentNode;
}
} catch (Exception e) {
// return null;
}
return null;
}
private CodeListItem findCodeListItem(List<CodeListItem> siblings, String code) {
String adaptedCode = code.trim();
adaptedCode = adaptedCode.toUpperCase();
//remove initial zeros
adaptedCode = adaptedCode.replaceFirst("^0+", "");
adaptedCode = Pattern.quote(adaptedCode);
for (CodeListItem item : siblings) {
String itemCode = item.getCode();
Pattern pattern = Pattern.compile("^[0]*" + adaptedCode + "$");
Matcher matcher = pattern.matcher(itemCode);
if(matcher.find()) {
return item;
}
}
return null;
}
private Code parseCode(Entity parent, CodeAttributeDefinition def, String value, ModelVersion version) {
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
Code code = parseCode(value, items, version);
return code;
}
private Code parseCode(String value, List<CodeListItem> codeList, ModelVersion version) {
Code code = null;
String[] strings = value.split(":");
String codeStr = null;
String qualifier = null;
switch(strings.length) {
case 2:
qualifier = strings[1].trim();
case 1:
codeStr = strings[0].trim();
break;
default:
//TODO throw error: invalid parameter
}
CodeListItem codeListItem = findCodeListItem(codeList, codeStr);
if(codeListItem != null) {
code = new Code(codeListItem.getCode(), qualifier);
}
if (code == null) {
code = new Code(codeStr, qualifier);
}
return code;
}
}
| udpated approve missing
| collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java | udpated approve missing | <ide><path>ollect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java
<ide> UpdateResponse response = getUpdateResponse(responseMap, attribute.getInternalId());
<ide> break;
<ide> case APPROVE_MISSING:
<del> record.setMissingApproved(parentEntity, node.getName(), true);
<add> record.setMissingApproved(parentEntity, nodeName, true);
<ide> cardinalityNodePointers = getCardinalityNodePointers(node);
<ide> break;
<ide> case UPDATE_REMARKS: |
|
Java | mit | error: pathspec '211/Solution.java' did not match any file(s) known to git
| 3f04cce5bc1a55be7b9f8cfef34a6313f72f6f1d | 1 | starforever/leetcode,starforever/leetcode,starforever/leetcode | class TrieNode
{
boolean finish = false;
HashMap<Character, TrieNode> next = new HashMap<Character, TrieNode>();
}
public class WordDictionary
{
private TrieNode root = new TrieNode();
public void addWord (String word)
{
if (word == null)
throw new IllegalArgumentException();
TrieNode p = root;
for (int i = 0; i < word.length(); ++i)
{
char c = word.charAt(i);
if (p.next.get(c) == null)
p.next.put(c, new TrieNode());
p = p.next.get(c);
}
p.finish = true;
}
private boolean match (TrieNode cur, int idx, String word)
{
if (idx == word.length())
return cur.finish;
while (idx < word.length() && word.charAt(idx) != '.')
{
cur = cur.next.get(word.charAt(idx++));
if (cur == null)
return false;
}
if (idx == word.length())
return cur.finish;
for (TrieNode r : cur.next.values())
{
if (match(r, idx + 1, word))
return true;
}
return false;
}
public boolean search (String word)
{
if (word == null)
throw new IllegalArgumentException();
return match(root, 0, word);
}
}
| 211/Solution.java | (Add and Search Word) [Accepted]
| 211/Solution.java | (Add and Search Word) [Accepted] | <ide><path>11/Solution.java
<add>class TrieNode
<add>{
<add> boolean finish = false;
<add> HashMap<Character, TrieNode> next = new HashMap<Character, TrieNode>();
<add>}
<add>
<add>public class WordDictionary
<add>{
<add> private TrieNode root = new TrieNode();
<add>
<add> public void addWord (String word)
<add> {
<add> if (word == null)
<add> throw new IllegalArgumentException();
<add> TrieNode p = root;
<add> for (int i = 0; i < word.length(); ++i)
<add> {
<add> char c = word.charAt(i);
<add> if (p.next.get(c) == null)
<add> p.next.put(c, new TrieNode());
<add> p = p.next.get(c);
<add> }
<add> p.finish = true;
<add> }
<add>
<add> private boolean match (TrieNode cur, int idx, String word)
<add> {
<add> if (idx == word.length())
<add> return cur.finish;
<add> while (idx < word.length() && word.charAt(idx) != '.')
<add> {
<add> cur = cur.next.get(word.charAt(idx++));
<add> if (cur == null)
<add> return false;
<add> }
<add> if (idx == word.length())
<add> return cur.finish;
<add> for (TrieNode r : cur.next.values())
<add> {
<add> if (match(r, idx + 1, word))
<add> return true;
<add> }
<add> return false;
<add> }
<add>
<add> public boolean search (String word)
<add> {
<add> if (word == null)
<add> throw new IllegalArgumentException();
<add> return match(root, 0, word);
<add> }
<add>} |
|
Java | mit | c7791e2fde2000a9e1a4af904ef882a3278c8fe6 | 0 | ist-dresden/composum-platform,ist-dresden/composum-platform,ist-dresden/composum-platform | services/staging/src/main/java/com/composum/sling/platform/staging/service/ReplicationManager.java | package com.composum.sling.platform.staging.service;
import org.apache.sling.api.resource.ResourceResolver;
import javax.jcr.RepositoryException;
import java.util.Calendar;
import java.util.List;
public interface ReplicationManager {
String RELEASE_LABEL_PREFIX = "composum-release-";
List<String> getReleases(ResourceResolver resolver, Iterable<String> rootPaths)
throws RepositoryException;
void updateToRelease(final ResourceResolver resolver, final String sitePath, String releaseLabel)
throws RepositoryException;
void createRelease(ResourceResolver resolver, Iterable<String> rootPaths,
String releaseLabel)
throws RepositoryException;
void removeRelease(ResourceResolver resolver, Iterable<String> rootPaths,
String releaseLabel, boolean deleteVersions)
throws RepositoryException;
void purgeReleases(ResourceResolver resolver, Iterable<String> rootPaths,
Calendar keepDate, int keepCount)
throws RepositoryException;
void rollbackToRelease(ResourceResolver resolver, Iterable<String> rootPaths,
String releaseLabel)
throws RepositoryException;
}
| CMP-61 obsolete (seems unused copy of ReleaseManager)
| services/staging/src/main/java/com/composum/sling/platform/staging/service/ReplicationManager.java | CMP-61 obsolete (seems unused copy of ReleaseManager) | <ide><path>ervices/staging/src/main/java/com/composum/sling/platform/staging/service/ReplicationManager.java
<del>package com.composum.sling.platform.staging.service;
<del>
<del>import org.apache.sling.api.resource.ResourceResolver;
<del>
<del>import javax.jcr.RepositoryException;
<del>import java.util.Calendar;
<del>import java.util.List;
<del>
<del>public interface ReplicationManager {
<del>
<del> String RELEASE_LABEL_PREFIX = "composum-release-";
<del>
<del> List<String> getReleases(ResourceResolver resolver, Iterable<String> rootPaths)
<del> throws RepositoryException;
<del>
<del> void updateToRelease(final ResourceResolver resolver, final String sitePath, String releaseLabel)
<del> throws RepositoryException;
<del>
<del> void createRelease(ResourceResolver resolver, Iterable<String> rootPaths,
<del> String releaseLabel)
<del> throws RepositoryException;
<del>
<del> void removeRelease(ResourceResolver resolver, Iterable<String> rootPaths,
<del> String releaseLabel, boolean deleteVersions)
<del> throws RepositoryException;
<del>
<del> void purgeReleases(ResourceResolver resolver, Iterable<String> rootPaths,
<del> Calendar keepDate, int keepCount)
<del> throws RepositoryException;
<del>
<del> void rollbackToRelease(ResourceResolver resolver, Iterable<String> rootPaths,
<del> String releaseLabel)
<del> throws RepositoryException;
<del>} |
||
Java | apache-2.0 | b5fcca5e0a7bc8aba88ca8509b5f428a6a721c1c | 0 | apache/derby,trejkaz/derby,trejkaz/derby,apache/derby,trejkaz/derby,apache/derby,apache/derby | /*
Derby - Class org.apache.derbyTesting.functionTests.tests.largedata.LobLimitsClientTest
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.derbyTesting.functionTests.tests.largedata;
import org.apache.derbyTesting.junit.TestConfiguration;
import junit.framework.Test;
/**
* LobLimitsClientTest runs the large lob limits test for the
* client. It is separated from LobLimitsTest because the
* test takes so long that it is convenient to run it separately
*
*/
public class LobLimitsClientTest extends LobLimitsTest {
public LobLimitsClientTest(String name) {
super(name);
}
public static Test suite() {
return (TestConfiguration.clientServerDecorator(LobLimitsTest.suite()));
}
}
| java/testing/org/apache/derbyTesting/functionTests/tests/largedata/LobLimitsClientTest.java | /*
Derby - Class org.apache.derbyTesting.functionTests.tests.largedata.LobLimitsClientTest
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.derbyTesting.functionTests.tests.largedata;
import org.apache.derbyTesting.junit.TestConfiguration;
import junit.framework.Test;
/**
* LobLimitsClientTest runs the large lob limits test for the
* client. It is separated from LobLimitsTest because the
* test takes so long that it is convenient to run it separately
*
*/
public class LobLimitsClientTest extends LobLimitsTest {
public LobLimitsClientTest(String name) {
super(name);
}
public static Test suite() {
return TestConfiguration.singleUseDatabaseDecorator(
TestConfiguration.clientServerDecorator(LobLimitsTest.suite()));
}
}
| DERBY-5638 intermittent test failure in test_05_ClobNegative when running full largedata._Suite; LobLimitsTestjava.sql.SQLException: Table/View 'BLOBTBL' already exists in Schema 'APP'.
Now that we truncate the tables and shutdown the databases after the large data suite run, we do not need to have a clean database test setup for network server run. I have run large data suite multiple times on my machine with the changes in this revision, and then all finished succesffuly with a fairly small wombat db size(3.9MB) and I did not see any lock timeouts in derby.log
git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@1305524 13f79535-47bb-0310-9956-ffa450edef68
| java/testing/org/apache/derbyTesting/functionTests/tests/largedata/LobLimitsClientTest.java | DERBY-5638 intermittent test failure in test_05_ClobNegative when running full largedata._Suite; LobLimitsTestjava.sql.SQLException: Table/View 'BLOBTBL' already exists in Schema 'APP'. | <ide><path>ava/testing/org/apache/derbyTesting/functionTests/tests/largedata/LobLimitsClientTest.java
<ide> }
<ide>
<ide> public static Test suite() {
<del> return TestConfiguration.singleUseDatabaseDecorator(
<del> TestConfiguration.clientServerDecorator(LobLimitsTest.suite()));
<add> return (TestConfiguration.clientServerDecorator(LobLimitsTest.suite()));
<ide> }
<ide> } |
|
JavaScript | bsd-2-clause | c6d703556e75bc6f854a0b4ee606b9866c3a8e53 | 0 | miataru/miataru-server,miataru/miataru-server | var RequestConfig = require('../../models/RequestConfig');
var RequestLocation = require('../../models/RequestLocation');
var RequestDevice = require('../../models/RequestDevice');
module.exports = function(req, res, next) {
req.MIATARU = req.MIATARU || {};
var nextError;
try {
switch(req.path) {
case '/UpdateLocation':
parseUpdateLocation(req);
break;
case '/GetLocation':
parseGetLocations(req);
break;
case '/GetLocationHistory':
//TODO
break;
}
}
catch(error) {
nextError = error;
}
next(nextError);
};
function parseUpdateLocation(req) {
req.MIATARU.config = new RequestConfig(req.body['MiataruConfig'] || {});
req.MIATARU.locations = (req.body['MiataruLocation'] || [{}]).map(function(location) {
return new RequestLocation(location);
});
}
function parseGetLocations(req) {
req.MIATARU.devices = (req.body['MiataruGetLocation'] || [{}]).map(function(device) {
console.log( device );
return new RequestDevice(device);
});
} | lib/routes/location/inputParser.js | var RequestConfig = require('../../models/RequestConfig');
var RequestLocation = require('../../models/RequestLocation');
var RequestDevice = require('../../models/RequestDevice');
module.exports = function(req, res, next) {
req.MIATARU = req.MIATARU || {};
var nextError;
try {
switch(req.path) {
case '/UpdateLocation':
parseUpdateLocation(req);
break;
case '/GetLocation':
parseGetLocations(req);
break;
case '/GetLocationHistory':
//TODO
break;
}
}
catch(error) {
console.log( 'sdf', error );
nextError = error;
}
next(nextError);
};
function parseUpdateLocation(req) {
req.MIATARU.config = new RequestConfig(req.body['MiataruConfig'] || {});
req.MIATARU.locations = (req.body['MiataruLocation'] || [{}]).map(function(location) {
return new RequestLocation(location);
});
}
function parseGetLocations(req) {
req.MIATARU.devices = (req.body['MiataruGetLocation'] || [{}]).map(function(device) {
console.log( device );
return new RequestDevice(device);
});
} | boyscout
| lib/routes/location/inputParser.js | boyscout | <ide><path>ib/routes/location/inputParser.js
<ide> }
<ide> }
<ide> catch(error) {
<del> console.log( 'sdf', error );
<ide> nextError = error;
<ide> }
<ide> |
|
JavaScript | lgpl-2.1 | 558f10799dbd769e4d1393ecf17b83e0ec875d95 | 0 | Distrotech/sogo,Distrotech/sogo,Distrotech/sogo,Distrotech/sogo,Distrotech/sogo | var isSieveScriptsEnabled = false;
var filters = [];
var mailAccounts = null;
var dialogs = {};
function savePreferences(sender) {
var sendForm = true;
var sigList = $("signaturePlacementList");
if (sigList)
sigList.disabled = false;
if ($("calendarCategoriesListWrapper")) {
serializeCalendarCategories();
}
if ($("contactsCategoriesListWrapper")) {
serializeContactsCategories();
}
if ($("dayStartTime")) {
var start = $("dayStartTime");
var selectedStart = parseInt(start.options[start.selectedIndex].value);
var end = $("dayEndTime");
var selectedEnd = parseInt(end.options[end.selectedIndex].value);
if (selectedStart >= selectedEnd) {
showAlertDialog (_("Day start time must be prior to day end time."));
sendForm = false;
}
}
if ($("enableVacation") && $("enableVacation").checked) {
if ($("autoReplyText").value.strip().length == 0
|| $("autoReplyEmailAddresses").value.strip().length == 0) {
showAlertDialog(_("Please specify your message and your email addresses for which you want to enable auto reply."));
sendForm = false;
}
if ($("enableVacationEndDate") && $("enableVacationEndDate").checked) {
var endDate = new Date($("vacationEndDate_date").value);
var now = new Date();
if (endDate.getTime() < now.getTime()) {
showAlertDialog(_("End date of your auto reply must be in the future."));
sendForm = false;
}
}
}
if ($("enableForward") && $("enableForward").checked) {
var addresses = $("forwardAddress").value.split(",");
for (var i = 0; i < addresses.length && sendForm; i++)
if (!emailRE.test(addresses[i].strip())) {
showAlertDialog(_("Please specify an address to which you want to forward your messages."));
sendForm = false;
}
}
if (isSieveScriptsEnabled) {
var jsonFilters = prototypeIfyFilters();
$("sieveFilters").setValue(Object.toJSON(jsonFilters));
}
saveMailAccounts();
if (sendForm)
$("mainForm").submit();
return false;
}
function prototypeIfyFilters() {
var newFilters = $([]);
for (var i = 0; i < filters.length; i++) {
var filter = filters[i];
var newFilter = $({});
newFilter.name = filter.name;
newFilter.match = filter.match;
newFilter.active = filter.active;
if (filter.rules) {
newFilter.rules = $([]);
for (var j = 0; j < filter.rules.length; j++) {
newFilter.rules.push($(filter.rules[j]));
}
}
newFilter.actions = $([]);
for (var j = 0; j < filter.actions.length; j++) {
newFilter.actions.push($(filter.actions[j]));
}
newFilters.push(newFilter);
}
return newFilters;
}
function _setupEvents() {
var widgets = [ "timezone", "shortDateFormat", "longDateFormat",
"timeFormat", "weekStartDay", "dayStartTime", "dayEndTime",
"firstWeek", "messageCheck", "sortByThreads",
"subscribedFoldersOnly", "language", "defaultCalendar",
"enableVacation" ];
for (var i = 0; i < widgets.length; i++) {
var widget = $(widgets[i]);
if (widget) {
widget.observe("change", onChoiceChanged);
}
}
// We check for non-null elements as replyPlacementList and composeMessagesType
// might not be present if ModulesConstraints disable those elements
if ($("replyPlacementList"))
$("replyPlacementList").observe ("change", onReplyPlacementListChange);
if ($("composeMessagesType"))
$("composeMessagesType").observe ("change", onComposeMessagesTypeChange);
// Note: we also monitor changes to the calendar categories.
// See functions endEditable and onColorPickerChoice.
var valueInputs = [ "calendarCategoriesValue", "calendarCategoriesValue" ];
for (var i = 0; i < valueInputs.length; i++) {
var valueInput = $(valueInputs[i]);
if (valueInput)
valueInput.value = "";
}
}
function onChoiceChanged(event) {
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
function addDefaultEmailAddresses(event) {
var defaultAddresses = $("defaultEmailAddresses").value.split(/, */);
var addresses = $("autoReplyEmailAddresses").value.trim();
if (addresses) addresses = addresses.split(/, */);
else addresses = new Array();
defaultAddresses.each(function(adr) {
for (var i = 0; i < addresses.length; i++)
if (adr == addresses[i])
break;
if (i == addresses.length)
addresses.push(adr);
});
$("autoReplyEmailAddresses").value = addresses.join(", ");
event.stop();
}
function initPreferences() {
var tabsContainer = $("preferencesTabs");
var controller = new SOGoTabsController();
controller.attachToTabsContainer(tabsContainer);
var filtersListWrapper = $("filtersListWrapper");
if (filtersListWrapper) {
isSieveScriptsEnabled = true;
}
_setupEvents();
if (typeof (initAdditionalPreferences) != "undefined")
initAdditionalPreferences();
var wrapper = $("calendarCategoriesListWrapper");
if (wrapper) {
var table = wrapper.childNodesWithTag("table")[0];
resetCalendarCategoriesColors(null);
var r = $$("#calendarCategoriesListWrapper tbody tr");
for (var i= 0; i < r.length; i++)
r[i].identify();
table.multiselect = true;
resetCalendarTableActions();
$("calendarCategoryAdd").observe("click", onCalendarCategoryAdd);
$("calendarCategoryDelete").observe("click", onCalendarCategoryDelete);
}
wrapper = $("contactsCategoriesListWrapper");
if (wrapper) {
var table = wrapper.childNodesWithTag("table")[0];
var r = $$("#contactsCategoriesListWrapper tbody tr");
for (var i= 0; i < r.length; i++)
r[i].identify();
table.multiselect = true;
resetContactsTableActions();
$("contactsCategoryAdd").observe("click", onContactsCategoryAdd);
$("contactsCategoryDelete").observe("click", onContactsCategoryDelete);
}
// Disable placement (after) if composing in HTML
if ($("composeMessagesType")) {
if ($("composeMessagesType").value == 1) {
$("replyPlacementList").selectedIndex = 0;
$("replyPlacementList").disabled = 1;
}
onReplyPlacementListChange ();
}
var button = $("addDefaultEmailAddresses");
if (button)
button.observe("click", addDefaultEmailAddresses);
button = $("changePasswordBtn");
if (button)
button.observe("click", onChangePasswordClick);
initSieveFilters();
initMailAccounts();
button = $("enableVacationEndDate");
if (button) {
assignCalendar('vacationEndDate_date');
button.on("change", function(event) {
if (this.checked)
$("vacationEndDate_date").enable();
else
$("vacationEndDate_date").disable();
});
}
}
function initSieveFilters() {
var table = $("filtersList");
if (table) {
var filtersValue = $("sieveFilters").getValue();
if (filtersValue && filtersValue.length) {
filters = $(filtersValue.evalJSON(false));
for (var i = 0; i < filters.length; i++) {
appendSieveFilterRow(table, i, filters[i]);
}
}
$("filterAdd").observe("click", onFilterAdd);
$("filterDelete").observe("click", onFilterDelete);
$("filterMoveUp").observe("click", onFilterMoveUp);
$("filterMoveDown").observe("click", onFilterMoveDown);
}
}
function appendSieveFilterRow(filterTable, number, filter) {
var row = createElement("tr");
row.observe("mousedown", onRowClick);
row.observe("dblclick", onFilterEdit.bindAsEventListener(row));
var nameColumn = createElement("td");
nameColumn.appendChild(document.createTextNode(filter["name"]));
row.appendChild(nameColumn);
var activeColumn = createElement("td", null, "activeColumn");
var cb = createElement("input", null, "checkBox",
{ type: "checkbox" },
null, activeColumn);
cb.checked = filter.active;
var bound = onScriptActiveCheck.bindAsEventListener(cb);
cb.observe("click", bound);
row.appendChild(activeColumn);
filterTable.tBodies[0].appendChild(row);
}
function onScriptActiveCheck(event) {
var index = this.parentNode.parentNode.rowIndex - 1;
filters[index].active = this.checked;
}
function updateSieveFilterRow(filterTable, number, filter) {
var row = $(filterTable.tBodies[0].rows[number]);
var columns = row.childNodesWithTag("td");
var nameColumn = columns[0];
while (nameColumn.firstChild) {
nameColumn.removeChild(nameColumn.firstChild);
}
nameColumn.appendChild(document.createTextNode(filter.name));
var activeColumn = columns[1];
var cb = activeColumn.childNodesWithTag("input");
cb[0].checked = filter.active;
}
function _editFilter(filterId) {
var urlstr = ApplicationBaseURL + "editFilter?filter=" + filterId;
var win = window.open(urlstr, "sieve_filter_" + filterId,
"width=560,height=380,resizable=0");
if (win)
win.focus();
}
function onFilterAdd(event) {
_editFilter("new");
event.stop();
}
function onFilterDelete(event) {
var filtersList = $("filtersList").tBodies[0];
var nodes = filtersList.getSelectedNodes();
if (nodes.length > 0) {
var deletedFilters = [];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
deletedFilters.push(node.rowIndex - 1);
}
deletedFilters = deletedFilters.sort(function (x,y) { return x-y; });
var rows = filtersList.rows;
for (var i = 0; i < deletedFilters.length; i++) {
var filterNbr = deletedFilters[i];
filters.splice(filterNbr, 1);
var row = rows[filterNbr];
row.parentNode.removeChild(row);
}
}
event.stop();
}
function onFilterMoveUp(event) {
var filtersList = $("filtersList").tBodies[0];
var nodes = filtersList.getSelectedNodes();
if (nodes.length > 0) {
var node = nodes[0];
var previous = node.previous();
if (previous) {
var count = node.rowIndex - 1;
node.parentNode.removeChild(node);
filtersList.insertBefore(node, previous);
var swapFilter = filters[count];
filters[count] = filters[count - 1];
filters[count - 1] = swapFilter;
}
}
event.stop();
}
function onFilterMoveDown(event) {
var filtersList = $("filtersList").tBodies[0];
var nodes = filtersList.getSelectedNodes();
if (nodes.length > 0) {
var node = nodes[0];
var next = node.next();
if (next) {
var count = node.rowIndex - 1;
filtersList.removeChild(next);
filtersList.insertBefore(next, node);
var swapFilter = filters[count];
filters[count] = filters[count + 1];
filters[count + 1] = swapFilter;
}
}
event.stop();
}
function onFilterEdit(event) {
_editFilter(this.rowIndex - 1);
event.stop();
}
function copyFilter(originalFilter) {
var newFilter = {};
newFilter.name = originalFilter.name;
newFilter.match = originalFilter.match;
newFilter.active = originalFilter.active;
if (originalFilter.rules) {
newFilter.rules = [];
for (var i = 0; i < originalFilter.rules.length; i++) {
newFilter.rules.push(_copyFilterElement(originalFilter.rules[i]));
}
}
newFilter.actions = [];
for (var i = 0; i < originalFilter.actions.length; i++) {
newFilter.actions.push(_copyFilterElement(originalFilter.actions[i]));
}
return newFilter;
}
function _copyFilterElement(filterElement) { /* element = rule or action */
var newElement = {};
for (var k in filterElement) {
var value = filterElement[k];
if (typeof(value) == "string" || typeof(value) == "number") {
newElement[k] = value;
}
}
return newElement;
}
function getSieveCapabilitiesFromEditor() {
return sieveCapabilities;
}
function getFilterFromEditor(filterId) {
return copyFilter(filters[filterId]);
}
function setupMailboxesFromJSON(jsonResponse) {
var responseMboxes = jsonResponse.mailboxes;
userMailboxes = $([]);
for (var i = 0; i < responseMboxes.length; i++) {
var name = responseMboxes[i].path.substr(1);
userMailboxes.push(name);
}
}
function updateFilterFromEditor(filterId, filterJSON) {
var filter = filterJSON.evalJSON();
var sanitized = {};
for (var k in filter) {
if (!(k == "rules" && filter.match == "allmessages")) {
sanitized[k] = filter[k];
}
}
var table = $("filtersList");
if (filterId == "new") {
var newNumber = filters.length;
filters.push(sanitized);
appendSieveFilterRow(table, newNumber, sanitized);
} else {
filters[filterId] = sanitized;
updateSieveFilterRow(table, filterId, sanitized);
}
}
/* mail accounts */
function initMailAccounts() {
var mailAccountsJSON = $("mailAccountsJSON");
mailAccounts = mailAccountsJSON.value.evalJSON();
var mailAccountsList = $("mailAccountsList");
if (mailAccountsList) {
var li = createMailAccountLI(mailAccounts[0], true);
mailAccountsList.appendChild(li);
for (var i = 1; i < mailAccounts.length; i++) {
li = createMailAccountLI(mailAccounts[i]);
mailAccountsList.appendChild(li);
}
var lis = mailAccountsList.childNodesWithTag("li");
lis[0].readOnly = true;
lis[0].selectElement();
var button = $("mailAccountAdd");
if (button) {
button.observe("click", onMailAccountAdd);
}
button = $("mailAccountDelete");
if (button) {
button.observe("click", onMailAccountDelete);
}
}
var info = $("accountInfo");
var inputs = info.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
$(inputs[i]).observe("change", onMailAccountInfoChange);
}
info = $("identityInfo");
inputs = info.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
$(inputs[i]).observe("change", onMailIdentityInfoChange);
}
$("actSignature").observe("click", onMailIdentitySignatureClick);
displayMailAccount(mailAccounts[0], true);
info = $("returnReceiptsInfo");
inputs = info.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
$(inputs[i]).observe("change", onMailReceiptInfoChange);
}
inputs = info.getElementsByTagName("select");
for (var i = 0; i < inputs.length; i++) {
$(inputs[i]).observe("change", onMailReceiptActionChange);
}
}
function onMailAccountInfoChange(event) {
this.mailAccount[this.name] = this.value;
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
function onMailIdentityInfoChange(event) {
if (!this.mailAccount["identities"]) {
this.mailAccount["identities"] = [{}];
}
var identity = this.mailAccount["identities"][0];
identity[this.name] = this.value;
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
function onMailReceiptInfoChange(event) {
if (!this.mailAccount["receipts"]) {
this.mailAccount["receipts"] = {};
}
var keyName = this.name.cssIdToHungarianId();
this.mailAccount["receipts"][keyName] = this.value;
var popupIds = [ "receipt-non-recipient-action",
"receipt-outside-domain-action",
"receipt-any-action" ];
var receiptActionsDisable = (this.value == "ignore");
for (var i = 0; i < popupIds.length; i++) {
var actionPopup = $(popupIds[i]);
actionPopup.disabled = receiptActionsDisable;
}
}
function onMailReceiptActionChange(event) {
if (!this.mailAccount["receipts"]) {
this.mailAccount["receipts"] = {};
}
var keyName = this.name.cssIdToHungarianId();
this.mailAccount["receipts"][keyName] = this.value;
}
function onMailIdentitySignatureClick(event) {
if (!this.readOnly) {
var dialogId = "signatureDialog";
var dialog = dialogs[dialogId];
if (!dialog) {
var label = _("Please enter your signature below:");
var fields = createElement("p");
fields.appendChild(createElement("textarea", "signature"));
fields.appendChild(createElement("br"));
fields.appendChild(createButton("okBtn", _("OK"),
onMailIdentitySignatureOK));
fields.appendChild(createButton("cancelBtn", _("Cancel"),
disposeDialog.bind(document.body, dialogId)));
var dialog = createDialog(dialogId,
_("Signature"),
label,
fields,
"none");
document.body.appendChild(dialog);
dialog.show();
dialogs[dialogId] = dialog;
if ($("composeMessagesType").value != 0) {
CKEDITOR.replace('signature',
{ height: "70px",
toolbar: [['Bold', 'Italic', '-', 'Link',
'Font','FontSize','-','TextColor',
'BGColor']
],
language: localeCode,
scayt_sLang: localeCode });
}
}
dialog.mailAccount = this.mailAccount;
if (!this.mailAccount["identities"]) {
this.mailAccount["identities"] = [{}];
}
var identity = this.mailAccount["identities"][0];
var area = $("signature");
if (typeof(identity["signature"]) != "undefined")
area.value = identity["signature"];
else
area.value = "";
dialog.show();
$("bgDialogDiv").show();
if (!CKEDITOR.instances["signature"])
area.focus();
event.stop();
}
}
function onMailIdentitySignatureOK(event) {
var dialog = $("signatureDialog");
var mailAccount = dialog.mailAccount;
if (!mailAccount["identities"]) {
mailAccount["identities"] = [{}];
}
var identity = mailAccount["identities"][0];
var content = (CKEDITOR.instances["signature"]
? CKEDITOR.instances["signature"].getData()
: $("signature").value);
identity["signature"] = content;
displayAccountSignature(mailAccount);
dialog.hide();
$("bgDialogDiv").hide();
dialog.mailAccount = null;
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
function createMailAccountLI(mailAccount, readOnly) {
var li = createElement("li");
li.appendChild(document.createTextNode(mailAccount["name"]));
li.observe("click", onMailAccountEntryClick);
li.observe("mousedown", onRowClick);
if (readOnly) {
li.addClassName("readonly");
}
else {
var editionCtlr = new RowEditionController();
editionCtlr.attachToRowElement(li);
editionCtlr.notifyNewValueCallback = function(ignore, newValue) {
mailAccount["name"] = newValue;
};
li.editionController = editionCtlr;
}
li.mailAccount = mailAccount;
return li;
}
function onMailAccountEntryClick(event) {
displayMailAccount(this.mailAccount, this.readOnly);
}
function displayMailAccount(mailAccount, readOnly) {
var fieldSet = $("accountInfo");
var inputs = fieldSet.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = readOnly;
inputs[i].mailAccount = mailAccount;
}
fieldSet = $("identityInfo");
inputs = fieldSet.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = readOnly;
inputs[i].mailAccount = mailAccount;
}
var form = $("mainForm");
var encryption = "none";
var encRadioValues = [ "none", "ssl", "tls" ];
if (mailAccount["encryption"]) {
encryption = mailAccount["encryption"];
}
form.setRadioValue("encryption", encRadioValues.indexOf(encryption));
var port;
if (mailAccount["port"]) {
port = mailAccount["port"];
}
else {
if (encryption == "ssl") {
port = 993;
}
else {
port = 143;
}
}
$("port").value = port;
$("serverName").value = mailAccount["serverName"];
$("userName").value = mailAccount["userName"];
$("password").value = mailAccount["password"];
var identity = (mailAccount["identities"]
? mailAccount["identities"][0]
: {} );
$("fullName").value = identity["fullName"] || "";
$("email").value = identity["email"] || "";
displayAccountSignature(mailAccount);
var receiptAction = "ignore";
var receiptActionValues = [ "ignore", "allow" ];
if (mailAccount["receipts"] && mailAccount["receipts"]["receiptAction"]) {
receiptAction = mailAccount["receipts"]["receiptAction"];
}
for (var i = 0; i < receiptActionValues.length; i++) {
var keyName = "receipt-action-" + receiptActionValues[i];
var input = $(keyName);
input.mailAccount = mailAccount;
}
form.setRadioValue("receipt-action",
receiptActionValues.indexOf(receiptAction));
var popupIds = [ "receipt-non-recipient-action",
"receipt-outside-domain-action",
"receipt-any-action" ];
var receiptActionsDisable = (receiptAction == "ignore");
for (var i = 0; i < popupIds.length; i++) {
var actionPopup = $(popupIds[i]);
actionPopup.disabled = receiptActionsDisable;
var settingValue = "ignore";
var settingName = popupIds[i].cssIdToHungarianId();
if (mailAccount["receipts"] && mailAccount["receipts"][settingName]) {
settingValue = mailAccount["receipts"][settingName];
}
actionPopup.value = settingValue;
actionPopup.mailAccount = mailAccount;
}
}
function displayAccountSignature(mailAccount) {
var actSignature = $("actSignature");
actSignature.mailAccount = mailAccount;
var actSignatureValue;
var identity = (mailAccount["identities"]
? mailAccount["identities"][0]
: {} );
var value = identity["signature"];
if (value && value.length > 0)
value = value.stripTags().unescapeHTML().replace(/^[ \n\r]*/, "");
if (value && value.length > 0) {
if (value.length < 30) {
actSignatureValue = value;
}
else {
actSignatureValue = value.substr(0, 30) + "...";
}
}
else {
actSignatureValue = _("(Click to create)");
}
while (actSignature.firstChild) {
actSignature.removeChild(actSignature.firstChild);
}
actSignature.update(actSignatureValue);
}
function createMailAccount() {
var firstIdentity = mailAccounts[0]["identities"][0];
var newIdentity = {};
for (var k in firstIdentity) {
newIdentity[k] = firstIdentity[k];
}
delete newIdentity["isDefault"];
var newMailAccount = { name: _("New Mail Account"),
serverName: "mailserver",
userName: UserLogin,
password: "",
identities: [ newIdentity ] };
return newMailAccount;
}
function onMailAccountAdd(event) {
var newMailAccount = createMailAccount();
mailAccounts.push(newMailAccount);
var li = createMailAccountLI(newMailAccount);
var mailAccountsList = $("mailAccountsList");
mailAccountsList.appendChild(li);
var selection = mailAccountsList.getSelectedNodes();
for (var i = 0; i < selection.length; i++) {
selection[i].deselect();
}
displayMailAccount(newMailAccount, false);
li.selectElement();
li.editionController.startEditing();
var hasChanged = $("hasChanged");
hasChanged.value = "1";
event.stop();
}
function onMailAccountDelete(event) {
var mailAccountsList = $("mailAccountsList");
var selection = mailAccountsList.getSelectedNodes();
if (selection.length > 0) {
var li = selection[0];
if (!li.readOnly) {
li.deselect();
li.editionController = null;
var next = li.next();
if (!next) {
next = li.previous();
}
mailAccountsList.removeChild(li);
var index = mailAccounts.indexOf(li.mailAccount);
mailAccounts.splice(index, 1);
next.selectElement();
displayMailAccount(next.mailAccount, next.readOnly);
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
}
event.stop();
}
function saveMailAccounts() {
/* This removal enables us to avoid a few warning from SOPE for the inputs
that were created dynamically. */
var editor = $("mailAccountEditor");
// Could be null if ModuleConstraints disables email access
if (editor)
editor.parentNode.removeChild(editor);
compactMailAccounts();
var mailAccountsJSON = $("mailAccountsJSON");
if (mailAccountsJSON)
mailAccountsJSON.value = Object.toJSON(mailAccounts);
}
function compactMailAccounts() {
if (!mailAccounts)
return;
for (var i = 1; i < mailAccounts.length; i++) {
var account = mailAccounts[i];
var encryption = account["encryption"];
if (encryption) {
if (encryption == "none") {
delete account["encryption"];
}
}
else {
encryption = "none";
}
var port = account["port"];
if (port) {
if ((encryption == "ssl" && port == 993)
|| port == 143) {
delete account["port"];
}
}
}
}
/* calendar categories */
function resetCalendarTableActions() {
var r = $$("#calendarCategoriesListWrapper tbody tr");
for (var i = 0; i < r.length; i++) {
var row = $(r[i]);
row.observe("mousedown", onRowClick);
var tds = row.childElements();
var editionCtlr = new RowEditionController();
editionCtlr.attachToRowElement(tds[0]);
tds[1].childElements()[0].observe("dblclick", onColorEdit);
}
}
function onColorEdit (e) {
var r = $$("#calendarCategoriesListWrapper div.colorEditing");
for (var i=0; i<r.length; i++)
r[i].removeClassName("colorEditing");
this.addClassName ("colorEditing");
var cPicker = window.open(ApplicationBaseURL + "../" + UserLogin
+ "/Calendar/colorPicker", "colorPicker",
"width=250,height=200,resizable=0,scrollbars=0"
+ "toolbar=0,location=0,directories=0,status=0,"
+ "menubar=0,copyhistory=0", "test"
);
cPicker.focus();
preventDefault(e);
}
function onColorPickerChoice (newColor) {
var div = $$("#calendarCategoriesListWrapper div.colorEditing").first ();
// div.removeClassName ("colorEditing");
div.showColor = newColor;
div.style.background = newColor;
if (parseInt($("hasChanged").value) == 0) {
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
}
function onCalendarCategoryAdd (e) {
var row = new Element ("tr");
var nametd = new Element ("td").update ("");
var colortd = new Element ("td");
var colordiv = new Element ("div", {"class": "colorBox"});
row.identify ();
row.addClassName ("categoryListRow");
nametd.addClassName ("categoryListCell");
colortd.addClassName ("categoryListCell");
colordiv.innerHTML = " ";
colordiv.showColor = "#F0F0F0";
colordiv.style.background = colordiv.showColor;
colortd.appendChild (colordiv);
row.appendChild (nametd);
row.appendChild (colortd);
$("calendarCategoriesListWrapper").childNodesWithTag("table")[0].tBodies[0].appendChild (row);
resetCalendarTableActions ();
nametd.editionController.startEditing();
}
function onCalendarCategoryDelete (e) {
var list = $('calendarCategoriesListWrapper').down("TABLE").down("TBODY");
var rows = list.getSelectedNodes();
var count = rows.length;
for (var i=0; i < count; i++) {
rows[i].editionController = null;
rows[i].remove ();
}
}
function serializeCalendarCategories() {
var r = $$("#calendarCategoriesListWrapper TBODY TR");
var values = [];
for (var i = 0; i < r.length; i++) {
var tds = r[i].childElements ();
var name = $(tds.first ()).innerHTML;
var color = $(tds.last ().childElements ().first ()).showColor;
values.push("\"" + name + "\": \"" + color + "\"");
}
$("calendarCategoriesValue").value = "{ " + values.join(",\n") + "}";
}
function resetCalendarCategoriesColors (e) {
var divs = $$("#calendarCategoriesListWrapper DIV.colorBox");
for (var i = 0; i < divs.length; i++) {
var d = divs[i];
var color = d.innerHTML;
d.showColor = color;
if (color != "undefined")
d.setStyle({ backgroundColor: color });
d.update(" ");
}
}
/* /calendar categories */
/* contacts categories */
function resetContactsTableActions() {
var r = $$("#contactsCategoriesListWrapper tbody tr");
for (var i = 0; i < r.length; i++) {
var row = $(r[i]);
row.observe("mousedown", onRowClick);
var tds = row.childElements();
var editionCtlr = new RowEditionController();
editionCtlr.attachToRowElement(tds[0]);
}
}
function onContactsCategoryAdd(e) {
var row = new Element("tr");
row.identify();
row.addClassName("categoryListRow");
var nametd = new Element("td").update("");
nametd.addClassName("categoryListCell");
row.appendChild(nametd);
var list = $('contactsCategoriesListWrapper').down("TABLE").down("TBODY");
list.appendChild(row);
resetContactsTableActions ();
nametd.editionController.startEditing();
}
function onContactsCategoryDelete (e) {
var list = $('contactsCategoriesListWrapper').down("TABLE").down("TBODY");
var rows = list.getSelectedNodes();
var count = rows.length;
for (var i = 0; i < count; i++) {
rows[i].editionController = null;
rows[i].remove();
}
}
function serializeContactsCategories() {
var values = [];
var tds = $$("#contactsCategoriesListWrapper TBODY TD");
for (var i = 0; i < tds.length; i++) {
var td = $(tds[i]);
values.push(td.allTextContent());
}
$("contactsCategoriesValue").value = Object.toJSON(values);
}
/* / contact categories */
function onReplyPlacementListChange() {
// above = 0
if ($("replyPlacementList").value == 0) {
$("signaturePlacementList").disabled=false;
}
else {
$("signaturePlacementList").value=1;
$("signaturePlacementList").disabled=true;
}
}
function onComposeMessagesTypeChange(event) {
// var textArea = $('signature');
if (this.value == 0) /* text */ {
if (CKEDITOR.instances["signature"]) {
var content = CKEDITOR.instances["signature"].getData();
var htmlEditorWidget = $('cke_signature');
htmlEditorWidget.parentNode.removeChild(htmlEditorWidget);
delete CKEDITOR.instances["signature"];
var textArea = $("signature");
textArea.value = content;
textArea.style.display = "";
textArea.style.visibility = "";
}
} else {
if ($("signature") && !CKEDITOR.instances["signature"]) {
CKEDITOR.replace('signature',
{
height: "70px",
toolbar: [['Bold', 'Italic', '-', 'Link',
'Font','FontSize','-','TextColor',
'BGColor']
],
language: localeCode,
scayt_sLang: localeCode
}
);
}
}
}
function onChangePasswordClick(event) {
var field = $("newPasswordField");
var confirmationField = $("newPasswordConfirmationField");
if (field && confirmationField) {
var password = field.value;
if (password == confirmationField.value) {
if (password.length > 0) {
var loginValues = readLoginCookie();
var policy = new PasswordPolicy(loginValues[0],
loginValues[1]);
policy.setCallbacks(onPasswordChangeSuccess,
onPasswordChangeFailure);
policy.changePassword(password);
}
else
SetLogMessage("passwordError", _("Password must not be empty."),
"error");
}
else {
SetLogMessage("passwordError", _("The passwords do not match."
+ " Please try again."),
"error");
field.focus();
field.select();
}
}
event.stop();
}
function onPasswordChangeSuccess(message) {
SetLogMessage("passwordError", message, "info");
}
function onPasswordChangeFailure(code, message) {
SetLogMessage("passwordError", message, "error");
}
document.observe("dom:loaded", initPreferences);
| UI/WebServerResources/UIxPreferences.js | var isSieveScriptsEnabled = false;
var filters = [];
var mailAccounts = null;
var dialogs = {};
function savePreferences(sender) {
var sendForm = true;
var sigList = $("signaturePlacementList");
if (sigList)
sigList.disabled = false;
if ($("calendarCategoriesListWrapper")) {
serializeCalendarCategories();
}
if ($("contactsCategoriesListWrapper")) {
serializeContactsCategories();
}
if ($("dayStartTime")) {
var start = $("dayStartTime");
var selectedStart = parseInt(start.options[start.selectedIndex].value);
var end = $("dayEndTime");
var selectedEnd = parseInt(end.options[end.selectedIndex].value);
if (selectedStart >= selectedEnd) {
showAlertDialog (_("Day start time must be prior to day end time."));
sendForm = false;
}
}
if ($("enableVacation") && $("enableVacation").checked) {
if ($("autoReplyText").value.strip().length == 0
|| $("autoReplyEmailAddresses").value.strip().length == 0) {
showAlertDialog(_("Please specify your message and your email addresses for which you want to enable auto reply."));
sendForm = false;
}
if ($("enableVacationEndDate") && $("enableVacationEndDate").checked) {
var endDate = new Date($("vacationEndDate_date").value);
var now = new Date();
if (endDate.getTime() < now.getTime()) {
showAlertDialog(_("End date of your auto reply must be in the future."));
sendForm = false;
}
}
}
if ($("enableForward") && $("enableForward").checked) {
var addresses = $("forwardAddress").value.split(",");
for (var i = 0; i < addresses.length && sendForm; i++)
if (!emailRE.test(addresses[i].strip())) {
showAlertDialog(_("Please specify an address to which you want to forward your messages."));
sendForm = false;
}
}
if (isSieveScriptsEnabled) {
var jsonFilters = prototypeIfyFilters();
$("sieveFilters").setValue(Object.toJSON(jsonFilters));
}
saveMailAccounts();
if (sendForm)
$("mainForm").submit();
return false;
}
function prototypeIfyFilters() {
var newFilters = $([]);
for (var i = 0; i < filters.length; i++) {
var filter = filters[i];
var newFilter = $({});
newFilter.name = filter.name;
newFilter.match = filter.match;
newFilter.active = filter.active;
if (filter.rules) {
newFilter.rules = $([]);
for (var j = 0; j < filter.rules.length; j++) {
newFilter.rules.push($(filter.rules[j]));
}
}
newFilter.actions = $([]);
for (var j = 0; j < filter.actions.length; j++) {
newFilter.actions.push($(filter.actions[j]));
}
newFilters.push(newFilter);
}
return newFilters;
}
function _setupEvents() {
var widgets = [ "timezone", "shortDateFormat", "longDateFormat",
"timeFormat", "weekStartDay", "dayStartTime", "dayEndTime",
"firstWeek", "messageCheck", "sortByThreads",
"subscribedFoldersOnly", "language", "defaultCalendar",
"enableVacation" ];
for (var i = 0; i < widgets.length; i++) {
var widget = $(widgets[i]);
if (widget) {
widget.observe("change", onChoiceChanged);
}
}
// We check for non-null elements as replyPlacementList and composeMessagesType
// might not be present if ModulesConstraints disable those elements
if ($("replyPlacementList"))
$("replyPlacementList").observe ("change", onReplyPlacementListChange);
if ($("composeMessagesType"))
$("composeMessagesType").observe ("change", onComposeMessagesTypeChange);
// Note: we also monitor changes to the calendar categories.
// See functions endEditable and onColorPickerChoice.
var valueInputs = [ "calendarCategoriesValue", "calendarCategoriesValue" ];
for (var i = 0; i < valueInputs.length; i++) {
var valueInput = $(valueInputs[i]);
if (valueInput)
valueInput.value = "";
}
}
function onChoiceChanged(event) {
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
function addDefaultEmailAddresses(event) {
var defaultAddresses = $("defaultEmailAddresses").value.split(/, */);
var addresses = $("autoReplyEmailAddresses").value.trim();
if (addresses) addresses = addresses.split(/, */);
else addresses = new Array();
defaultAddresses.each(function(adr) {
for (var i = 0; i < addresses.length; i++)
if (adr == addresses[i])
break;
if (i == addresses.length)
addresses.push(adr);
});
$("autoReplyEmailAddresses").value = addresses.join(", ");
event.stop();
}
function initPreferences() {
var tabsContainer = $("preferencesTabs");
var controller = new SOGoTabsController();
controller.attachToTabsContainer(tabsContainer);
var filtersListWrapper = $("filtersListWrapper");
if (filtersListWrapper) {
isSieveScriptsEnabled = true;
}
_setupEvents();
if (typeof (initAdditionalPreferences) != "undefined")
initAdditionalPreferences();
var wrapper = $("calendarCategoriesListWrapper");
if (wrapper) {
var table = wrapper.childNodesWithTag("table")[0];
resetCalendarCategoriesColors(null);
var r = $$("#calendarCategoriesListWrapper tbody tr");
for (var i= 0; i < r.length; i++)
r[i].identify();
table.multiselect = true;
resetCalendarTableActions();
$("calendarCategoryAdd").observe("click", onCalendarCategoryAdd);
$("calendarCategoryDelete").observe("click", onCalendarCategoryDelete);
}
wrapper = $("contactsCategoriesListWrapper");
if (wrapper) {
var table = wrapper.childNodesWithTag("table")[0];
var r = $$("#contactsCategoriesListWrapper tbody tr");
for (var i= 0; i < r.length; i++)
r[i].identify();
table.multiselect = true;
resetContactsTableActions();
$("contactsCategoryAdd").observe("click", onContactsCategoryAdd);
$("contactsCategoryDelete").observe("click", onContactsCategoryDelete);
}
// Disable placement (after) if composing in HTML
if ($("composeMessagesType")) {
if ($("composeMessagesType").value == 1) {
$("replyPlacementList").selectedIndex = 0;
$("replyPlacementList").disabled = 1;
}
onReplyPlacementListChange ();
}
var button = $("addDefaultEmailAddresses");
if (button)
button.observe("click", addDefaultEmailAddresses);
button = $("changePasswordBtn");
if (button)
button.observe("click", onChangePasswordClick);
initSieveFilters();
initMailAccounts();
assignCalendar('vacationEndDate_date');
$("enableVacationEndDate").on("change", function(event) {
if (this.checked)
$("vacationEndDate_date").enable();
else
$("vacationEndDate_date").disable();
});
}
function initSieveFilters() {
var table = $("filtersList");
if (table) {
var filtersValue = $("sieveFilters").getValue();
if (filtersValue && filtersValue.length) {
filters = $(filtersValue.evalJSON(false));
for (var i = 0; i < filters.length; i++) {
appendSieveFilterRow(table, i, filters[i]);
}
}
$("filterAdd").observe("click", onFilterAdd);
$("filterDelete").observe("click", onFilterDelete);
$("filterMoveUp").observe("click", onFilterMoveUp);
$("filterMoveDown").observe("click", onFilterMoveDown);
}
}
function appendSieveFilterRow(filterTable, number, filter) {
var row = createElement("tr");
row.observe("mousedown", onRowClick);
row.observe("dblclick", onFilterEdit.bindAsEventListener(row));
var nameColumn = createElement("td");
nameColumn.appendChild(document.createTextNode(filter["name"]));
row.appendChild(nameColumn);
var activeColumn = createElement("td", null, "activeColumn");
var cb = createElement("input", null, "checkBox",
{ type: "checkbox" },
null, activeColumn);
cb.checked = filter.active;
var bound = onScriptActiveCheck.bindAsEventListener(cb);
cb.observe("click", bound);
row.appendChild(activeColumn);
filterTable.tBodies[0].appendChild(row);
}
function onScriptActiveCheck(event) {
var index = this.parentNode.parentNode.rowIndex - 1;
filters[index].active = this.checked;
}
function updateSieveFilterRow(filterTable, number, filter) {
var row = $(filterTable.tBodies[0].rows[number]);
var columns = row.childNodesWithTag("td");
var nameColumn = columns[0];
while (nameColumn.firstChild) {
nameColumn.removeChild(nameColumn.firstChild);
}
nameColumn.appendChild(document.createTextNode(filter.name));
var activeColumn = columns[1];
var cb = activeColumn.childNodesWithTag("input");
cb[0].checked = filter.active;
}
function _editFilter(filterId) {
var urlstr = ApplicationBaseURL + "editFilter?filter=" + filterId;
var win = window.open(urlstr, "sieve_filter_" + filterId,
"width=560,height=380,resizable=0");
if (win)
win.focus();
}
function onFilterAdd(event) {
_editFilter("new");
event.stop();
}
function onFilterDelete(event) {
var filtersList = $("filtersList").tBodies[0];
var nodes = filtersList.getSelectedNodes();
if (nodes.length > 0) {
var deletedFilters = [];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
deletedFilters.push(node.rowIndex - 1);
}
deletedFilters = deletedFilters.sort(function (x,y) { return x-y; });
var rows = filtersList.rows;
for (var i = 0; i < deletedFilters.length; i++) {
var filterNbr = deletedFilters[i];
filters.splice(filterNbr, 1);
var row = rows[filterNbr];
row.parentNode.removeChild(row);
}
}
event.stop();
}
function onFilterMoveUp(event) {
var filtersList = $("filtersList").tBodies[0];
var nodes = filtersList.getSelectedNodes();
if (nodes.length > 0) {
var node = nodes[0];
var previous = node.previous();
if (previous) {
var count = node.rowIndex - 1;
node.parentNode.removeChild(node);
filtersList.insertBefore(node, previous);
var swapFilter = filters[count];
filters[count] = filters[count - 1];
filters[count - 1] = swapFilter;
}
}
event.stop();
}
function onFilterMoveDown(event) {
var filtersList = $("filtersList").tBodies[0];
var nodes = filtersList.getSelectedNodes();
if (nodes.length > 0) {
var node = nodes[0];
var next = node.next();
if (next) {
var count = node.rowIndex - 1;
filtersList.removeChild(next);
filtersList.insertBefore(next, node);
var swapFilter = filters[count];
filters[count] = filters[count + 1];
filters[count + 1] = swapFilter;
}
}
event.stop();
}
function onFilterEdit(event) {
_editFilter(this.rowIndex - 1);
event.stop();
}
function copyFilter(originalFilter) {
var newFilter = {};
newFilter.name = originalFilter.name;
newFilter.match = originalFilter.match;
newFilter.active = originalFilter.active;
if (originalFilter.rules) {
newFilter.rules = [];
for (var i = 0; i < originalFilter.rules.length; i++) {
newFilter.rules.push(_copyFilterElement(originalFilter.rules[i]));
}
}
newFilter.actions = [];
for (var i = 0; i < originalFilter.actions.length; i++) {
newFilter.actions.push(_copyFilterElement(originalFilter.actions[i]));
}
return newFilter;
}
function _copyFilterElement(filterElement) { /* element = rule or action */
var newElement = {};
for (var k in filterElement) {
var value = filterElement[k];
if (typeof(value) == "string" || typeof(value) == "number") {
newElement[k] = value;
}
}
return newElement;
}
function getSieveCapabilitiesFromEditor() {
return sieveCapabilities;
}
function getFilterFromEditor(filterId) {
return copyFilter(filters[filterId]);
}
function setupMailboxesFromJSON(jsonResponse) {
var responseMboxes = jsonResponse.mailboxes;
userMailboxes = $([]);
for (var i = 0; i < responseMboxes.length; i++) {
var name = responseMboxes[i].path.substr(1);
userMailboxes.push(name);
}
}
function updateFilterFromEditor(filterId, filterJSON) {
var filter = filterJSON.evalJSON();
var sanitized = {};
for (var k in filter) {
if (!(k == "rules" && filter.match == "allmessages")) {
sanitized[k] = filter[k];
}
}
var table = $("filtersList");
if (filterId == "new") {
var newNumber = filters.length;
filters.push(sanitized);
appendSieveFilterRow(table, newNumber, sanitized);
} else {
filters[filterId] = sanitized;
updateSieveFilterRow(table, filterId, sanitized);
}
}
/* mail accounts */
function initMailAccounts() {
var mailAccountsJSON = $("mailAccountsJSON");
mailAccounts = mailAccountsJSON.value.evalJSON();
var mailAccountsList = $("mailAccountsList");
if (mailAccountsList) {
var li = createMailAccountLI(mailAccounts[0], true);
mailAccountsList.appendChild(li);
for (var i = 1; i < mailAccounts.length; i++) {
li = createMailAccountLI(mailAccounts[i]);
mailAccountsList.appendChild(li);
}
var lis = mailAccountsList.childNodesWithTag("li");
lis[0].readOnly = true;
lis[0].selectElement();
var button = $("mailAccountAdd");
if (button) {
button.observe("click", onMailAccountAdd);
}
button = $("mailAccountDelete");
if (button) {
button.observe("click", onMailAccountDelete);
}
}
var info = $("accountInfo");
var inputs = info.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
$(inputs[i]).observe("change", onMailAccountInfoChange);
}
info = $("identityInfo");
inputs = info.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
$(inputs[i]).observe("change", onMailIdentityInfoChange);
}
$("actSignature").observe("click", onMailIdentitySignatureClick);
displayMailAccount(mailAccounts[0], true);
info = $("returnReceiptsInfo");
inputs = info.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
$(inputs[i]).observe("change", onMailReceiptInfoChange);
}
inputs = info.getElementsByTagName("select");
for (var i = 0; i < inputs.length; i++) {
$(inputs[i]).observe("change", onMailReceiptActionChange);
}
}
function onMailAccountInfoChange(event) {
this.mailAccount[this.name] = this.value;
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
function onMailIdentityInfoChange(event) {
if (!this.mailAccount["identities"]) {
this.mailAccount["identities"] = [{}];
}
var identity = this.mailAccount["identities"][0];
identity[this.name] = this.value;
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
function onMailReceiptInfoChange(event) {
if (!this.mailAccount["receipts"]) {
this.mailAccount["receipts"] = {};
}
var keyName = this.name.cssIdToHungarianId();
this.mailAccount["receipts"][keyName] = this.value;
var popupIds = [ "receipt-non-recipient-action",
"receipt-outside-domain-action",
"receipt-any-action" ];
var receiptActionsDisable = (this.value == "ignore");
for (var i = 0; i < popupIds.length; i++) {
var actionPopup = $(popupIds[i]);
actionPopup.disabled = receiptActionsDisable;
}
}
function onMailReceiptActionChange(event) {
if (!this.mailAccount["receipts"]) {
this.mailAccount["receipts"] = {};
}
var keyName = this.name.cssIdToHungarianId();
this.mailAccount["receipts"][keyName] = this.value;
}
function onMailIdentitySignatureClick(event) {
if (!this.readOnly) {
var dialogId = "signatureDialog";
var dialog = dialogs[dialogId];
if (!dialog) {
var label = _("Please enter your signature below:");
var fields = createElement("p");
fields.appendChild(createElement("textarea", "signature"));
fields.appendChild(createElement("br"));
fields.appendChild(createButton("okBtn", _("OK"),
onMailIdentitySignatureOK));
fields.appendChild(createButton("cancelBtn", _("Cancel"),
disposeDialog.bind(document.body, dialogId)));
var dialog = createDialog(dialogId,
_("Signature"),
label,
fields,
"none");
document.body.appendChild(dialog);
dialog.show();
dialogs[dialogId] = dialog;
if ($("composeMessagesType").value != 0) {
CKEDITOR.replace('signature',
{ height: "70px",
toolbar: [['Bold', 'Italic', '-', 'Link',
'Font','FontSize','-','TextColor',
'BGColor']
],
language: localeCode,
scayt_sLang: localeCode });
}
}
dialog.mailAccount = this.mailAccount;
if (!this.mailAccount["identities"]) {
this.mailAccount["identities"] = [{}];
}
var identity = this.mailAccount["identities"][0];
var area = $("signature");
if (typeof(identity["signature"]) != "undefined")
area.value = identity["signature"];
else
area.value = "";
dialog.show();
$("bgDialogDiv").show();
if (!CKEDITOR.instances["signature"])
area.focus();
event.stop();
}
}
function onMailIdentitySignatureOK(event) {
var dialog = $("signatureDialog");
var mailAccount = dialog.mailAccount;
if (!mailAccount["identities"]) {
mailAccount["identities"] = [{}];
}
var identity = mailAccount["identities"][0];
var content = (CKEDITOR.instances["signature"]
? CKEDITOR.instances["signature"].getData()
: $("signature").value);
identity["signature"] = content;
displayAccountSignature(mailAccount);
dialog.hide();
$("bgDialogDiv").hide();
dialog.mailAccount = null;
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
function createMailAccountLI(mailAccount, readOnly) {
var li = createElement("li");
li.appendChild(document.createTextNode(mailAccount["name"]));
li.observe("click", onMailAccountEntryClick);
li.observe("mousedown", onRowClick);
if (readOnly) {
li.addClassName("readonly");
}
else {
var editionCtlr = new RowEditionController();
editionCtlr.attachToRowElement(li);
editionCtlr.notifyNewValueCallback = function(ignore, newValue) {
mailAccount["name"] = newValue;
};
li.editionController = editionCtlr;
}
li.mailAccount = mailAccount;
return li;
}
function onMailAccountEntryClick(event) {
displayMailAccount(this.mailAccount, this.readOnly);
}
function displayMailAccount(mailAccount, readOnly) {
var fieldSet = $("accountInfo");
var inputs = fieldSet.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = readOnly;
inputs[i].mailAccount = mailAccount;
}
fieldSet = $("identityInfo");
inputs = fieldSet.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = readOnly;
inputs[i].mailAccount = mailAccount;
}
var form = $("mainForm");
var encryption = "none";
var encRadioValues = [ "none", "ssl", "tls" ];
if (mailAccount["encryption"]) {
encryption = mailAccount["encryption"];
}
form.setRadioValue("encryption", encRadioValues.indexOf(encryption));
var port;
if (mailAccount["port"]) {
port = mailAccount["port"];
}
else {
if (encryption == "ssl") {
port = 993;
}
else {
port = 143;
}
}
$("port").value = port;
$("serverName").value = mailAccount["serverName"];
$("userName").value = mailAccount["userName"];
$("password").value = mailAccount["password"];
var identity = (mailAccount["identities"]
? mailAccount["identities"][0]
: {} );
$("fullName").value = identity["fullName"] || "";
$("email").value = identity["email"] || "";
displayAccountSignature(mailAccount);
var receiptAction = "ignore";
var receiptActionValues = [ "ignore", "allow" ];
if (mailAccount["receipts"] && mailAccount["receipts"]["receiptAction"]) {
receiptAction = mailAccount["receipts"]["receiptAction"];
}
for (var i = 0; i < receiptActionValues.length; i++) {
var keyName = "receipt-action-" + receiptActionValues[i];
var input = $(keyName);
input.mailAccount = mailAccount;
}
form.setRadioValue("receipt-action",
receiptActionValues.indexOf(receiptAction));
var popupIds = [ "receipt-non-recipient-action",
"receipt-outside-domain-action",
"receipt-any-action" ];
var receiptActionsDisable = (receiptAction == "ignore");
for (var i = 0; i < popupIds.length; i++) {
var actionPopup = $(popupIds[i]);
actionPopup.disabled = receiptActionsDisable;
var settingValue = "ignore";
var settingName = popupIds[i].cssIdToHungarianId();
if (mailAccount["receipts"] && mailAccount["receipts"][settingName]) {
settingValue = mailAccount["receipts"][settingName];
}
actionPopup.value = settingValue;
actionPopup.mailAccount = mailAccount;
}
}
function displayAccountSignature(mailAccount) {
var actSignature = $("actSignature");
actSignature.mailAccount = mailAccount;
var actSignatureValue;
var identity = (mailAccount["identities"]
? mailAccount["identities"][0]
: {} );
var value = identity["signature"];
if (value && value.length > 0)
value = value.stripTags().unescapeHTML().replace(/^[ \n\r]*/, "");
if (value && value.length > 0) {
if (value.length < 30) {
actSignatureValue = value;
}
else {
actSignatureValue = value.substr(0, 30) + "...";
}
}
else {
actSignatureValue = _("(Click to create)");
}
while (actSignature.firstChild) {
actSignature.removeChild(actSignature.firstChild);
}
actSignature.update(actSignatureValue);
}
function createMailAccount() {
var firstIdentity = mailAccounts[0]["identities"][0];
var newIdentity = {};
for (var k in firstIdentity) {
newIdentity[k] = firstIdentity[k];
}
delete newIdentity["isDefault"];
var newMailAccount = { name: _("New Mail Account"),
serverName: "mailserver",
userName: UserLogin,
password: "",
identities: [ newIdentity ] };
return newMailAccount;
}
function onMailAccountAdd(event) {
var newMailAccount = createMailAccount();
mailAccounts.push(newMailAccount);
var li = createMailAccountLI(newMailAccount);
var mailAccountsList = $("mailAccountsList");
mailAccountsList.appendChild(li);
var selection = mailAccountsList.getSelectedNodes();
for (var i = 0; i < selection.length; i++) {
selection[i].deselect();
}
displayMailAccount(newMailAccount, false);
li.selectElement();
li.editionController.startEditing();
var hasChanged = $("hasChanged");
hasChanged.value = "1";
event.stop();
}
function onMailAccountDelete(event) {
var mailAccountsList = $("mailAccountsList");
var selection = mailAccountsList.getSelectedNodes();
if (selection.length > 0) {
var li = selection[0];
if (!li.readOnly) {
li.deselect();
li.editionController = null;
var next = li.next();
if (!next) {
next = li.previous();
}
mailAccountsList.removeChild(li);
var index = mailAccounts.indexOf(li.mailAccount);
mailAccounts.splice(index, 1);
next.selectElement();
displayMailAccount(next.mailAccount, next.readOnly);
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
}
event.stop();
}
function saveMailAccounts() {
/* This removal enables us to avoid a few warning from SOPE for the inputs
that were created dynamically. */
var editor = $("mailAccountEditor");
// Could be null if ModuleConstraints disables email access
if (editor)
editor.parentNode.removeChild(editor);
compactMailAccounts();
var mailAccountsJSON = $("mailAccountsJSON");
if (mailAccountsJSON)
mailAccountsJSON.value = Object.toJSON(mailAccounts);
}
function compactMailAccounts() {
if (!mailAccounts)
return;
for (var i = 1; i < mailAccounts.length; i++) {
var account = mailAccounts[i];
var encryption = account["encryption"];
if (encryption) {
if (encryption == "none") {
delete account["encryption"];
}
}
else {
encryption = "none";
}
var port = account["port"];
if (port) {
if ((encryption == "ssl" && port == 993)
|| port == 143) {
delete account["port"];
}
}
}
}
/* calendar categories */
function resetCalendarTableActions() {
var r = $$("#calendarCategoriesListWrapper tbody tr");
for (var i = 0; i < r.length; i++) {
var row = $(r[i]);
row.observe("mousedown", onRowClick);
var tds = row.childElements();
var editionCtlr = new RowEditionController();
editionCtlr.attachToRowElement(tds[0]);
tds[1].childElements()[0].observe("dblclick", onColorEdit);
}
}
function onColorEdit (e) {
var r = $$("#calendarCategoriesListWrapper div.colorEditing");
for (var i=0; i<r.length; i++)
r[i].removeClassName("colorEditing");
this.addClassName ("colorEditing");
var cPicker = window.open(ApplicationBaseURL + "../" + UserLogin
+ "/Calendar/colorPicker", "colorPicker",
"width=250,height=200,resizable=0,scrollbars=0"
+ "toolbar=0,location=0,directories=0,status=0,"
+ "menubar=0,copyhistory=0", "test"
);
cPicker.focus();
preventDefault(e);
}
function onColorPickerChoice (newColor) {
var div = $$("#calendarCategoriesListWrapper div.colorEditing").first ();
// div.removeClassName ("colorEditing");
div.showColor = newColor;
div.style.background = newColor;
if (parseInt($("hasChanged").value) == 0) {
var hasChanged = $("hasChanged");
hasChanged.value = "1";
}
}
function onCalendarCategoryAdd (e) {
var row = new Element ("tr");
var nametd = new Element ("td").update ("");
var colortd = new Element ("td");
var colordiv = new Element ("div", {"class": "colorBox"});
row.identify ();
row.addClassName ("categoryListRow");
nametd.addClassName ("categoryListCell");
colortd.addClassName ("categoryListCell");
colordiv.innerHTML = " ";
colordiv.showColor = "#F0F0F0";
colordiv.style.background = colordiv.showColor;
colortd.appendChild (colordiv);
row.appendChild (nametd);
row.appendChild (colortd);
$("calendarCategoriesListWrapper").childNodesWithTag("table")[0].tBodies[0].appendChild (row);
resetCalendarTableActions ();
nametd.editionController.startEditing();
}
function onCalendarCategoryDelete (e) {
var list = $('calendarCategoriesListWrapper').down("TABLE").down("TBODY");
var rows = list.getSelectedNodes();
var count = rows.length;
for (var i=0; i < count; i++) {
rows[i].editionController = null;
rows[i].remove ();
}
}
function serializeCalendarCategories() {
var r = $$("#calendarCategoriesListWrapper TBODY TR");
var values = [];
for (var i = 0; i < r.length; i++) {
var tds = r[i].childElements ();
var name = $(tds.first ()).innerHTML;
var color = $(tds.last ().childElements ().first ()).showColor;
values.push("\"" + name + "\": \"" + color + "\"");
}
$("calendarCategoriesValue").value = "{ " + values.join(",\n") + "}";
}
function resetCalendarCategoriesColors (e) {
var divs = $$("#calendarCategoriesListWrapper DIV.colorBox");
for (var i = 0; i < divs.length; i++) {
var d = divs[i];
var color = d.innerHTML;
d.showColor = color;
if (color != "undefined")
d.setStyle({ backgroundColor: color });
d.update(" ");
}
}
/* /calendar categories */
/* contacts categories */
function resetContactsTableActions() {
var r = $$("#contactsCategoriesListWrapper tbody tr");
for (var i = 0; i < r.length; i++) {
var row = $(r[i]);
row.observe("mousedown", onRowClick);
var tds = row.childElements();
var editionCtlr = new RowEditionController();
editionCtlr.attachToRowElement(tds[0]);
}
}
function onContactsCategoryAdd(e) {
var row = new Element("tr");
row.identify();
row.addClassName("categoryListRow");
var nametd = new Element("td").update("");
nametd.addClassName("categoryListCell");
row.appendChild(nametd);
var list = $('contactsCategoriesListWrapper').down("TABLE").down("TBODY");
list.appendChild(row);
resetContactsTableActions ();
nametd.editionController.startEditing();
}
function onContactsCategoryDelete (e) {
var list = $('contactsCategoriesListWrapper').down("TABLE").down("TBODY");
var rows = list.getSelectedNodes();
var count = rows.length;
for (var i = 0; i < count; i++) {
rows[i].editionController = null;
rows[i].remove();
}
}
function serializeContactsCategories() {
var values = [];
var tds = $$("#contactsCategoriesListWrapper TBODY TD");
for (var i = 0; i < tds.length; i++) {
var td = $(tds[i]);
values.push(td.allTextContent());
}
$("contactsCategoriesValue").value = Object.toJSON(values);
}
/* / contact categories */
function onReplyPlacementListChange() {
// above = 0
if ($("replyPlacementList").value == 0) {
$("signaturePlacementList").disabled=false;
}
else {
$("signaturePlacementList").value=1;
$("signaturePlacementList").disabled=true;
}
}
function onComposeMessagesTypeChange(event) {
// var textArea = $('signature');
if (this.value == 0) /* text */ {
if (CKEDITOR.instances["signature"]) {
var content = CKEDITOR.instances["signature"].getData();
var htmlEditorWidget = $('cke_signature');
htmlEditorWidget.parentNode.removeChild(htmlEditorWidget);
delete CKEDITOR.instances["signature"];
var textArea = $("signature");
textArea.value = content;
textArea.style.display = "";
textArea.style.visibility = "";
}
} else {
if ($("signature") && !CKEDITOR.instances["signature"]) {
CKEDITOR.replace('signature',
{
height: "70px",
toolbar: [['Bold', 'Italic', '-', 'Link',
'Font','FontSize','-','TextColor',
'BGColor']
],
language: localeCode,
scayt_sLang: localeCode
}
);
}
}
}
function onChangePasswordClick(event) {
var field = $("newPasswordField");
var confirmationField = $("newPasswordConfirmationField");
if (field && confirmationField) {
var password = field.value;
if (password == confirmationField.value) {
if (password.length > 0) {
var loginValues = readLoginCookie();
var policy = new PasswordPolicy(loginValues[0],
loginValues[1]);
policy.setCallbacks(onPasswordChangeSuccess,
onPasswordChangeFailure);
policy.changePassword(password);
}
else
SetLogMessage("passwordError", _("Password must not be empty."),
"error");
}
else {
SetLogMessage("passwordError", _("The passwords do not match."
+ " Please try again."),
"error");
field.focus();
field.select();
}
}
event.stop();
}
function onPasswordChangeSuccess(message) {
SetLogMessage("passwordError", message, "info");
}
function onPasswordChangeFailure(code, message) {
SetLogMessage("passwordError", message, "error");
}
document.observe("dom:loaded", initPreferences);
|
Monotone-Parent: dc2b5d63bf3592c44b2949f5f4b0b1145256d072
Monotone-Revision: be2355409b08911bf260a0d3ffdfab275fd30725
Monotone-Author: [email protected]
Monotone-Date: 2011-12-08T21:51:28
| UI/WebServerResources/UIxPreferences.js | <ide><path>I/WebServerResources/UIxPreferences.js
<ide> initSieveFilters();
<ide> initMailAccounts();
<ide>
<del> assignCalendar('vacationEndDate_date');
<del> $("enableVacationEndDate").on("change", function(event) {
<del> if (this.checked)
<del> $("vacationEndDate_date").enable();
<del> else
<del> $("vacationEndDate_date").disable();
<del> });
<add> button = $("enableVacationEndDate");
<add> if (button) {
<add> assignCalendar('vacationEndDate_date');
<add> button.on("change", function(event) {
<add> if (this.checked)
<add> $("vacationEndDate_date").enable();
<add> else
<add> $("vacationEndDate_date").disable();
<add> });
<add> }
<ide> }
<ide>
<ide> function initSieveFilters() { |
||
JavaScript | apache-2.0 | c6d901293cee2bc7597d03f8fa8eb06a63874b92 | 0 | ihowarth/MtG-Referee-App,ihowarth/MtG-Referee-App | /***************************************
* Author : Ian & Lewis Howarth
* Project : Magic the Gathering Referee App
* Latest Revision : 12th September 2015
***************************************/
/*
* APP singleton
*/
var APP = {
// Custom recursive function to remove all children of a view and null everything one at a time
releaseAllMemoryOfView : function(view) {
// Getting the chilldren to null, then removing them from the view
var childrenArray = view.getChildren();
view.removeAllChildren();
// Checking if each child has it's own children, recursing the function if they do and nulling them if not
for (var i = 0, iLength = childrenArray.length; i < iLength; i++) {
var secondChildrenArray = childrenArray[i].getChildren();
// If the view contains children put it back into the function, else; kill the the view
if (secondChildrenArray.length > 0) {
APP.releaseAllMemoryOfView(childrenArray[i]);
} else {
childrenArray[i] = null;
}
}
// Finally, null out the view that was passed into the function
view = null;
}
};
/*
* Libraries
*/
/*
* Modules
*/
/*
* Global Variables
*
* Fonts, colors and frquently used sizes etc are saved here so I can easily change the application without having to dive into the code again
*/
// Separating OSs, so we can differentiate the variables needed for them
if (OS_IOS) {
Alloy.Globals.fonts = {
regularFont : "HelveticaNeue",
lightFont : "HelveticaNeue-Light"
};
Alloy.Globals.deviceMeasurements = {
height : Ti.Platform.displayCaps.platformHeight,
width : Ti.Platform.displayCaps.platformWidth,
minusHeight : -Ti.Platform.displayCaps.platformHeight,
minusWidth : -Ti.Platform.displayCaps.platformWidth,
halfWidth : Ti.Platform.displayCaps.platformWidth / 2
};
Alloy.Globals.colors = {
mainWinBackground : "#fff",
defaultBackground : "#ddd",
defaultText : "#000"
};
// ANDROID
} else {
Alloy.Globals.fonts = {
regularFont : "Roboto Regular",
lightFont : "Roboto Light"
};
Alloy.Globals.deviceMeasurements = {
height : 567,
width : 360,
minusHeight : -567,
minusWidth : -360,
halfWidth : 180
};
Alloy.Globals.colors = {
mainWinBackground : "#fff",
defaultBackground : "#ddd",
defaultText : "#000"
};
} | app/alloy.js | /***************************************
* Author : Ian & Lewis Howarth
* Project : Magic the Gathering Referee App
* Latest Revision : 12th September 2015
***************************************/
/*
* APP singleton
*/
var APP = {
// Custom recursive fuinction to remove all children of a view and null everything one at a time
releaseAllMemoryOfView : function( view ) {
// Getting the chilldren to null, then removing them from the view
var childrenArray = view.getChildren();
view.removeAllChildren();
// Checking if each child has it's own children, recursing the function if they do and nulling them if not
for ( var i = 0; i < childrenArray.length; i++) {
var secondChildrenArray = childrenArray[i].getChildren();
if ( secondChildrenArray.length > 0 ) {
for ( var j = 0; j < secondChildrenArray.length; j++ ) {
APP.releaseAllMemoryOfView( secondChildrenArray[j] );
}
} else {
childrenArray[i] = null;
}
}
}
};
/*
* Libraries
*/
/*
* Modules
*/
/*
* Global Variables
*
* Fonts, colors and frquently used sizes etc are saved here so I can easily change the application without having to dive into the code again
*/
// Separating OSs, so we can differentiate the variables needed for them
if ( OS_IOS ) {
Alloy.Globals.fonts = {
regularFont : "HelveticaNeue",
lightFont : "HelveticaNeue-Light"
};
Alloy.Globals.deviceMeasurements = {
height : Ti.Platform.displayCaps.platformHeight,
width : Ti.Platform.displayCaps.platformWidth,
minusHeight : -Ti.Platform.displayCaps.platformHeight,
minusWidth : -Ti.Platform.displayCaps.platformWidth,
halfWidth : Ti.Platform.displayCaps.platformWidth / 2
};
Alloy.Globals.colors = {
mainWinBackground : "#fff",
defaultBackground : "#ddd",
defaultText : "#000"
};
// ANDROID
} else {
Alloy.Globals.fonts = {
regularFont : "Roboto Regular",
lightFont : "Roboto Light"
};
Alloy.Globals.deviceMeasurements = {
height : 567,
width : 360,
minusHeight : -567,
minusWidth : -360,
halfWidth : 180
};
Alloy.Globals.colors = {
mainWinBackground : "#fff",
defaultBackground : "#ddd",
defaultText : "#000"
};
} | Updated releaseAllMemoryOfAView function
| app/alloy.js | Updated releaseAllMemoryOfAView function | <ide><path>pp/alloy.js
<ide> * Latest Revision : 12th September 2015
<ide> ***************************************/
<ide>
<del>
<ide> /*
<ide> * APP singleton
<ide> */
<ide>
<ide> var APP = {
<del> // Custom recursive fuinction to remove all children of a view and null everything one at a time
<del> releaseAllMemoryOfView : function( view ) {
<add> // Custom recursive function to remove all children of a view and null everything one at a time
<add> releaseAllMemoryOfView : function(view) {
<ide> // Getting the chilldren to null, then removing them from the view
<ide> var childrenArray = view.getChildren();
<ide> view.removeAllChildren();
<del>
<add>
<ide> // Checking if each child has it's own children, recursing the function if they do and nulling them if not
<del> for ( var i = 0; i < childrenArray.length; i++) {
<add> for (var i = 0, iLength = childrenArray.length; i < iLength; i++) {
<ide> var secondChildrenArray = childrenArray[i].getChildren();
<ide>
<del> if ( secondChildrenArray.length > 0 ) {
<del> for ( var j = 0; j < secondChildrenArray.length; j++ ) {
<del> APP.releaseAllMemoryOfView( secondChildrenArray[j] );
<del> }
<del>
<add> // If the view contains children put it back into the function, else; kill the the view
<add> if (secondChildrenArray.length > 0) {
<add> APP.releaseAllMemoryOfView(childrenArray[i]);
<add>
<ide> } else {
<ide> childrenArray[i] = null;
<ide> }
<ide> }
<add>
<add> // Finally, null out the view that was passed into the function
<add> view = null;
<ide> }
<ide> };
<ide>
<add>/*
<add>* Libraries
<add>*/
<ide>
<ide> /*
<del> * Libraries
<del> */
<del>
<del>
<add>* Modules
<add>*/
<ide>
<ide> /*
<del> * Modules
<del> */
<del>
<del>
<del>
<del>/*
<del> * Global Variables
<del> *
<del> * Fonts, colors and frquently used sizes etc are saved here so I can easily change the application without having to dive into the code again
<del> */
<add>* Global Variables
<add>*
<add>* Fonts, colors and frquently used sizes etc are saved here so I can easily change the application without having to dive into the code again
<add>*/
<ide>
<ide> // Separating OSs, so we can differentiate the variables needed for them
<del>if ( OS_IOS ) {
<add>if (OS_IOS) {
<ide> Alloy.Globals.fonts = {
<ide> regularFont : "HelveticaNeue",
<del> lightFont : "HelveticaNeue-Light"
<add> lightFont : "HelveticaNeue-Light"
<ide> };
<del>
<add>
<ide> Alloy.Globals.deviceMeasurements = {
<ide> height : Ti.Platform.displayCaps.platformHeight,
<del> width : Ti.Platform.displayCaps.platformWidth,
<del>
<add> width : Ti.Platform.displayCaps.platformWidth,
<add>
<ide> minusHeight : -Ti.Platform.displayCaps.platformHeight,
<ide> minusWidth : -Ti.Platform.displayCaps.platformWidth,
<del>
<add>
<ide> halfWidth : Ti.Platform.displayCaps.platformWidth / 2
<ide> };
<del>
<add>
<ide> Alloy.Globals.colors = {
<ide> mainWinBackground : "#fff",
<ide> defaultBackground : "#ddd",
<del> defaultText : "#000"
<add> defaultText : "#000"
<ide> };
<del>
<del>// ANDROID
<add>
<add> // ANDROID
<ide> } else {
<ide> Alloy.Globals.fonts = {
<ide> regularFont : "Roboto Regular",
<del> lightFont : "Roboto Light"
<add> lightFont : "Roboto Light"
<ide> };
<del>
<add>
<ide> Alloy.Globals.deviceMeasurements = {
<ide> height : 567,
<del> width : 360,
<del>
<add> width : 360,
<add>
<ide> minusHeight : -567,
<del> minusWidth : -360,
<del>
<del> halfWidth : 180
<add> minusWidth : -360,
<add>
<add> halfWidth : 180
<ide> };
<del>
<add>
<ide> Alloy.Globals.colors = {
<ide> mainWinBackground : "#fff",
<ide> defaultBackground : "#ddd",
<del> defaultText : "#000"
<add> defaultText : "#000"
<ide> };
<ide> } |
|
Java | apache-2.0 | 26526b6e644231830dba59de1ba3026aaee0ab2f | 0 | MaltheFriisberg/CiEyeWork,netmelody/ci-eye,MaltheFriisberg/CiEyeWork,MaltheFriisberg/CIE,MaltheFriisberg/CIE,MaltheFriisberg/CiEyeWork,netmelody/ci-eye,MaltheFriisberg/CiEyeWork,netmelody/ci-eye,MaltheFriisberg/CIE,MaltheFriisberg/CIE,netmelody/ci-eye | package org.netmelody.cieye.core.observation;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import static com.google.common.base.Functions.compose;
public final class CodeBook {
private final String username;
private final String password;
private final SimpleDateFormat dateFormat;
private final ImmutableMap<Class<?>, JsonDeserializer<?>> deserialisers;
private final Function<String, String> munger;
public CodeBook() {
this(new SimpleDateFormat());
}
public CodeBook(SimpleDateFormat dateFormat) {
this("", "", dateFormat, Functions.<String>identity(), ImmutableMap.<Class<?>, JsonDeserializer<?>>of());
}
private CodeBook(String username, String password, SimpleDateFormat dateFormat, Function<String, String> munger, ImmutableMap<Class<?>, JsonDeserializer<?>> deserialisers) {
this.username = username;
this.password = password;
this.dateFormat = dateFormat;
this.deserialisers = deserialisers;
this.munger = munger;
}
public CodeBook withCredentials(String name, String pass) {
return new CodeBook(name, pass, this.dateFormat, this.munger, this.deserialisers);
}
public CodeBook withRawContentMunger(Function<String, String> munger) {
return new CodeBook(this.username, this.password, this.dateFormat, compose(munger, this.munger), this.deserialisers);
}
public <T> CodeBook withJsonDeserializerFor(Class<T> type, JsonDeserializer<T> deserialiser) {
return new CodeBook(this.username, this.password, this.dateFormat, this.munger, extend(this.deserialisers, type, deserialiser));
}
public String username() {
return username;
}
public String password() {
return password;
}
public Function<String, String> contentMunger() {
return munger;
}
private static <X, Y> ImmutableMap<X, Y> extend(Map<X, Y> map, X key, Y value) {
return ImmutableMap.<X, Y>builder().putAll(map).put(key, value).build();
}
public Gson decoder() {
final GsonBuilder builder = new GsonBuilder().setDateFormat(dateFormat.toPattern());
for (Entry<Class<?>, JsonDeserializer<?>> entry : this.deserialisers.entrySet()) {
builder.registerTypeAdapter(entry.getKey(), entry.getValue());
}
return builder.create();
}
} | src/main/java/org/netmelody/cieye/core/observation/CodeBook.java | package org.netmelody.cieye.core.observation;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import static com.google.common.base.Functions.compose;
public final class CodeBook {
private final String username;
private final String password;
private final SimpleDateFormat dateFormat;
private final ImmutableMap<Class<?>, JsonDeserializer<?>> deserialisers;
private final Function<String, String> munger;
public CodeBook() {
this(new SimpleDateFormat());
}
public CodeBook(SimpleDateFormat dateFormat) {
this("", "", dateFormat, Functions.<String>identity(), ImmutableMap.<Class<?>, JsonDeserializer<?>>of());
}
private CodeBook(String username, String password, SimpleDateFormat dateFormat, Function<String, String> munger, ImmutableMap<Class<?>, JsonDeserializer<?>> deserialisers) {
this.username = username;
this.password = password;
this.dateFormat = dateFormat;
this.deserialisers = deserialisers;
this.munger = munger;
}
public CodeBook withCredentials(String name, String pass) {
return new CodeBook(name, pass, this.dateFormat, this.munger, this.deserialisers);
}
public CodeBook withRawContentMunger(Function<String, String> munger) {
return new CodeBook(this.username, this.password, this.dateFormat, compose(munger, this.munger), this.deserialisers);
}
public <T> CodeBook withJsonDeserializerFor(Class<T> type, JsonDeserializer<T> deserialiser) {
return new CodeBook(this.username, this.password, this.dateFormat, this.munger, extend(this.deserialisers, type, deserialiser));
}
public String username() {
return username;
}
public String password() {
return password;
}
public SimpleDateFormat dateFormat() {
return dateFormat;
}
public Function<String, String> contentMunger() {
return munger;
}
public Map<Class<?>, JsonDeserializer<?>> deserialisers() {
return this.deserialisers;
}
private static <X, Y> ImmutableMap<X, Y> extend(Map<X, Y> map, X key, Y value) {
return ImmutableMap.<X, Y>builder().putAll(map).put(key, value).build();
}
public Gson decoder() {
final GsonBuilder builder = new GsonBuilder().setDateFormat(dateFormat().toPattern());
for (Entry<Class<?>, JsonDeserializer<?>> entry : deserialisers().entrySet()) {
builder.registerTypeAdapter(entry.getKey(), entry.getValue());
}
return builder.create();
}
} | remove unused methods
| src/main/java/org/netmelody/cieye/core/observation/CodeBook.java | remove unused methods | <ide><path>rc/main/java/org/netmelody/cieye/core/observation/CodeBook.java
<ide> return password;
<ide> }
<ide>
<del> public SimpleDateFormat dateFormat() {
<del> return dateFormat;
<del> }
<del>
<ide> public Function<String, String> contentMunger() {
<ide> return munger;
<del> }
<del>
<del> public Map<Class<?>, JsonDeserializer<?>> deserialisers() {
<del> return this.deserialisers;
<ide> }
<ide>
<ide> private static <X, Y> ImmutableMap<X, Y> extend(Map<X, Y> map, X key, Y value) {
<ide> }
<ide>
<ide> public Gson decoder() {
<del> final GsonBuilder builder = new GsonBuilder().setDateFormat(dateFormat().toPattern());
<add> final GsonBuilder builder = new GsonBuilder().setDateFormat(dateFormat.toPattern());
<ide>
<del> for (Entry<Class<?>, JsonDeserializer<?>> entry : deserialisers().entrySet()) {
<add> for (Entry<Class<?>, JsonDeserializer<?>> entry : this.deserialisers.entrySet()) {
<ide> builder.registerTypeAdapter(entry.getKey(), entry.getValue());
<ide> }
<ide> return builder.create(); |
|
Java | mit | 6a91f5452c8106001b1b32b7be126c145bc86757 | 0 | junwang15/leetcode | /**
* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
* The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
* How many possible unique paths are there?
**/
public class Solution {
// dp solution 1
public int uniquePaths(int m, int n) {
if(m==0 || n==0) return 0;
int[][] paths = new int[m][n];
for(int i=m-1; i>=0; i--)
paths[i][n-1]=1;
for(int j=n-1; j>=0; j--)
paths[m-1][j]=1;
for(int i=m-2; i>=0; i--)
for(int j=n-2; j>=0; j--)
paths[i][j] = paths[i+1][j] + paths[i][j+1];
return paths[0][0];
}
// dp solution 2
public int uniquePaths2(int m, int n) {
if(m < 1 || n < 1)
return 0;
int[] dp = new int[n];
int[] dp_last = new int[n];
for(int i = 0; i < n; i++) {
dp[i] = 1;
dp_last[i] = 1;
}
for(int j = 1; j < m; j++) {
dp[0] = 1;
for(int i = 1; i < n; i++) {
dp[i] = dp[i-1] + dp_last[i];
dp_last[i] = dp[i];
}
}
return dp[n-1];
}
// dfs solution (recursion): Time Limit Exceeded
public int uniquePaths(int m, int n) {
return dfs(0, 0, m, n);
}
private int dfs(int i, int j, int m, int n) {
if(i == m-1 && j == n-1)
return 1;
if(i < m-1 && j < n-1)
return dfs(i+1, j, m, n) + dfs(i, j+1, m, n);
if(i < m-1)
return dfs(i+1, j, m, n);
if(j < n-1)
return dfs(i, j+1, m, n);
return 0;
}
}
| java/062.java | /**
* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
* The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
* How many possible unique paths are there?
**/
public class Solution {
public int uniquePaths(int m, int n) {
if(m==0 || n==0) return 0;
int[][] paths = new int[m][n];
for(int i=m-1; i>=0; i--)
paths[i][n-1]=1;
for(int j=n-1; j>=0; j--)
paths[m-1][j]=1;
for(int i=m-2; i>=0; i--)
for(int j=n-2; j>=0; j--)
paths[i][j] = paths[i+1][j] + paths[i][j+1];
return paths[0][0];
}
}
| Modified 62 Unique Pahts
| java/062.java | Modified 62 Unique Pahts | <ide><path>ava/062.java
<ide> * How many possible unique paths are there?
<ide> **/
<ide> public class Solution {
<add> // dp solution 1
<ide> public int uniquePaths(int m, int n) {
<ide> if(m==0 || n==0) return 0;
<ide>
<ide> paths[i][j] = paths[i+1][j] + paths[i][j+1];
<ide> return paths[0][0];
<ide> }
<add>
<add> // dp solution 2
<add> public int uniquePaths2(int m, int n) {
<add> if(m < 1 || n < 1)
<add> return 0;
<add> int[] dp = new int[n];
<add> int[] dp_last = new int[n];
<add> for(int i = 0; i < n; i++) {
<add> dp[i] = 1;
<add> dp_last[i] = 1;
<add> }
<add> for(int j = 1; j < m; j++) {
<add> dp[0] = 1;
<add> for(int i = 1; i < n; i++) {
<add> dp[i] = dp[i-1] + dp_last[i];
<add> dp_last[i] = dp[i];
<add> }
<add> }
<add> return dp[n-1];
<add> }
<add>
<add> // dfs solution (recursion): Time Limit Exceeded
<add> public int uniquePaths(int m, int n) {
<add> return dfs(0, 0, m, n);
<add> }
<add>
<add> private int dfs(int i, int j, int m, int n) {
<add> if(i == m-1 && j == n-1)
<add> return 1;
<add> if(i < m-1 && j < n-1)
<add> return dfs(i+1, j, m, n) + dfs(i, j+1, m, n);
<add> if(i < m-1)
<add> return dfs(i+1, j, m, n);
<add> if(j < n-1)
<add> return dfs(i, j+1, m, n);
<add> return 0;
<add> }
<ide> } |
|
JavaScript | apache-2.0 | f85b4755fc9442e90875cbffce96e172a7ac5b5a | 0 | MICommunity/ComplexViewer,colin-combe/interaction-viewer,colin-combe/ComplexViewer,MICommunity/ComplexViewer,colin-combe/ComplexViewer,colin-combe/interaction-viewer,colin-combe/MI-model,MICommunity/interaction-viewer,MICommunity/interaction-viewer,colin-combe/MI-model,MICommunity/interaction-viewer,colin-combe/MI-model | // xiNET interaction viewer
// Copyright 2014 Rappsilber Laboratory
//
// This product includes software developed at
// the Rappsilber Laboratory (http://www.rappsilberlab.org/).
//
// author: Colin Combe
"use strict";
// NaryLink.js
// graphically represents an n-ary interaction
NaryLink.naryColours = d3.scale.ordinal().range(colorbrewer.Paired[6]);//d3.scale.category20c();//d3.scale.ordinal().range(colorbrewer.Paired[12]);//
NaryLink.prototype = new xiNET.Link();
function NaryLink(id, xlvController) {
this.id = id;
this.evidences = d3.map();
this.interactors = null;// will be new Array();//need order for binary links so use array
this.subLinks = d3.map();
this.ctrl = xlvController;
//this.ambig = false;
this.tooltip = this.id;
//used to avoid some unnecessary manipulation of DOM
this.shown = false;
//this.thickLineShown = false;
//layout stuff
this.hidden = false;
}
NaryLink.prototype.addEvidence = function(interaction) {
if (this.evidences.has(interaction.id) === false) {
this.evidences.set(interaction.id, interaction);
//~ if (this.evidences.values().length > NaryLink.maxNoEvidences) {//TODO: update d3 lib
//~ xiNET.Link.maxNoEvidences = this.evidences.values().length; //values().length can be replaced with size() in newer d3 lib
//~ }
if (this.interactors === null){
this.initInteractors(interaction);
}
for (var pi = 0; pi < interaction.participants.length; pi++){
var sourceID = interaction.participants[pi].interactorRef;
var sourceInteractor = this.ctrl.interactors.get(sourceID);
var bindingSites = interaction.participants[pi].bindingSites;
if (bindingSites){
var bsCount = bindingSites.length;
for (var bsi = 0; bsi < bsCount; bsi++){
var bindingSite = bindingSites[bsi];
if (bindingSite.linkedFeatures){
for (var fi = 0; fi < bindingSite.linkedFeatures.length; fi++){
var target = this.ctrl.features.get(bindingSite.linkedFeatures[fi]);
var targetInteractor = this.ctrl.interactors.get(target.interactor);
var linkID, fromInteractor, toInteractor;
// these links are undirected and should have same ID regardless of which way round
// source and target are
if (sourceID - 0 < target.interactor - 0) {
linkID = sourceID + '-' + target.interactor;
fromInteractor = sourceInteractor;
toInteractor = targetInteractor;
} else {
linkID = target.interactor + '-' + sourceID;
fromInteractor = targetInteractor;
toInteractor = sourceInteractor;
}
}
var link = this.ctrl.links.get(linkID);
if (typeof link === 'undefined') {
if (fromInteractor === toInteractor){
link = new UnaryLink(linkID, this.ctrl);
fromInteractor.addLink(link);
}else {
link = new BinaryLink(linkID, this.ctrl, fromInteractor,toInteractor);
fromInteractor.addLink(link);
toInteractor.addLink(link);
}
this.ctrl.links.set(linkID, link);
}
this.subLinks.set(linkID, link);
link.addEvidence(interaction);
}
}
}
}
}
};
NaryLink.prototype.initSVG = function() {
this.rect = document.createElementNS(xiNET.svgns, "path");
this.rect.setAttribute('fill', NaryLink.naryColours(this.id));
this.rect.setAttribute('opacity', 0.4);
this.rect.setAttribute('stroke', NaryLink.naryColours(this.id));
this.rect.setAttribute('stroke-linejoin', 'round');
this.rect.setAttribute('stroke-width', 40);
//set the events for it
var self = this;
this.rect.onmousedown = function(evt) {
self.mouseDown(evt);
};
this.rect.onmouseover = function(evt) {
self.mouseOver(evt);
console.log("interactors", this.ctrl);
};
this.rect.onmouseout = function(evt) {
self.mouseOut(evt);
};
this.rect.ontouchstart = function(evt) {
console.log("touchstart");
self.touchStart(evt);
};
};
NaryLink.prototype.showHighlight = function(show) {
//~ if (this.shown) {
//~ //we will iterate through all interactors and sublinks and highlight them
//~ this.highlightInteractors(show);
//~ var subLinks = this.subLinks.values();
//~ for (var s = 0; s < subLinks.length; s++) {
//~ subLinks[s].showHighlight(show);
//~ }
//~ }
};
//~ NaryLink.prototype.getFilteredEvidences = function() {
//~ var seqLinks = this.sequenceLinks.values();
//~ var seqLinkCount = seqLinks.length;
//~ // use map to eliminate duplicates
//~ // (which result from linked features resulting in multiple SequenceLinks for single interaction)
//~ var filteredEvids = d3.map();
//~ for (var i = 0; i < seqLinkCount; i++) {
//~ var seqLink = seqLinks[i];
//~ var seqLinkEvids = seqLink.getFilteredEvidences();
//~ var seqLinkEvidCount = seqLinkEvids.length;
//~ for (var j = 0; j < seqLinkEvidCount; j++) {
//~ filteredEvids.set(seqLinkEvids[j].identifiers[0].db + seqLinkEvids[j].identifiers[0].id, seqLinkEvids[j]);
//~ }
//~ }
//~ return filteredEvids.values();
//~ };
NaryLink.prototype.check = function() {
//~ var seqLinks = this.sequenceLinks.values();
//~ var seqLinkCount = seqLinks.length;
// if either end of interaction is 'parked', i.e. greyed out,
// or self-interactors are hidden and this is self interactor
// or this specific link is hidden
//~ if (this.fromInteractor.isParked || this.toInteractor.isParked
//~ || (this.ctrl.intraHidden && this.intra)
//~ || this.hidden) {
//~ //if both ends are blobs then hide interactor-level link
//~ if (this.fromInteractor.form === 0 && this.toInteractor.form === 0) {
//~ this.hide();
//~ }
//~ //else loop through linked features hiding them
//~ else {
//~ for (var i = 0; i < seqLinkCount; i++) {
//~ seqLinks[i].hide();
//~ }
//~ }
//~ return false;
//~ }
//~ else // we need to check which interaction evidences match the filter criteria
//~ if (this.fromInteractor.form === 0 && this.toInteractor.form === 0) {
//~ this.ambig = true;
//~ var filteredEvids = this.getFilteredEvidences();
//~ var evidCount = filteredEvids.length;
//~ for (var i = 0; i < evidCount; i++) {
//~ var evid = filteredEvids[i];
//~ if (typeof evid.expansion === 'undefined') {
//~ this.ambig = false;
//~ }
//~ }
//~ if (evidCount > 0) {
//~ //tooltip
//~ this.tooltip = /*this.id + ', ' +*/ evidCount + ' experiment';
//~ if (evidCount > 1) {
//~ this.tooltip += 's';
//~ }
//~ this.tooltip += ' (';
//~ var nested_data = d3.nest()
//~ .key(function(d) {
//~ return d.experiment.detmethod.name;
//~ })
//~ .rollup(function(leaves) {
//~ return leaves.length;
//~ })
//~ .entries(filteredEvids);
//~
//~ nested_data.sort(function(a, b) {
//~ return b.values - a.values
//~ });
//~ var countDetMethods = nested_data.length
//~ for (var i = 0; i < countDetMethods; i++) {
//~ if (i > 0) {
//~ this.tooltip += ', ';
//~ }
//~ this.tooltip += nested_data[i].values + ' ' + nested_data[i].key;
//~ }
//~ this.tooltip += ' )';
//~ //thickLine
//~ if (evidCount > 1) {
//~ this.thickLineShown = true
//~ this.w = evidCount * (45 / NaryLink.maxNoEvidences);
//~ }
//~ else {
//~ // this.thickLineShown = false;//hack
//~ this.w = evidCount * (45 / NaryLink.maxNoEvidences);//hack
//~ }
//~ //ambig?
//~ this.dashedLine(this.ambig);
//sequence links will have been hidden previously
this.show();
return true;
//~ }
//~ else {
//~ this.hide();
//~ return false;
//~ }
//~ }
//~ else {//at least one end was in stick form
//~ this.hide();
//~ var showedResResLink = false
//~ for (var rl = 0; rl < seqLinkCount; rl++) {
//~ if (seqLinks[rl].check() === true) {
//~ showedResResLink = true;
//~ }
//~ }
//~ return showedResResLink;
//~ }
};
NaryLink.prototype.show = function() {
if (this.ctrl.initComplete) {
if (!this.shown) {
this.shown = true;
if (typeof this.rect === 'undefined') {
this.initSVG();
}
// this.rect.setAttribute("stroke-width", this.ctrl.z * 1);
this.setLinkCoordinates();
this.ctrl.naryLinks.appendChild(this.rect);
}
}
};
NaryLink.prototype.hide = function() {
//~ if (this.shown) {
//~ this.shown = false;
//~ if (this.thickLineShown) {
//~ this.ctrl.p_pLinksWide.removeChild(this.thickLine);
//~ }
//this.ctrl.highlights.removeChild(this.highlightLine);
//~ this.ctrl.p_pLinks.removeChild(this.rect);
//~ }
};
// Uses d3.geom.hull to calculate a path's move-to points based on an array of vertices.
var hullPath = function(values) {
// d3.geom.hull fails when values aren't perfect ([0,0] vertices, or less than three nodes)
// TODO: Figure out a better way than try catching!
var returnval = null;
try {
var calced = d3.geom.hull(values);
returnval = "M" + calced.join("L") + "Z";
} catch(err) {
return null
}
return returnval;
};
NaryLink.prototype.setLinkCoordinates = function(interactor) {
if (this.shown) {//don't waste time changing DOM if link not visible
var northerly = null, southerly = null,
westerly = null, easterly = null; //bounding interactors
var interactors = this.interactors;
var mapped = interactors.map(function(i) {
return [i.x, i.y];
});
var hullValues = hullPath(mapped);
this.rect.setAttribute('d',hullValues);
}
};
| js/model/link/NaryLink.js | // xiNET interaction viewer
// Copyright 2014 Rappsilber Laboratory
//
// This product includes software developed at
// the Rappsilber Laboratory (http://www.rappsilberlab.org/).
//
// author: Colin Combe
"use strict";
// NaryLink.js
// graphically represents an n-ary interaction
NaryLink.naryColours = d3.scale.ordinal().range(colorbrewer.Paired[6]);//d3.scale.category20c();//d3.scale.ordinal().range(colorbrewer.Paired[12]);//
NaryLink.prototype = new xiNET.Link();
function NaryLink(id, xlvController) {
this.id = id;
this.evidences = d3.map();
this.interactors = null;// will be new Array();//need order for binary links so use array
this.subLinks = d3.map();
this.ctrl = xlvController;
//this.ambig = false;
this.tooltip = this.id;
//used to avoid some unnecessary manipulation of DOM
this.shown = false;
//this.thickLineShown = false;
//layout stuff
this.hidden = false;
}
NaryLink.prototype.addEvidence = function(interaction) {
if (this.evidences.has(interaction.id) === false) {
this.evidences.set(interaction.id, interaction);
//~ if (this.evidences.values().length > NaryLink.maxNoEvidences) {//TODO: update d3 lib
//~ xiNET.Link.maxNoEvidences = this.evidences.values().length; //values().length can be replaced with size() in newer d3 lib
//~ }
if (this.interactors === null){
this.initInteractors(interaction);
}
for (var pi = 0; pi < interaction.participants.length; pi++){
var sourceID = interaction.participants[pi].interactorRef;
var sourceInteractor = this.ctrl.interactors.get(sourceID);
var bindingSites = interaction.participants[pi].bindingSites;
if (bindingSites){
var bsCount = bindingSites.length;
for (var bsi = 0; bsi < bsCount; bsi++){
var bindingSite = bindingSites[bsi];
if (bindingSite.linkedFeatures){
for (var fi = 0; fi < bindingSite.linkedFeatures.length; fi++){
var target = this.ctrl.features.get(bindingSite.linkedFeatures[fi]);
var targetInteractor = this.ctrl.interactors.get(target.interactor);
var linkID, fromInteractor, toInteractor;
// these links are undirected and should have same ID regardless of which way round
// source and target are
if (sourceID - 0 < target.interactor - 0) {
linkID = sourceID + '-' + target.interactor;
fromInteractor = sourceInteractor;
toInteractor = targetInteractor;
} else {
linkID = target.interactor + '-' + sourceID;
fromInteractor = targetInteractor;
toInteractor = sourceInteractor;
}
}
var link = this.ctrl.links.get(linkID);
if (typeof link === 'undefined') {
if (fromInteractor === toInteractor){
link = new UnaryLink(linkID, this.ctrl);
fromInteractor.addLink(link);
}else {
link = new BinaryLink(linkID, this.ctrl, fromInteractor,toInteractor);
fromInteractor.addLink(link);
toInteractor.addLink(link);
}
this.ctrl.links.set(linkID, link);
}
this.subLinks.set(linkID, link);
link.addEvidence(interaction);
}
}
}
}
}
};
NaryLink.prototype.initSVG = function() {
this.rect = document.createElementNS(xiNET.svgns, "rect");
this.rect.setAttribute('fill', NaryLink.naryColours(this.id));
this.rect.setAttribute('opacity', 0.4);
this.rect.setAttribute('rx', '30');
this.rect.setAttribute('ry', '30');
//set the events for it
var self = this;
this.rect.onmousedown = function(evt) {
self.mouseDown(evt);
};
this.rect.onmouseover = function(evt) {
self.mouseOver(evt);
};
this.rect.onmouseout = function(evt) {
self.mouseOut(evt);
};
this.rect.ontouchstart = function(evt) {
self.touchStart(evt);
};
};
NaryLink.prototype.showHighlight = function(show) {
//~ if (this.shown) {
//~ //we will iterate through all interactors and sublinks and highlight them
//~ this.highlightInteractors(show);
//~ var subLinks = this.subLinks.values();
//~ for (var s = 0; s < subLinks.length; s++) {
//~ subLinks[s].showHighlight(show);
//~ }
//~ }
};
//~ NaryLink.prototype.getFilteredEvidences = function() {
//~ var seqLinks = this.sequenceLinks.values();
//~ var seqLinkCount = seqLinks.length;
//~ // use map to eliminate duplicates
//~ // (which result from linked features resulting in multiple SequenceLinks for single interaction)
//~ var filteredEvids = d3.map();
//~ for (var i = 0; i < seqLinkCount; i++) {
//~ var seqLink = seqLinks[i];
//~ var seqLinkEvids = seqLink.getFilteredEvidences();
//~ var seqLinkEvidCount = seqLinkEvids.length;
//~ for (var j = 0; j < seqLinkEvidCount; j++) {
//~ filteredEvids.set(seqLinkEvids[j].identifiers[0].db + seqLinkEvids[j].identifiers[0].id, seqLinkEvids[j]);
//~ }
//~ }
//~ return filteredEvids.values();
//~ };
NaryLink.prototype.check = function() {
//~ var seqLinks = this.sequenceLinks.values();
//~ var seqLinkCount = seqLinks.length;
// if either end of interaction is 'parked', i.e. greyed out,
// or self-interactors are hidden and this is self interactor
// or this specific link is hidden
//~ if (this.fromInteractor.isParked || this.toInteractor.isParked
//~ || (this.ctrl.intraHidden && this.intra)
//~ || this.hidden) {
//~ //if both ends are blobs then hide interactor-level link
//~ if (this.fromInteractor.form === 0 && this.toInteractor.form === 0) {
//~ this.hide();
//~ }
//~ //else loop through linked features hiding them
//~ else {
//~ for (var i = 0; i < seqLinkCount; i++) {
//~ seqLinks[i].hide();
//~ }
//~ }
//~ return false;
//~ }
//~ else // we need to check which interaction evidences match the filter criteria
//~ if (this.fromInteractor.form === 0 && this.toInteractor.form === 0) {
//~ this.ambig = true;
//~ var filteredEvids = this.getFilteredEvidences();
//~ var evidCount = filteredEvids.length;
//~ for (var i = 0; i < evidCount; i++) {
//~ var evid = filteredEvids[i];
//~ if (typeof evid.expansion === 'undefined') {
//~ this.ambig = false;
//~ }
//~ }
//~ if (evidCount > 0) {
//~ //tooltip
//~ this.tooltip = /*this.id + ', ' +*/ evidCount + ' experiment';
//~ if (evidCount > 1) {
//~ this.tooltip += 's';
//~ }
//~ this.tooltip += ' (';
//~ var nested_data = d3.nest()
//~ .key(function(d) {
//~ return d.experiment.detmethod.name;
//~ })
//~ .rollup(function(leaves) {
//~ return leaves.length;
//~ })
//~ .entries(filteredEvids);
//~
//~ nested_data.sort(function(a, b) {
//~ return b.values - a.values
//~ });
//~ var countDetMethods = nested_data.length
//~ for (var i = 0; i < countDetMethods; i++) {
//~ if (i > 0) {
//~ this.tooltip += ', ';
//~ }
//~ this.tooltip += nested_data[i].values + ' ' + nested_data[i].key;
//~ }
//~ this.tooltip += ' )';
//~ //thickLine
//~ if (evidCount > 1) {
//~ this.thickLineShown = true
//~ this.w = evidCount * (45 / NaryLink.maxNoEvidences);
//~ }
//~ else {
//~ // this.thickLineShown = false;//hack
//~ this.w = evidCount * (45 / NaryLink.maxNoEvidences);//hack
//~ }
//~ //ambig?
//~ this.dashedLine(this.ambig);
//sequence links will have been hidden previously
this.show();
return true;
//~ }
//~ else {
//~ this.hide();
//~ return false;
//~ }
//~ }
//~ else {//at least one end was in stick form
//~ this.hide();
//~ var showedResResLink = false
//~ for (var rl = 0; rl < seqLinkCount; rl++) {
//~ if (seqLinks[rl].check() === true) {
//~ showedResResLink = true;
//~ }
//~ }
//~ return showedResResLink;
//~ }
};
NaryLink.prototype.show = function() {
if (this.ctrl.initComplete) {
if (!this.shown) {
this.shown = true;
if (typeof this.rect === 'undefined') {
this.initSVG();
}
this.rect.setAttribute("stroke-width", this.ctrl.z * 1);
this.setLinkCoordinates();
this.ctrl.naryLinks.appendChild(this.rect);
}
}
};
NaryLink.prototype.hide = function() {
//~ if (this.shown) {
//~ this.shown = false;
//~ if (this.thickLineShown) {
//~ this.ctrl.p_pLinksWide.removeChild(this.thickLine);
//~ }
//this.ctrl.highlights.removeChild(this.highlightLine);
//~ this.ctrl.p_pLinks.removeChild(this.rect);
//~ }
};
NaryLink.prototype.setLinkCoordinates = function(interactor) {
if (this.shown) {//don't waste time changing DOM if link not visible
var northerly = null, southerly = null,
westerly = null, easterly = null; //bounding interactors
var interactors = this.interactors;
var iCount = interactors.length;
for (var i = 0; i < iCount; i++){
var interactor = interactors[i];
if (westerly === null || interactor.x < westerly.x) {
westerly = interactor;
}
if (easterly === null || interactor.x > easterly.x) {
easterly = interactor;
}
if (southerly === null || interactor.y > southerly.y) {
southerly = interactor;
}
if (northerly === null || interactor.y < northerly.y) {
northerly = interactor;
}
}
//~ console.debug(this.id + "\t" + this.interactors.length)
this.rect.setAttribute('x',westerly.x - 20);
this.rect.setAttribute('y',northerly.y - 20);
this.rect.setAttribute('width',(easterly.x - westerly.x) + 40);
this.rect.setAttribute('height',(southerly.y - northerly.y) + 40);
}
};
| Converted NaryLink link backgrounds to paths to consume less screen space.
| js/model/link/NaryLink.js | Converted NaryLink link backgrounds to paths to consume less screen space. | <ide><path>s/model/link/NaryLink.js
<del>// xiNET interaction viewer
<del>// Copyright 2014 Rappsilber Laboratory
<add>// xiNET interaction viewer
<add>// Copyright 2014 Rappsilber Laboratory
<ide> //
<del>// This product includes software developed at
<del>// the Rappsilber Laboratory (http://www.rappsilberlab.org/).
<add>// This product includes software developed at
<add>// the Rappsilber Laboratory (http://www.rappsilberlab.org/).
<ide> //
<del>// author: Colin Combe
<add>// author: Colin Combe
<ide>
<ide> "use strict";
<ide>
<ide> }
<ide>
<ide> NaryLink.prototype.addEvidence = function(interaction) {
<del> if (this.evidences.has(interaction.id) === false) {
<del> this.evidences.set(interaction.id, interaction);
<add> if (this.evidences.has(interaction.id) === false) {
<add> this.evidences.set(interaction.id, interaction);
<ide>
<del> //~ if (this.evidences.values().length > NaryLink.maxNoEvidences) {//TODO: update d3 lib
<del> //~ xiNET.Link.maxNoEvidences = this.evidences.values().length; //values().length can be replaced with size() in newer d3 lib
<del> //~ }
<del>
<del> if (this.interactors === null){
<del> this.initInteractors(interaction);
<del> }
<del>
<del> for (var pi = 0; pi < interaction.participants.length; pi++){
<del> var sourceID = interaction.participants[pi].interactorRef;
<del> var sourceInteractor = this.ctrl.interactors.get(sourceID);
<del>
<del> var bindingSites = interaction.participants[pi].bindingSites;
<del> if (bindingSites){
<del> var bsCount = bindingSites.length;
<del> for (var bsi = 0; bsi < bsCount; bsi++){
<del>
<del> var bindingSite = bindingSites[bsi];
<del> if (bindingSite.linkedFeatures){
<del> for (var fi = 0; fi < bindingSite.linkedFeatures.length; fi++){
<del> var target = this.ctrl.features.get(bindingSite.linkedFeatures[fi]);
<del> var targetInteractor = this.ctrl.interactors.get(target.interactor);
<del> var linkID, fromInteractor, toInteractor;
<del> // these links are undirected and should have same ID regardless of which way round
<del> // source and target are
<del> if (sourceID - 0 < target.interactor - 0) {
<del> linkID = sourceID + '-' + target.interactor;
<del> fromInteractor = sourceInteractor;
<del> toInteractor = targetInteractor;
<del> } else {
<del> linkID = target.interactor + '-' + sourceID;
<del> fromInteractor = targetInteractor;
<del> toInteractor = sourceInteractor;
<del> }
<del>
<del> }
<del>
<del> var link = this.ctrl.links.get(linkID);
<del> if (typeof link === 'undefined') {
<del> if (fromInteractor === toInteractor){
<del> link = new UnaryLink(linkID, this.ctrl);
<del> fromInteractor.addLink(link);
<del> }else {
<del> link = new BinaryLink(linkID, this.ctrl, fromInteractor,toInteractor);
<del> fromInteractor.addLink(link);
<del> toInteractor.addLink(link);
<del> }
<del> this.ctrl.links.set(linkID, link);
<del> }
<del> this.subLinks.set(linkID, link);
<del> link.addEvidence(interaction);
<del> }
<del> }
<del> }
<del> }
<del> }
<add> //~ if (this.evidences.values().length > NaryLink.maxNoEvidences) {//TODO: update d3 lib
<add> //~ xiNET.Link.maxNoEvidences = this.evidences.values().length; //values().length can be replaced with size() in newer d3 lib
<add> //~ }
<add>
<add> if (this.interactors === null){
<add> this.initInteractors(interaction);
<add> }
<add>
<add> for (var pi = 0; pi < interaction.participants.length; pi++){
<add> var sourceID = interaction.participants[pi].interactorRef;
<add> var sourceInteractor = this.ctrl.interactors.get(sourceID);
<add>
<add> var bindingSites = interaction.participants[pi].bindingSites;
<add> if (bindingSites){
<add> var bsCount = bindingSites.length;
<add> for (var bsi = 0; bsi < bsCount; bsi++){
<add>
<add> var bindingSite = bindingSites[bsi];
<add> if (bindingSite.linkedFeatures){
<add> for (var fi = 0; fi < bindingSite.linkedFeatures.length; fi++){
<add> var target = this.ctrl.features.get(bindingSite.linkedFeatures[fi]);
<add> var targetInteractor = this.ctrl.interactors.get(target.interactor);
<add> var linkID, fromInteractor, toInteractor;
<add> // these links are undirected and should have same ID regardless of which way round
<add> // source and target are
<add> if (sourceID - 0 < target.interactor - 0) {
<add> linkID = sourceID + '-' + target.interactor;
<add> fromInteractor = sourceInteractor;
<add> toInteractor = targetInteractor;
<add> } else {
<add> linkID = target.interactor + '-' + sourceID;
<add> fromInteractor = targetInteractor;
<add> toInteractor = sourceInteractor;
<add> }
<add>
<add> }
<add>
<add> var link = this.ctrl.links.get(linkID);
<add> if (typeof link === 'undefined') {
<add> if (fromInteractor === toInteractor){
<add> link = new UnaryLink(linkID, this.ctrl);
<add> fromInteractor.addLink(link);
<add> }else {
<add> link = new BinaryLink(linkID, this.ctrl, fromInteractor,toInteractor);
<add> fromInteractor.addLink(link);
<add> toInteractor.addLink(link);
<add> }
<add> this.ctrl.links.set(linkID, link);
<add> }
<add> this.subLinks.set(linkID, link);
<add> link.addEvidence(interaction);
<add> }
<add> }
<add> }
<add> }
<add> }
<ide> };
<ide>
<ide> NaryLink.prototype.initSVG = function() {
<del> this.rect = document.createElementNS(xiNET.svgns, "rect");
<del> this.rect.setAttribute('fill', NaryLink.naryColours(this.id));
<del> this.rect.setAttribute('opacity', 0.4);
<del> this.rect.setAttribute('rx', '30');
<del> this.rect.setAttribute('ry', '30');
<add>
<add> this.rect = document.createElementNS(xiNET.svgns, "path");
<add> this.rect.setAttribute('fill', NaryLink.naryColours(this.id));
<add> this.rect.setAttribute('opacity', 0.4);
<add> this.rect.setAttribute('stroke', NaryLink.naryColours(this.id));
<add> this.rect.setAttribute('stroke-linejoin', 'round');
<add> this.rect.setAttribute('stroke-width', 40);
<add>
<ide> //set the events for it
<ide> var self = this;
<ide> this.rect.onmousedown = function(evt) {
<ide> };
<ide> this.rect.onmouseover = function(evt) {
<ide> self.mouseOver(evt);
<add> console.log("interactors", this.ctrl);
<ide> };
<ide> this.rect.onmouseout = function(evt) {
<ide> self.mouseOut(evt);
<ide> };
<ide> this.rect.ontouchstart = function(evt) {
<add> console.log("touchstart");
<ide> self.touchStart(evt);
<ide> };
<ide> };
<ide>
<ide> NaryLink.prototype.showHighlight = function(show) {
<del> //~ if (this.shown) {
<del> //~ //we will iterate through all interactors and sublinks and highlight them
<del> //~ this.highlightInteractors(show);
<del> //~ var subLinks = this.subLinks.values();
<del> //~ for (var s = 0; s < subLinks.length; s++) {
<del> //~ subLinks[s].showHighlight(show);
<del> //~ }
<del> //~ }
<add> //~ if (this.shown) {
<add> //~ //we will iterate through all interactors and sublinks and highlight them
<add> //~ this.highlightInteractors(show);
<add> //~ var subLinks = this.subLinks.values();
<add> //~ for (var s = 0; s < subLinks.length; s++) {
<add> //~ subLinks[s].showHighlight(show);
<add> //~ }
<add> //~ }
<ide> };
<ide>
<ide>
<ide>
<ide> NaryLink.prototype.check = function() {
<ide>
<del>
<add>
<ide> //~ var seqLinks = this.sequenceLinks.values();
<ide> //~ var seqLinkCount = seqLinks.length;
<ide> // if either end of interaction is 'parked', i.e. greyed out,
<ide> if (typeof this.rect === 'undefined') {
<ide> this.initSVG();
<ide> }
<del> this.rect.setAttribute("stroke-width", this.ctrl.z * 1);
<del> this.setLinkCoordinates();
<del> this.ctrl.naryLinks.appendChild(this.rect);
<del> }
<add> // this.rect.setAttribute("stroke-width", this.ctrl.z * 1);
<add> this.setLinkCoordinates();
<add> this.ctrl.naryLinks.appendChild(this.rect);
<add> }
<ide> }
<ide> };
<ide>
<ide> NaryLink.prototype.hide = function() {
<ide> //~ if (this.shown) {
<ide> //~ this.shown = false;
<del> //~ if (this.thickLineShown) {
<del> //~ this.ctrl.p_pLinksWide.removeChild(this.thickLine);
<del> //~ }
<del> //this.ctrl.highlights.removeChild(this.highlightLine);
<del> //~ this.ctrl.p_pLinks.removeChild(this.rect);
<del> //~ }
<add> //~ if (this.thickLineShown) {
<add> //~ this.ctrl.p_pLinksWide.removeChild(this.thickLine);
<add> //~ }
<add> //this.ctrl.highlights.removeChild(this.highlightLine);
<add> //~ this.ctrl.p_pLinks.removeChild(this.rect);
<add> //~ }
<add>};
<add>
<add>
<add>// Uses d3.geom.hull to calculate a path's move-to points based on an array of vertices.
<add>var hullPath = function(values) {
<add> // d3.geom.hull fails when values aren't perfect ([0,0] vertices, or less than three nodes)
<add> // TODO: Figure out a better way than try catching!
<add> var returnval = null;
<add>
<add> try {
<add> var calced = d3.geom.hull(values);
<add> returnval = "M" + calced.join("L") + "Z";
<add> } catch(err) {
<add> return null
<add> }
<add>
<add> return returnval;
<ide> };
<ide>
<ide> NaryLink.prototype.setLinkCoordinates = function(interactor) {
<add>
<ide> if (this.shown) {//don't waste time changing DOM if link not visible
<del> var northerly = null, southerly = null,
<del> westerly = null, easterly = null; //bounding interactors
<del> var interactors = this.interactors;
<del> var iCount = interactors.length;
<del> for (var i = 0; i < iCount; i++){
<del> var interactor = interactors[i];
<del>
<del> if (westerly === null || interactor.x < westerly.x) {
<del> westerly = interactor;
<del> }
<del>
<del> if (easterly === null || interactor.x > easterly.x) {
<del> easterly = interactor;
<del> }
<del>
<del> if (southerly === null || interactor.y > southerly.y) {
<del> southerly = interactor;
<del> }
<del>
<del> if (northerly === null || interactor.y < northerly.y) {
<del> northerly = interactor;
<del> }
<del> }
<del> //~ console.debug(this.id + "\t" + this.interactors.length)
<del> this.rect.setAttribute('x',westerly.x - 20);
<del> this.rect.setAttribute('y',northerly.y - 20);
<del> this.rect.setAttribute('width',(easterly.x - westerly.x) + 40);
<del> this.rect.setAttribute('height',(southerly.y - northerly.y) + 40);
<add> var northerly = null, southerly = null,
<add> westerly = null, easterly = null; //bounding interactors
<add>
<add> var interactors = this.interactors;
<add>
<add> var mapped = interactors.map(function(i) {
<add> return [i.x, i.y];
<add> });
<add>
<add> var hullValues = hullPath(mapped);
<add> this.rect.setAttribute('d',hullValues);
<ide> }
<ide> }; |
|
Java | mit | 8d39979c191f7c37841fcf6765393da33e094328 | 0 | rayjun/awesome-algorithm,rayjun/awesome-algorithm | import Leetcode24.ListNode;
/**
* Leetcode147
*/
public class Leetcode147 {
public ListNode insertionSortList(ListNode head) {
ListNode p = new ListNode(Integer.MIN_VALUE);
p.next = head;
head = p;
ListNode begin = head; // 有序序列的开头
ListNode index = head; // 有序序列的结尾
p = head.next;
while (p != null) {
ListNode i = head;
// 在没有遍历到有序序列结尾的情况下继续比较
while (i != index && begin.next != null) {
if (p.val < begin.next.val) { // 找到位置,插入
index.next = p.next;
p.next = begin.next;
begin.next = p;
p = index.next;
begin = head;
break;
} else { // 没有找到位置,继续遍历
begin = begin.next;
i = i.next;
}
}
if (i == index) {
p = p.next;
index = index.next;
begin = head;
}
}
return head.next;
}
public static void main(String[] args) {
Leetcode147 leetcode147 = new Leetcode147();
ListNode head = new ListNode(3);
ListNode node2 = new ListNode(4);
ListNode node3 = new ListNode(1);
/*
ListNode head = new ListNode(4);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(1);
ListNode node4 = new ListNode(3);
*/
/*
ListNode head = new ListNode(-1);
ListNode node2 = new ListNode(5);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(0);
*/
head.next = node2;
node2.next = node3;
/*
node3.next = node4;
node4.next = node5;
*/
head = leetcode147.insertionSortList(head);
ListNode p = head;
while (p != null) {
System.out.print(p.val + " ");
p = p.next;
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
} | leetcode/linkedlist/Leetcode147.java | import Leetcode24.ListNode;
/**
* Leetcode147
*/
public class Leetcode147 {
public ListNode insertionSortList(ListNode head) {
ListNode p = new ListNode(Integer.MIN_VALUE);
p.next = head;
head = p;
ListNode begin = head; // 有序序列的开头
ListNode index = head; // 有序序列的结尾
p = head.next;
while(p != null) {
ListNode i = head;
// 在没有遍历到有序序列结尾的情况下继续比较
while(i !=index && begin.next != null) {
if (p.val < begin.next.val) { //找到位置,插入
index.next = p.next;
p.next = begin.next;
begin.next = p;
p = index.next;
begin = head;
break;
} else { //没有找到位置,继续遍历
begin = begin.next;
i = i.next;
}
}
if (i == index) {
p = p.next;
index = index.next;
begin = head;
}
}
return head.next;
}
public static void main(String[] args) {
Leetcode147 leetcode147 = new Leetcode147();
ListNode head = new ListNode(3);
ListNode node2 = new ListNode(4);
ListNode node3 = new ListNode(1);
/*
ListNode head = new ListNode(4);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(1);
ListNode node4 = new ListNode(3);
*/
/*
ListNode head = new ListNode(-1);
ListNode node2 = new ListNode(5);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(0);
*/
head.next = node2;
node2.next = node3;
/*
node3.next = node4;
node4.next = node5;
*/
head = leetcode147.insertionSortList(head);
ListNode p = head;
while (p != null) {
System.out.print(p.val + " ");
p = p.next;
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
} | Update
| leetcode/linkedlist/Leetcode147.java | Update | <ide><path>eetcode/linkedlist/Leetcode147.java
<ide> p.next = head;
<ide> head = p;
<ide>
<del> ListNode begin = head; // 有序序列的开头
<del> ListNode index = head; // 有序序列的结尾
<del> p = head.next;
<del> while(p != null) {
<add> ListNode begin = head; // 有序序列的开头
<add> ListNode index = head; // 有序序列的结尾
<add> p = head.next;
<add> while (p != null) {
<ide> ListNode i = head;
<ide> // 在没有遍历到有序序列结尾的情况下继续比较
<del> while(i !=index && begin.next != null) {
<del> if (p.val < begin.next.val) { //找到位置,插入
<add> while (i != index && begin.next != null) {
<add> if (p.val < begin.next.val) { // 找到位置,插入
<ide> index.next = p.next;
<ide> p.next = begin.next;
<ide> begin.next = p;
<ide> p = index.next;
<ide> begin = head;
<ide> break;
<del> } else { //没有找到位置,继续遍历
<add> } else { // 没有找到位置,继续遍历
<ide> begin = begin.next;
<ide> i = i.next;
<ide> } |
|
Java | apache-2.0 | 4177d2f44031eeec9ced5bd2358cf8e73303d772 | 0 | akchinSTC/systemml,niketanpansare/incubator-systemml,iyounus/incubator-systemml,sandeep-n/incubator-systemml,nakul02/systemml,dusenberrymw/systemml,gweidner/systemml,asurve/systemml,gweidner/systemml,deroneriksson/incubator-systemml,deroneriksson/incubator-systemml,niketanpansare/systemml,asurve/arvind-sysml2,nakul02/incubator-systemml,dhutchis/systemml,asurve/systemml,asurve/incubator-systemml,gweidner/incubator-systemml,dusenberrymw/incubator-systemml,asurve/incubator-systemml,asurve/systemml,iyounus/incubator-systemml,dusenberrymw/incubator-systemml,asurve/arvind-sysml2,niketanpansare/systemml,sandeep-n/incubator-systemml,dusenberrymw/incubator-systemml,nakul02/incubator-systemml,deroneriksson/systemml,iyounus/incubator-systemml,niketanpansare/systemml,niketanpansare/systemml,Wenpei/incubator-systemml,nakul02/systemml,deroneriksson/systemml,sandeep-n/incubator-systemml,apache/incubator-systemml,niketanpansare/systemml,deroneriksson/systemml,Myasuka/systemml,apache/incubator-systemml,apache/incubator-systemml,gweidner/incubator-systemml,gweidner/systemml,dusenberrymw/systemml,dusenberrymw/incubator-systemml,gweidner/systemml,asurve/incubator-systemml,dusenberrymw/systemml,dhutchis/systemml,dusenberrymw/incubator-systemml,fschueler/incubator-systemml,Myasuka/systemml,akchinSTC/systemml,Myasuka/systemml,apache/incubator-systemml,deroneriksson/incubator-systemml,akchinSTC/systemml,nakul02/systemml,gweidner/incubator-systemml,nakul02/incubator-systemml,niketanpansare/incubator-systemml,asurve/incubator-systemml,deroneriksson/systemml,asurve/incubator-systemml,Wenpei/incubator-systemml,gweidner/incubator-systemml,Wenpei/incubator-systemml,nakul02/incubator-systemml,asurve/systemml,asurve/systemml,dhutchis/systemml,asurve/arvind-sysml2,fschueler/incubator-systemml,fschueler/incubator-systemml,dusenberrymw/systemml,iyounus/incubator-systemml,Wenpei/incubator-systemml,asurve/arvind-sysml2,deroneriksson/systemml,asurve/arvind-sysml2,niketanpansare/incubator-systemml,asurve/arvind-sysml2,deroneriksson/incubator-systemml,sandeep-n/incubator-systemml,gweidner/systemml,nakul02/incubator-systemml,deroneriksson/systemml,gweidner/incubator-systemml,iyounus/incubator-systemml,gweidner/incubator-systemml,fschueler/incubator-systemml,Myasuka/systemml,asurve/incubator-systemml,akchinSTC/systemml,asurve/systemml,dusenberrymw/incubator-systemml,niketanpansare/systemml,deroneriksson/incubator-systemml,niketanpansare/incubator-systemml,dusenberrymw/systemml,akchinSTC/systemml,nakul02/systemml,dhutchis/systemml,apache/incubator-systemml,dusenberrymw/systemml,dhutchis/systemml,Myasuka/systemml,gweidner/systemml,akchinSTC/systemml,Myasuka/systemml,iyounus/incubator-systemml,nakul02/systemml,nakul02/incubator-systemml,nakul02/systemml,apache/incubator-systemml,dhutchis/systemml,deroneriksson/incubator-systemml | /**
* (C) Copyright IBM Corp. 2010, 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ibm.bi.dml.test.integration.functions.aggregate;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/** Group together the tests in this package into a single suite so that the Maven build
* won't run two of them at once. */
@RunWith(Suite.class)
@Suite.SuiteClasses({
AggregateInfTest.class,
ColSumTest.class,
LengthTest.class,
MaxTest.class,
MinTest.class,
NColTest.class,
NRowTest.class,
ProdTest.class,
RowSumTest.class,
SumTest.class,
SumSqTest.class,
RowSumsSqTest.class,
ColSumsSqTest.class,
TraceTest.class,
FullAggregateTest.class,
FullColAggregateTest.class,
FullGroupedAggregateTest.class,
FullRowAggregateTest.class
})
/** This class is just a holder for the above JUnit annotations. */
public class ZPackageSuite {
}
| src/test_suites/java/com/ibm/bi/dml/test/integration/functions/aggregate/ZPackageSuite.java | /**
* (C) Copyright IBM Corp. 2010, 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ibm.bi.dml.test.integration.functions.aggregate;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/** Group together the tests in this package into a single suite so that the Maven build
* won't run two of them at once. */
@RunWith(Suite.class)
@Suite.SuiteClasses({
AggregateInfTest.class,
ColSumTest.class,
LengthTest.class,
MaxTest.class,
MinTest.class,
NColTest.class,
NRowTest.class,
ProdTest.class,
RowSumTest.class,
SumTest.class,
TraceTest.class,
FullAggregateTest.class,
FullColAggregateTest.class,
FullGroupedAggregateTest.class,
FullRowAggregateTest.class
})
/** This class is just a holder for the above JUnit annotations. */
public class ZPackageSuite {
}
| Add SumSq tests to aggregate test suite.
Closes #3.
| src/test_suites/java/com/ibm/bi/dml/test/integration/functions/aggregate/ZPackageSuite.java | Add SumSq tests to aggregate test suite. | <ide><path>rc/test_suites/java/com/ibm/bi/dml/test/integration/functions/aggregate/ZPackageSuite.java
<ide> ProdTest.class,
<ide> RowSumTest.class,
<ide> SumTest.class,
<add> SumSqTest.class,
<add> RowSumsSqTest.class,
<add> ColSumsSqTest.class,
<ide> TraceTest.class,
<ide>
<ide> FullAggregateTest.class, |
|
Java | mit | 6e439df26d556453916e33f00c3ed437e60d8f94 | 0 | Fengtan/solr-gui | package com.github.fengtan.solrgui;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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.impl.HttpSolrServer;
import org.apache.solr.client.solrj.request.LukeRequest;
import org.apache.solr.client.solrj.response.LukeResponse;
import org.apache.solr.client.solrj.response.LukeResponse.FieldInfo;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
// TODO test with Solr < 4.
public class SolrGUIServer {
private URL url;
private String name;
private SolrServer server;
private List<SolrGUIDocument> documents;
private Set<ISolrGUIServerViewer> changeListeners = new HashSet<ISolrGUIServerViewer>();
public SolrGUIServer(URL url, String name) {
this.url = url;
this.name = name;
this.server = new HttpSolrServer(url.toExternalForm());
refreshDocuments();
}
public URL getURL() {
return url;
}
public String getName() {
return name;
}
public void refreshDocuments() {
documents = getAllDocuments();
}
// TODO cache ? use transactions ?
private List<SolrGUIDocument> getAllDocuments() {
SolrQuery query = new SolrQuery();
query.set("q", "*:*");
return getDocumentList(query);
}
private List<SolrGUIDocument> getDocumentList(SolrQuery query) {
List<SolrGUIDocument> list = new ArrayList<SolrGUIDocument>();
QueryResponse response;
try {
response = server.query(query);
} catch (SolrServerException e) {
// TODO log error
return list;
}
for (SolrDocument document:response.getResults()) {
list.add(new SolrGUIDocument(document));
}
return list;
}
/**
* Return the collection of documents
*/
public List<SolrGUIDocument> getDocuments() {
return documents;
}
/**
* Add a new document to the collection of documents
*/
public void addDocument() {
SolrGUIDocument document = new SolrGUIDocument(getFields());
document.setChange(SolrGUIChange.ADDED);
documents.add(documents.size(), document);
for (ISolrGUIServerViewer viewer:changeListeners) {
viewer.addDocument(document);
}
}
/**
* @param document
*/
public void removeDocument(SolrGUIDocument document) {
document.setChange(SolrGUIChange.DELETED);
for (ISolrGUIServerViewer viewer:changeListeners) {
viewer.updateDocument(document);
}
}
/**
* @param document
*/
public void documentChanged(SolrGUIDocument document) {
document.setChange(SolrGUIChange.UPDATED);
for (ISolrGUIServerViewer viewer:changeListeners) {
viewer.updateDocument(document);
}
}
/**
* @param viewer
*/
public void removeChangeListener(ISolrGUIServerViewer viewer) {
changeListeners.remove(viewer);
}
/**
* @param viewer
*/
public void addChangeListener(ISolrGUIServerViewer viewer) {
changeListeners.add(viewer);
}
// TODO is there a better way to get the list of fields ? e.g. SolrQuery with only 1 document (not q *:*)
// TODO what if there is no document in the server ?
public String[] getFields() {
LukeRequest request = new LukeRequest();
try {
LukeResponse response = request.process(server);
Collection<FieldInfo> fieldsInfo = response.getFieldInfo().values();
List<String> fields = new ArrayList<String>();
for (FieldInfo fieldInfo:fieldsInfo) {
fields.add(fieldInfo.getName());
}
return fields.toArray(new String[fields.size()]);
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new String[]{};
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new String[]{};
}
/* TODO provide option to use this in case Luke handler is not available?
Collection<String> fields = getAllDocuments().get(0).getFieldNames();
return fields.toArray(new String[fields.size()]);
*/
}
public void commit() {
// TODO could use CollectionUtils.filter().
// TODO graceful degradation if Luke handlers not provided by server
// TODO clean up libraries
SolrInputDocument input;
for (SolrGUIDocument document:documents) {
switch (document.getChange()) {
case ADDED:
input = ClientUtils.toSolrInputDocument(document.getDocument());
try {
// TODO use LukeRequest ?
server.add(input); // Returned object seems to have no relevant information.
} catch(SolrServerException e) {
// TODO
e.printStackTrace();
} catch(IOException e) {
// TODO
e.printStackTrace();
}
break;
case DELETED:
// TODO use LukeRequest ?
String id = document.getDocument().getFieldValue("id").toString(); // TODO what if no field named "id"
try {
server.deleteById(id);
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case NONE:
// Nothing to do.
break;
case UPDATED:
// TODO use LukeRequest ?
input = ClientUtils.toSolrInputDocument(document.getDocument());
try {
server.add(input); // Returned object seems to have no relevant information.
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
try {
server.commit();
refreshDocuments(); // Returned object seems to have no relevant information.
// TODO popup to confirm commit is successful ?
// TODO allow to revert a specific document
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO reload data
}
/*
* Release resources.
*/
public void dispose() {
server.shutdown();
}
} | src/com/github/fengtan/solrgui/SolrGUIServer.java | package com.github.fengtan.solrgui;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
// TODO test with Solr < 4.
public class SolrGUIServer {
private URL url;
private String name;
private SolrServer server;
private List<SolrGUIDocument> documents;
private Set<ISolrGUIServerViewer> changeListeners = new HashSet<ISolrGUIServerViewer>();
public SolrGUIServer(URL url, String name) {
this.url = url;
this.name = name;
this.server = new HttpSolrServer(url.toExternalForm());
refreshDocuments();
}
public URL getURL() {
return url;
}
public String getName() {
return name;
}
public void refreshDocuments() {
documents = getAllDocuments();
}
// TODO cache ? use transactions ?
private List<SolrGUIDocument> getAllDocuments() {
SolrQuery query = new SolrQuery();
query.set("q", "*:*");
return getDocumentList(query);
}
private List<SolrGUIDocument> getDocumentList(SolrQuery query) {
List<SolrGUIDocument> list = new ArrayList<SolrGUIDocument>();
QueryResponse response;
try {
response = server.query(query);
} catch (SolrServerException e) {
// TODO log error
return list;
}
for (SolrDocument document:response.getResults()) {
list.add(new SolrGUIDocument(document));
}
return list;
}
/**
* Return the collection of documents
*/
public List<SolrGUIDocument> getDocuments() {
return documents;
}
/**
* Add a new document to the collection of documents
*/
public void addDocument() {
SolrGUIDocument document = new SolrGUIDocument(getFields());
document.setChange(SolrGUIChange.ADDED);
documents.add(documents.size(), document);
for (ISolrGUIServerViewer viewer:changeListeners) {
viewer.addDocument(document);
}
}
/**
* @param document
*/
public void removeDocument(SolrGUIDocument document) {
document.setChange(SolrGUIChange.DELETED);
for (ISolrGUIServerViewer viewer:changeListeners) {
viewer.updateDocument(document);
}
}
/**
* @param document
*/
public void documentChanged(SolrGUIDocument document) {
document.setChange(SolrGUIChange.UPDATED);
for (ISolrGUIServerViewer viewer:changeListeners) {
viewer.updateDocument(document);
}
}
/**
* @param viewer
*/
public void removeChangeListener(ISolrGUIServerViewer viewer) {
changeListeners.remove(viewer);
}
/**
* @param viewer
*/
public void addChangeListener(ISolrGUIServerViewer viewer) {
changeListeners.add(viewer);
}
// TODO is there a better way to get the list of fields ? e.g. SolrQuery with only 1 document (not q *:*)
// TODO what if there is no document in the server ?
public String[] getFields() {
Collection<String> fields = getAllDocuments().get(0).getFieldNames();
return fields.toArray(new String[fields.size()]);
}
public void commit() {
// TODO could use CollectionUtils.filter().
// TODO graceful degradation if Luke handlers not provided by server
// TODO clean up libraries
SolrInputDocument input;
for (SolrGUIDocument document:documents) {
switch (document.getChange()) {
case ADDED:
input = ClientUtils.toSolrInputDocument(document.getDocument());
try {
// TODO use LukeRequest ?
server.add(input); // Returned object seems to have no relevant information.
} catch(SolrServerException e) {
// TODO
e.printStackTrace();
} catch(IOException e) {
// TODO
e.printStackTrace();
}
break;
case DELETED:
// TODO use LukeRequest ?
String id = document.getDocument().getFieldValue("id").toString(); // TODO what if no field named "id"
try {
server.deleteById(id);
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case NONE:
// Nothing to do.
break;
case UPDATED:
// TODO use LukeRequest ?
input = ClientUtils.toSolrInputDocument(document.getDocument());
try {
server.add(input); // Returned object seems to have no relevant information.
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
try {
server.commit();
refreshDocuments(); // Returned object seems to have no relevant information.
// TODO popup to confirm commit is successful ?
// TODO allow to revert a specific document
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO reload data
}
/*
* Release resources.
*/
public void dispose() {
server.shutdown();
}
} | Use Luke to discover fields.
| src/com/github/fengtan/solrgui/SolrGUIServer.java | Use Luke to discover fields. | <ide><path>rc/com/github/fengtan/solrgui/SolrGUIServer.java
<ide> import org.apache.solr.client.solrj.SolrServer;
<ide> import org.apache.solr.client.solrj.SolrServerException;
<ide> import org.apache.solr.client.solrj.impl.HttpSolrServer;
<add>import org.apache.solr.client.solrj.request.LukeRequest;
<add>import org.apache.solr.client.solrj.response.LukeResponse;
<add>import org.apache.solr.client.solrj.response.LukeResponse.FieldInfo;
<ide> import org.apache.solr.client.solrj.response.QueryResponse;
<ide> import org.apache.solr.client.solrj.util.ClientUtils;
<ide> import org.apache.solr.common.SolrDocument;
<ide> // TODO is there a better way to get the list of fields ? e.g. SolrQuery with only 1 document (not q *:*)
<ide> // TODO what if there is no document in the server ?
<ide> public String[] getFields() {
<add> LukeRequest request = new LukeRequest();
<add> try {
<add> LukeResponse response = request.process(server);
<add> Collection<FieldInfo> fieldsInfo = response.getFieldInfo().values();
<add> List<String> fields = new ArrayList<String>();
<add> for (FieldInfo fieldInfo:fieldsInfo) {
<add> fields.add(fieldInfo.getName());
<add> }
<add> return fields.toArray(new String[fields.size()]);
<add> } catch (SolrServerException e) {
<add> // TODO Auto-generated catch block
<add> e.printStackTrace();
<add> return new String[]{};
<add> } catch (IOException e) {
<add> // TODO Auto-generated catch block
<add> e.printStackTrace();
<add> return new String[]{};
<add> }
<add> /* TODO provide option to use this in case Luke handler is not available?
<ide> Collection<String> fields = getAllDocuments().get(0).getFieldNames();
<ide> return fields.toArray(new String[fields.size()]);
<add> */
<ide> }
<ide>
<ide> public void commit() { |
|
Java | mpl-2.0 | cb27013a024e1c776a948ebcb0ed2d6e8d38038a | 0 | etomica/etomica,etomica/etomica,etomica/etomica | package etomica.potential.compute;
import etomica.atom.AtomType;
import etomica.atom.IAtom;
import etomica.atom.IAtomList;
import etomica.box.Box;
import etomica.box.BoxEventListener;
import etomica.box.BoxMoleculeEvent;
import etomica.integrator.IntegratorEvent;
import etomica.integrator.IntegratorListener;
import etomica.math.Complex;
import etomica.molecule.IMolecule;
import etomica.potential.BondingInfo;
import etomica.simulation.Simulation;
import etomica.space.Space;
import etomica.space.Vector;
import etomica.species.ISpecies;
import etomica.util.collections.DoubleArrayList;
import etomica.util.collections.IntArrayList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import static etomica.math.SpecialFunctions.erfc;
import static etomica.math.SpecialFunctions.factorial;
import static java.lang.Math.PI;
public class PotentialComputeEwaldFourier implements PotentialCompute {
private static final double SQRT_PI = Math.sqrt(PI);
private final Box box;
protected double[] uAtom;
protected final DoubleArrayList duAtom;
protected final IntArrayList uAtomsChanged;
protected double virialTot;
protected Vector[] forces;
protected final int[] atomCountByType;
protected final Space space;
private final BondingInfo bondingInfo;
private final double[] chargesByType;
private final double[][] B6;
private final double[][] b6;
private final Vector kBasis;
public void setkCut(double kCut) {
this.kCut = kCut;
}
public void setAlpha(double alpha) {
this.alpha = alpha;
}
public void setAlpha6(double alpha6) {
this.alpha6 = alpha6;
}
private double kCut;
private double alpha;
private double alpha6;
private Complex[] sFacAtom = new Complex[0]; // Complex for each atom
private Complex[] sFac = new Complex[0]; // Complex for each kVector
private final Complex[][] sFacB = new Complex[7][0]; // 7 arrays of, Complex for each kVector
// Array for each spacial dimension, then flattened array of (num kVectors in that dimension)*Complex for each atom
private final Complex[][] eik = new Complex[3][0];
private Complex[] dsFac = new Complex[0]; // Complex for each kVector
private final Complex[][] dsFacB = new Complex[7][0]; // 7 arrays of, Complex for each kVector
private double[] fExp; // double for each kVector
private double[] f6Exp; // double for each kVector
private int nWaveVectors;
private void setArraySizes(int numAtoms, int numKVectors, int[] dimKVectors) {
if (numAtoms > sFacAtom.length) {
sFacAtom = new Complex[numAtoms];
Arrays.setAll(sFacAtom, i -> new Complex());
forces = new Vector[numAtoms];
Arrays.setAll(forces, i -> space.makeVector());
}
for (int i = 0; i < eik.length; i++) {
if (dimKVectors[i] * numAtoms > eik[i].length) {
eik[i] = new Complex[numAtoms * dimKVectors[i]];
Arrays.setAll(eik[i], j -> new Complex());
}
}
if (numKVectors > sFac.length) {
sFac = new Complex[numKVectors];
Arrays.setAll(sFac, i -> new Complex());
for (int j = 0; j < sFacB.length; j++) {
sFacB[j] = new Complex[numKVectors];
Arrays.setAll(sFacB[j], i -> new Complex());
}
dsFac = new Complex[numKVectors];
Arrays.setAll(dsFac, i -> new Complex());
for (int j = 0; j < dsFacB.length; j++) {
dsFacB[j] = new Complex[numKVectors];
Arrays.setAll(dsFacB[j], i -> new Complex());
}
fExp = new double[numKVectors];
f6Exp = new double[numKVectors];
}
}
public PotentialComputeEwaldFourier(Simulation sim, Box box, BondingInfo bondingInfo) {
this.box = box;
this.space = box.getSpace();
this.bondingInfo = bondingInfo;
this.duAtom = new DoubleArrayList(16);
this.uAtomsChanged = new IntArrayList(16);
this.forces = new Vector[0];
ISpecies species = sim.getSpecies(sim.getSpeciesCount() - 1);
int lastTypeIndex = species.getAtomType(species.getUniqueAtomTypeCount() - 1).getIndex();
int numAtomTypes = lastTypeIndex + 1;
this.atomCountByType = new int[numAtomTypes];
box.getEventManager().addListener(new BoxEventListener() {
@Override
public void boxMoleculeAdded(BoxMoleculeEvent e) {
for (AtomType atomType : e.getMolecule().getType().getAtomTypes()) {
atomCountByType[atomType.getIndex()]++;
}
}
@Override
public void boxMoleculeRemoved(BoxMoleculeEvent e) {
for (AtomType atomType : e.getMolecule().getType().getAtomTypes()) {
atomCountByType[atomType.getIndex()]--;
}
}
});
this.chargesByType = new double[numAtomTypes];
this.B6 = new double[numAtomTypes][numAtomTypes];
this.b6 = new double[numAtomTypes][7];
this.kBasis = space.makeVector();
}
public void setCharge(AtomType type, double charge) {
this.chargesByType[type.getIndex()] = charge;
}
public void setR6Coefficient(AtomType type, double sigma, double epsilon) {
int numAtomTypes = this.B6.length;
int iType = type.getIndex();
double sigmak = 1;
for (int k=0; k<=6; k++) {
long ck = factorial(6)/(factorial(6-k)*factorial(k));
b6[iType][k] = 0.25*sigmak*Math.sqrt(ck*epsilon);
sigmak *= sigma;
}
for (int jType=0; jType<numAtomTypes; jType++) {
B6[iType][jType] = 0;
for (int k=0; k<=6; k++) {
B6[iType][jType] += b6[iType][k]*b6[jType][6-k];
}
B6[jType][iType] = B6[iType][jType];
}
}
@Override
public void init() {
}
@Override
public Vector[] getForces() {
return forces;
}
@Override
public double getLastVirial() {
return virialTot;
}
@Override
public double getOldEnergy() {
return 0;
}
@Override
public void updateAtom(IAtom atom) {
}
@Override
public double computeAll(boolean doForces) {
int numAtoms = box.getLeafList().size();
virialTot = 0;
double q2sum = 0;
double sumBij = 0;
double sumBii = 0;
double uTot = 0;
for (int iType = 0; iType < atomCountByType.length; iType++) {
int iNum = atomCountByType[iType];
if (iNum == 0) { continue; }
double qi = chargesByType[iType];
q2sum += iNum * qi * qi;
double Bii = B6[iType][iType];
if (alpha6 > 0 && Bii != 0) {
sumBii += iNum * Bii;
for (int jType = 0; jType < atomCountByType.length; jType++) {
sumBij += iNum * atomCountByType[jType] * B6[iType][jType];
}
}
}
uTot -= alpha / SQRT_PI * q2sum;
double vol = box.getBoundary().volume();
if (sumBii > 0) {
double alpha63 = alpha6 * alpha6 * alpha6;
uTot -= SQRT_PI * PI * alpha63 / (6 * vol) * sumBij;
virialTot += 3 * SQRT_PI * PI * alpha63 / (6 * vol) * sumBij;
uTot += alpha63 * (alpha63 / 12) * sumBii;
}
// TODO intramolecular
double kCut2 = kCut * kCut;
Vector bs = box.getBoundary().getBoxSize();
int kxMax = (int)(0.5 * bs.getX(0) / PI * kCut);
// cube instead of sphere, so conservatively big
int[] kMax = {
kxMax,
(int)(0.5 * bs.getX(1) / PI * kCut),
(int)(0.5 * bs.getX(2) / PI * kCut)
};
int[] nk = {kMax[0] + 1, 2*kMax[1] + 1, 2*kMax[2] + 1};
int nkTot = ((2*kxMax + 1) * nk[1] * nk[2] - 1) / 2;
this.setArraySizes(numAtoms, nkTot, nk);
Arrays.stream(forces).forEach(v -> v.E(0));
// We want exp(i dot(k,r)) for every k and every r
// then sum over atoms, s(k) = sum[exp(i dot(k,r))] and U(k) = s(k) * s*(k)
//
// To get there, we first invoke that
// exp(i dot(k,r)) = exp(i kx rx) exp(i ky ry) exp(i kz rz)
// the values of ka (a=x,y,z) will be such that ka = 2 l pi / bs[a]
// so ea(l=2) = ea(l=1) ea(l=1)
// ea(l=3) = ea(l=1) ea(l=2)
// and so on, where ea(l) = exp(i (2 l pi / bs[a]) ra)
// See Allen & Tildesley for more details
// https://dx.doi.org/10.1093/oso/9780198803195.001.0001
// https://github.com/Allen-Tildesley/examples/blob/master/ewald_module.f90
IAtomList atoms = box.getLeafList();
for (int a=0; a<3; a++) {
double fac = 2.0* PI / bs.getX(a);
for (int iAtom=0; iAtom<numAtoms; iAtom++) {
int idx = iAtom*nk[a];
if (a>0) idx += kMax[a];
eik[a][idx] = new Complex(1, 0);
if (nk[a]==1) continue;
int iType = atoms.get(iAtom).getType().getIndex();
if (chargesByType[iType] == 0 && B6[iType][iType] == 0) continue;
Vector ri = atoms.get(iAtom).getPosition();
eik[a][idx+1] = new Complex(Math.cos(fac*ri.getX(a)), Math.sin(fac*ri.getX(a)));
for (int i=2; i<=kMax[a]; i++) {
eik[a][idx+i] = eik[a][idx+1].times(eik[a][idx+i-1]);
}
if (a==0) continue;
for (int i=1; i<=kMax[a]; i++) {
eik[a][idx-i] = eik[a][idx+i].conjugate();
}
}
}
double coeff = 4 * PI / vol;
double coeffB2 = -2.0* SQRT_PI * PI * alpha6*alpha6*alpha6/(3.0*vol);
double fourierSum = 0;
double fourierSum6 = 0;
double virialSum = 0;
double virialSum6 = 0;
int ik = 0;
kBasis.E(2 * PI);
kBasis.DE(bs);
for (int ikx=0; ikx<=kxMax; ikx++) {
double kx = ikx*kBasis.getX(0);
double kx2 = kx*kx;
double kyCut2 = kCut2 - kx2;
boolean xpositive = ikx>0;
int kyMax = (int)(0.5*bs.getX(1)*Math.sqrt(kyCut2)/PI);
for (int iky=-kyMax; iky<=kyMax; iky++) {
if (!xpositive && iky<0) continue;
boolean ypositive = iky>0;
double ky = iky*kBasis.getX(1);
double kxy2 = kx2 + ky*ky;
int kzMax = (int)(0.5*bs.getX(2)*Math.sqrt(kCut2 - kxy2)/PI);
for (int ikz=-kzMax; ikz<=kzMax; ikz++) {
if (!xpositive && !ypositive && ikz<=0) continue;
double kz = ikz*kBasis.getX(2);
double kxyz2 = kxy2 + kz*kz;
double expthing = Math.exp(-0.25*kxyz2/(alpha*alpha));
sFac[ik] = Complex.ZERO;
for (int kB=0; kB<=6; kB++) sFacB[kB][ik] = Complex.ZERO;
// we could skip this as long as box-length, kCut don't change between calls
fExp[ik] = coeff*expthing/kxyz2;
double hdf6dh = 0;
if (alpha6 > 0) {
double kxyz1 = Math.sqrt(kxyz2);
double h = kxyz1/(2*alpha6);
double h2 = h*h;
double exph2 = Math.exp(-h2);
f6Exp[ik] = coeffB2*h*h2*(SQRT_PI * erfc(h) + (0.5/h2 - 1)/h*exph2);
hdf6dh = 3*f6Exp[ik] - 1.5*coeffB2*exph2;
}
for (int iAtom=0; iAtom<numAtoms; iAtom++) {
int iType = atoms.get(iAtom).getType().getIndex();
double qi = chargesByType[iType];
double Bii = B6[iType][iType];
if (qi==0 && Bii == 0) {
sFacAtom[iAtom] = Complex.ZERO;
continue;
}
Complex iContrib = eik[0][iAtom*nk[0]+ikx]
.times(eik[1][iAtom*nk[1]+kMax[1]+iky])
.times(eik[2][iAtom*nk[2]+kMax[2]+ikz]);
sFacAtom[iAtom] = iContrib;
sFac[ik] = sFac[ik].plus(iContrib.times(qi));
if (alpha6 > 0) {
for (int kB=0; kB<=6; kB++) {
sFacB[kB][ik] = sFacB[kB][ik].plus(iContrib.times(b6[iType][kB]));
}
}
}
double x = (sFac[ik].times(sFac[ik].conjugate())).real();
fourierSum += fExp[ik] * x;
double kdfdk = 0;
double dfqdV = 0, df6dV = 0;
if (alpha>0) {
kdfdk = -(2 + kxyz2/(2*alpha*alpha))*fExp[ik];
dfqdV = -fExp[ik]/vol - kdfdk/(3*vol);
virialSum += 3*vol*dfqdV*x;
}
if (alpha6>0) {
df6dV = -f6Exp[ik]/vol - hdf6dh/(3*vol);
for (int kB=0; kB<=6; kB++) {
double y = sFacB[kB][ik].times(sFacB[6 - kB][ik].conjugate()).real();
fourierSum6 += f6Exp[ik] * y;
virialSum6 += 3*vol*df6dV*y;
}
}
if (doForces) {
for (int iAtom=0; iAtom<numAtoms; iAtom++) {
int iType = atoms.get(iAtom).getType().getIndex();
double coeffki = alpha==0 ? 0 :
2*fExp[ik]*chargesByType[iType]*(sFacAtom[iAtom].times(sFac[ik].conjugate()).imaginary());
double coeffki6 = 0;
if (alpha6 > 0) {
for (int kB=0; kB<=6; kB++) {
coeffki6 += 2*f6Exp[ik]*b6[iType][kB]*(sFacAtom[iAtom].times(sFacB[6-kB][ik].conjugate())).imaginary();
}
}
coeffki += coeffki6;
forces[iAtom].PE(Vector.of(coeffki * kx, coeffki * ky, coeffki * kz));
}
}
ik++;
}
}
}
this.nWaveVectors = ik;
uTot += fourierSum + fourierSum6;
virialTot += virialSum + virialSum6;
return uTot;
}
@Override
public double computeOneOld(IAtom iAtom) {
return 0;
}
@Override
public double computeOneOldMolecule(IMolecule molecule) {
return 0;
}
@Override
public double computeOne(IAtom iAtom) {
return 0;
}
@Override
public double computeOneMolecule(IMolecule molecule) {
return 0;
}
@Override
public void processAtomU(double fac) {
}
@Override
public IntegratorListener makeIntegratorListener() {
return new IntegratorListener() {
@Override
public void integratorInitialized(IntegratorEvent e) {
}
@Override
public void integratorStepStarted(IntegratorEvent e) {
}
@Override
public void integratorStepFinished(IntegratorEvent e) {
}
};
}
}
| etomica-core/src/main/java/etomica/potential/compute/PotentialComputeEwaldFourier.java | package etomica.potential.compute;
import etomica.atom.AtomType;
import etomica.atom.IAtom;
import etomica.atom.IAtomList;
import etomica.box.Box;
import etomica.box.BoxEventListener;
import etomica.box.BoxMoleculeEvent;
import etomica.integrator.IntegratorEvent;
import etomica.integrator.IntegratorListener;
import etomica.math.Complex;
import etomica.molecule.IMolecule;
import etomica.potential.BondingInfo;
import etomica.simulation.Simulation;
import etomica.space.Space;
import etomica.space.Vector;
import etomica.species.ISpecies;
import etomica.util.collections.DoubleArrayList;
import etomica.util.collections.IntArrayList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import static etomica.math.SpecialFunctions.erfc;
import static etomica.math.SpecialFunctions.factorial;
import static java.lang.Math.PI;
public class PotentialComputeEwaldFourier implements PotentialCompute {
private static final double SQRT_PI = Math.sqrt(PI);
private final Box box;
protected double[] uAtom;
protected final DoubleArrayList duAtom;
protected final IntArrayList uAtomsChanged;
protected double virialTot;
protected Vector[] forces;
protected final int[] atomCountByType;
protected final Space space;
private final BondingInfo bondingInfo;
private final double[] chargesByType;
private final double[][] B6;
private final double[][] b6;
private final Vector kBasis;
public void setkCut(double kCut) {
this.kCut = kCut;
}
public void setAlpha(double alpha) {
this.alpha = alpha;
}
public void setAlpha6(double alpha6) {
this.alpha6 = alpha6;
}
private double kCut;
private double alpha;
private double alpha6;
private Complex[] sFacAtom = new Complex[0]; // Complex for each atom
private Complex[] sFac = new Complex[0]; // Complex for each kVector
private final Complex[][] sFacB = new Complex[7][0]; // 7 arrays of, Complex for each kVector
// Array for each spacial dimension, then flattened array of (num kVectors in that dimension)*Complex for each atom
private final Complex[][] eik = new Complex[3][0];
private Complex[] dsFac = new Complex[0]; // Complex for each kVector
private final Complex[][] dsFacB = new Complex[7][0]; // 7 arrays of, Complex for each kVector
private double[] fExp; // double for each kVector
private double[] f6Exp; // double for each kVector
private int nWaveVectors;
private void setArraySizes(int numAtoms, int numKVectors, int[] dimKVectors) {
if (numAtoms > sFacAtom.length) {
sFacAtom = new Complex[numAtoms];
Arrays.setAll(sFacAtom, i -> new Complex());
forces = new Vector[numAtoms];
Arrays.setAll(forces, i -> space.makeVector());
}
for (int i = 0; i < eik.length; i++) {
if (dimKVectors[i] * numAtoms > eik[i].length) {
eik[i] = new Complex[numAtoms * dimKVectors[i]];
Arrays.setAll(eik[i], j -> new Complex());
}
}
if (numKVectors > sFac.length) {
sFac = new Complex[numKVectors];
Arrays.setAll(sFac, i -> new Complex());
for (int j = 0; j < sFacB.length; j++) {
sFacB[j] = new Complex[numKVectors];
Arrays.setAll(sFacB[j], i -> new Complex());
}
dsFac = new Complex[numKVectors];
Arrays.setAll(dsFac, i -> new Complex());
for (int j = 0; j < dsFacB.length; j++) {
dsFacB[j] = new Complex[numKVectors];
Arrays.setAll(dsFacB[j], i -> new Complex());
}
fExp = new double[numKVectors];
f6Exp = new double[numKVectors];
}
}
public PotentialComputeEwaldFourier(Simulation sim, Box box, BondingInfo bondingInfo) {
this.box = box;
this.space = box.getSpace();
this.bondingInfo = bondingInfo;
this.duAtom = new DoubleArrayList(16);
this.uAtomsChanged = new IntArrayList(16);
this.forces = new Vector[0];
ISpecies species = sim.getSpecies(sim.getSpeciesCount() - 1);
int lastTypeIndex = species.getAtomType(species.getUniqueAtomTypeCount() - 1).getIndex();
int numAtomTypes = lastTypeIndex + 1;
this.atomCountByType = new int[numAtomTypes];
box.getEventManager().addListener(new BoxEventListener() {
@Override
public void boxMoleculeAdded(BoxMoleculeEvent e) {
for (AtomType atomType : e.getMolecule().getType().getAtomTypes()) {
atomCountByType[atomType.getIndex()]++;
}
}
@Override
public void boxMoleculeRemoved(BoxMoleculeEvent e) {
for (AtomType atomType : e.getMolecule().getType().getAtomTypes()) {
atomCountByType[atomType.getIndex()]--;
}
}
});
this.chargesByType = new double[numAtomTypes];
this.B6 = new double[numAtomTypes][numAtomTypes];
this.b6 = new double[numAtomTypes][7];
this.kBasis = space.makeVector();
}
public void setCharge(AtomType type, double charge) {
this.chargesByType[type.getIndex()] = charge;
}
public void setR6Coefficient(AtomType type, double sigma, double epsilon) {
int numAtomTypes = this.B6.length;
int iType = type.getIndex();
double sigmak = 1;
for (int k=0; k<=6; k++) {
long ck = factorial(6)/(factorial(6-k)*factorial(k));
b6[iType][k] = 0.25*sigmak*Math.sqrt(ck*epsilon);
sigmak *= sigma;
}
for (int jType=0; jType<numAtomTypes; jType++) {
B6[iType][jType] = 0;
for (int k=0; k<=6; k++) {
B6[iType][jType] += b6[iType][k]*b6[jType][6-k];
}
B6[jType][iType] = B6[iType][jType];
}
}
@Override
public void init() {
}
@Override
public Vector[] getForces() {
return forces;
}
@Override
public double getLastVirial() {
return virialTot;
}
@Override
public double getOldEnergy() {
return 0;
}
@Override
public void updateAtom(IAtom atom) {
}
@Override
public double computeAll(boolean doForces) {
int numAtoms = box.getLeafList().size();
virialTot = 0;
double q2sum = 0;
double sumBij = 0;
double sumBii = 0;
double uTot = 0;
for (int iType = 0; iType < atomCountByType.length; iType++) {
int iNum = atomCountByType[iType];
if (iNum == 0) { continue; }
double qi = chargesByType[iType];
q2sum += iNum * qi * qi;
double Bii = B6[iType][iType];
if (alpha6 > 0 && Bii != 0) {
sumBii += iNum * Bii;
for (int jType = 0; jType < atomCountByType.length; jType++) {
sumBij += iNum * atomCountByType[jType] * B6[iType][jType];
}
}
}
uTot -= alpha / SQRT_PI * q2sum;
double vol = box.getBoundary().volume();
if (sumBii > 0) {
double alpha63 = alpha6 * alpha6 * alpha6;
uTot -= SQRT_PI * PI * alpha63 / (6 * vol) * sumBij;
virialTot += 3 * SQRT_PI * PI * alpha63 / (6 * vol) * sumBij;
uTot += alpha63 * (alpha63 / 12) * sumBii;
}
// TODO intramolecular
double kCut2 = kCut * kCut;
Vector bs = box.getBoundary().getBoxSize();
int kxMax = (int)(0.5 * bs.getX(0) / PI * kCut);
// cube instead of sphere, so conservatively big
int[] kMax = {
kxMax,
(int)(0.5 * bs.getX(1) / PI * kCut),
(int)(0.5 * bs.getX(2) / PI * kCut)
};
int[] nk = {kMax[0] + 1, 2*kMax[1] + 1, 2*kMax[2] + 1};
int nkTot = ((2*kxMax + 1) * nk[1] * nk[2] - 1) / 2;
this.setArraySizes(numAtoms, nkTot, nk);
Arrays.stream(forces).forEach(v -> v.E(0));
// We want exp(i dot(k,r)) for every k and every r
// then sum over atoms, s(k) = sum[exp(i dot(k,r))] and U(k) = s(k) * s*(k)
//
// To get there, we first invoke that
// exp(i dot(k,r)) = exp(i kx rx) exp(i ky ry) exp(i kz rz)
// the values of ka (a=x,y,z) will be such that ka = 2 l pi / bs[a]
// so ea(l=2) = ea(l=1) ea(l=1)
// ea(l=3) = ea(l=1) ea(l=2)
// and so on, where ea(l) = exp(i (2 l pi / bs[a]) ra)
// See Allen & Tildesley for more details
// https://dx.doi.org/10.1093/oso/9780198803195.001.0001
// https://github.com/Allen-Tildesley/examples/blob/master/ewald_module.f90
IAtomList atoms = box.getLeafList();
for (int a=0; a<3; a++) {
double fac = 2.0* PI / bs.getX(a);
for (int iAtom=0; iAtom<numAtoms; iAtom++) {
int idx = iAtom*nk[a];
if (a>0) idx += kMax[a];
eik[a][idx] = new Complex(1, 0);
if (nk[a]==1) continue;
int iType = atoms.get(iAtom).getType().getIndex();
if (chargesByType[iType] == 0 && B6[iType][iType] == 0) continue;
Vector ri = atoms.get(iAtom).getPosition();
eik[a][idx+1] = new Complex(Math.cos(fac*ri.getX(a)), Math.sin(fac*ri.getX(a)));
for (int i=2; i<=kMax[a]; i++) {
eik[a][idx+i] = eik[a][idx+1].times(eik[a][idx+i-1]);
}
if (a==0) continue;
for (int i=1; i<=kMax[a]; i++) {
eik[a][idx-i] = eik[a][idx+i].conjugate();
}
}
}
double coeff = 4 * PI / vol;
double coeffB2 = -2.0* SQRT_PI * PI * alpha6*alpha6*alpha6/(3.0*vol);
double fourierSum = 0;
double fourierSum6 = 0;
double virialSum = 0;
double virialSum6 = 0;
int ik = 0;
kBasis.E(2 * PI);
kBasis.DE(bs);
for (int ikx=0; ikx<=kxMax; ikx++) {
double kx = ikx*kBasis.getX(0);
double kx2 = kx*kx;
double kyCut2 = kCut2 - kx2;
boolean xpositive = ikx>0;
int kyMax = (int)(0.5*bs.getX(1)*Math.sqrt(kyCut2)/PI);
for (int iky=-kyMax; iky<=kyMax; iky++) {
if (!xpositive && iky<0) continue;
boolean ypositive = iky>0;
double ky = iky*kBasis.getX(1);
double kxy2 = kx2 + ky*ky;
int kzMax = (int)(0.5*bs.getX(2)*Math.sqrt(kCut2 - kxy2)/PI);
for (int ikz=-kzMax; ikz<=kzMax; ikz++) {
if (!xpositive && !ypositive && ikz<=0) continue;
double kz = ikz*kBasis.getX(2);
double kxyz2 = kxy2 + kz*kz;
double expthing = Math.exp(-0.25*kxyz2/(alpha*alpha));
sFac[ik] = Complex.ZERO;
for (int kB=0; kB<=6; kB++) sFacB[kB][ik] = Complex.ZERO;
// we could skip this as long as box-length, kCut don't change between calls
fExp[ik] = coeff*expthing/kxyz2;
double hdf6dh = 0;
if (alpha6 > 0) {
double kxyz1 = Math.sqrt(kxyz2);
double h = kxyz1/(2*alpha6);
double h2 = h*h;
double exph2 = Math.exp(-h2);
f6Exp[ik] = coeffB2*h*h2*(SQRT_PI * erfc(h) + (0.5/h2 - 1)/h*exph2);
hdf6dh = 3*f6Exp[ik] - 1.5*coeffB2*exph2;
}
for (int iAtom=0; iAtom<numAtoms; iAtom++) {
int iType = atoms.get(iAtom).getType().getIndex();
double qi = chargesByType[iType];
double Bii = B6[iType][iType];
if (qi==0 && Bii == 0) {
sFacAtom[iAtom] = Complex.ZERO;
continue;
}
Complex iContrib = eik[0][iAtom*nk[0]+ikx]
.times(eik[1][iAtom*nk[1]+kMax[1]+iky])
.times(eik[2][iAtom*nk[2]+kMax[2]+ikz]);
sFacAtom[iAtom] = iContrib;
sFac[ik] = sFac[ik].plus(iContrib.times(qi));
if (alpha6 > 0) {
for (int kB=0; kB<=6; kB++) {
sFacB[kB][ik] = sFacB[kB][ik].plus(iContrib.times(b6[iType][kB]));
}
}
}
double x = (sFac[ik].times(sFac[ik].conjugate())).real();
fourierSum += fExp[ik] * x;
double kdfdk = 0;
double dfqdV = 0, df6dV = 0;
if (alpha>0) {
kdfdk = -(2 + kxyz2/(2*alpha*alpha))*fExp[ik];
dfqdV = -fExp[ik]/vol - kdfdk/(3*vol);
virialSum += 3*vol*dfqdV*x;
}
if (alpha6>0) {
df6dV = -f6Exp[ik]/vol - hdf6dh/(3*vol);
for (int kB=0; kB<=6; kB++) {
double y = sFacB[kB][ik].times(sFacB[6 - kB][ik].conjugate()).real();
fourierSum6 += f6Exp[ik] * y;
virialSum6 += 3*vol*df6dV*y;
}
}
if (doForces) {
for (int iAtom=0; iAtom<numAtoms; iAtom++) {
int iType = atoms.get(iAtom).getType().getIndex();
double coeffki = alpha==0 ? 0 :
2*fExp[ik]*chargesByType[iType]*(sFacAtom[iAtom].times(sFac[ik].conjugate()).imaginary());
double coeffki6 = 0;
if (alpha6 > 0) {
for (int kB=0; kB<=6; kB++) {
coeffki6 += 2*f6Exp[ik]*b6[iType][kB]*(sFacAtom[iAtom].times(sFacB[6-kB][ik].conjugate())).imaginary();
}
}
coeffki += coeffki6;
forces[iAtom].PE(Vector.of(coeffki * kx, coeffki * ky, coeffki * kz));
}
}
ik++;
}
}
}
this.nWaveVectors = ik;
uTot += fourierSum + fourierSum6;
virialTot += virialSum - virialSum6;
return uTot;
}
@Override
public double computeOneOld(IAtom iAtom) {
return 0;
}
@Override
public double computeOneOldMolecule(IMolecule molecule) {
return 0;
}
@Override
public double computeOne(IAtom iAtom) {
return 0;
}
@Override
public double computeOneMolecule(IMolecule molecule) {
return 0;
}
@Override
public void processAtomU(double fac) {
}
@Override
public IntegratorListener makeIntegratorListener() {
return new IntegratorListener() {
@Override
public void integratorInitialized(IntegratorEvent e) {
}
@Override
public void integratorStepStarted(IntegratorEvent e) {
}
@Override
public void integratorStepFinished(IntegratorEvent e) {
}
};
}
}
| Revert back to adding virialSum6
| etomica-core/src/main/java/etomica/potential/compute/PotentialComputeEwaldFourier.java | Revert back to adding virialSum6 | <ide><path>tomica-core/src/main/java/etomica/potential/compute/PotentialComputeEwaldFourier.java
<ide>
<ide> this.nWaveVectors = ik;
<ide> uTot += fourierSum + fourierSum6;
<del> virialTot += virialSum - virialSum6;
<add> virialTot += virialSum + virialSum6;
<ide>
<ide> return uTot;
<ide> } |
|
Java | apache-2.0 | 933cf1989c7ed00b01e85d12749a6c6492ab814d | 0 | BruceZu/KeepTry,BruceZu/KeepTry,BruceZu/sawdust,BruceZu/KeepTry,BruceZu/sawdust,BruceZu/sawdust,BruceZu/sawdust,BruceZu/KeepTry | // Copyright 2016 The Sawdust Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// https://leetcode.com/problems/remove-element/
public class Leetcode27RemoveElement {
// Leetcode 27 Remove Element
// runtime beats 73.63% of java submissions.
// Given an array and a value, remove all instances of that value in place and return the new length.
// The order of elements can be changed. It doesn't matter what you leave beyond the new length.
public static int removeElement(int[] nums, int val) {
int newIndex = 0;
int i = 0;
while (i < nums.length) {
int current = nums[i];
if (current != val) {
nums[newIndex++] = nums[i];
}
i++;
}
return newIndex;
}
}
| practiseProblem/leetcode/src/main/java/Leetcode27RemoveElement.java | // Copyright 2016 The Sawdust Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
public class Leetcode27RemoveElement {
// Leetcode 27 Remove Element
// runtime beats 73.63% of java submissions.
// Given an array and a value, remove all instances of that value in place and return the new length.
// The order of elements can be changed. It doesn't matter what you leave beyond the new length.
public static int removeElement(int[] nums, int val) {
int newIndex = 0;
int i = 0;
while (i < nums.length) {
int current = nums[i];
if (current != val) {
nums[newIndex++] = nums[i];
}
i++;
}
return newIndex;
}
}
| Add Leetcode link to Leetcode27RemoveElement
| practiseProblem/leetcode/src/main/java/Leetcode27RemoveElement.java | Add Leetcode link to Leetcode27RemoveElement | <ide><path>ractiseProblem/leetcode/src/main/java/Leetcode27RemoveElement.java
<ide> // limitations under the License.
<ide> //
<ide>
<add>// https://leetcode.com/problems/remove-element/
<ide> public class Leetcode27RemoveElement {
<ide> // Leetcode 27 Remove Element
<ide> // runtime beats 73.63% of java submissions. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.