answer
stringlengths 17
10.2M
|
|---|
package railo.runtime.tag;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import railo.commons.io.ModeUtil;
import railo.commons.io.res.Resource;
import railo.commons.io.res.ResourceMetaData;
import railo.commons.io.res.filter.AndResourceFilter;
import railo.commons.io.res.filter.DirectoryResourceFilter;
import railo.commons.io.res.filter.FileResourceFilter;
import railo.commons.io.res.filter.NotResourceFilter;
import railo.commons.io.res.filter.OrResourceFilter;
import railo.commons.io.res.filter.ResourceFilter;
import railo.commons.io.res.filter.ResourceNameFilter;
import railo.commons.io.res.type.file.FileResource;
import railo.commons.io.res.type.s3.S3;
import railo.commons.io.res.type.s3.S3Constants;
import railo.commons.io.res.type.s3.S3Exception;
import railo.commons.io.res.type.s3.S3Resource;
import railo.commons.io.res.util.ModeObjectWrap;
import railo.commons.io.res.util.ResourceAndResourceNameFilter;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.io.res.util.UDFFilter;
import railo.commons.lang.StringUtil;
import railo.runtime.PageContext;
import railo.runtime.exp.ApplicationException;
import railo.runtime.exp.PageException;
import railo.runtime.ext.tag.TagImpl;
import railo.runtime.functions.s3.StoreSetACL;
import railo.runtime.op.Caster;
import railo.runtime.op.Decision;
import railo.runtime.security.SecurityManager;
import railo.runtime.type.Array;
import railo.runtime.type.ArrayImpl;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.Query;
import railo.runtime.type.QueryImpl;
import railo.runtime.type.UDF;
import railo.runtime.type.util.KeyConstants;
/**
* Handles interactions with directories.
*
*
*
**/
public final class Directory extends TagImpl {
public static final int TYPE_ALL = 0;
public static final int TYPE_FILE = 1;
public static final int TYPE_DIR = 2;
public static final ResourceFilter DIRECTORY_FILTER = new DirectoryResourceFilter();
public static final ResourceFilter FILE_FILTER = new FileResourceFilter();
private static final Key MODE = KeyConstants._mode;
private static final Key META = KeyConstants._meta;
private static final Key DATE_LAST_MODIFIED = KeyConstants._dateLastModified;
private static final Key ATTRIBUTES = KeyConstants._attributes;
private static final Key DIRECTORY = KeyConstants._directory;
public static final int LIST_INFO_QUERY_ALL = 1;
public static final int LIST_INFO_QUERY_NAME = 2;
public static final int LIST_INFO_ARRAY_NAME = 4;
public static final int LIST_INFO_ARRAY_PATH = 8;
/** Optional for action = "list". Ignored by all other actions. File extension filter applied to
** returned names. For example: *m. Only one mask filter can be applied at a time. */
private ResourceFilter filter;
private ResourceAndResourceNameFilter nameFilter;
/** The name of the directory to perform the action against. */
private Resource directory;
/** Defines the action to be taken with directory(ies) specified in directory. */
private String action="list";
/** Optional for action = "list". Ignored by all other actions. The query columns by which to sort
** the directory listing. Any combination of columns from query output can be specified in comma-separated list.
** You can specify ASC (ascending) or DESC (descending) as qualifiers for column names. ASC is the default */
private String sort;
private int mode=-1;
/** Required for action = "rename". Ignored by all other actions. The new name of the directory
** specified in the directory attribute. */
private String strNewdirectory;
/** Required for action = "list". Ignored by all other actions. Name of output query for directory
** listing. */
private String name=null;
private boolean recurse=false;
private String serverPassword;
private int type=TYPE_ALL;
//private boolean listOnlyNames;
private int listInfo=LIST_INFO_QUERY_ALL;
//private int acl=S3Constants.ACL_UNKNOW;
private Object acl=null;
private int storage=S3Constants.STORAGE_UNKNOW;
private String destination;
/**
* @see javax.servlet.jsp.tagext.Tag#release()
*/
public void release() {
super.release();
acl=null;
storage=S3Constants.STORAGE_UNKNOW;
type=TYPE_ALL;
filter=null;
nameFilter=null;
destination=null;
directory=null;
action="list";
sort=null;
mode=-1;
strNewdirectory=null;
name=null;
recurse=false;
serverPassword=null;
listInfo=LIST_INFO_QUERY_ALL;
}
/**
* sets a filter
* @param pattern
* @throws PageException
**/
public void setFilter(Object filter) throws PageException {
this.filter=nameFilter=UDFFilter.createResourceAndResourceNameFilter(filter);
}
public void setFilter(UDF filter) throws PageException {
this.filter=nameFilter=UDFFilter.createResourceAndResourceNameFilter(filter);
}
public void setFilter(String pattern) {
this.filter = nameFilter = UDFFilter.createResourceAndResourceNameFilter( pattern );
}
/** set the value acl
* used only for s3 resources, for all others ignored
* @param charset value to set
* @throws ApplicationException
* @Deprecated only exists for backward compatibility to old ra files.
**/
public void setAcl(String acl) throws ApplicationException {
this.acl=acl;
/*acl=acl.trim().toLowerCase();
if("private".equals(acl)) this.acl=S3Constants.ACL_PRIVATE;
else if("public-read".equals(acl)) this.acl=S3Constants.ACL_PRIVATE;
else if("public-read-write".equals(acl)) this.acl=S3Constants.ACL_PUBLIC_READ_WRITE;
else if("authenticated-read".equals(acl)) this.acl=S3Constants.ACL_AUTH_READ;
else throw new ApplicationException("invalid value for attribute acl ["+acl+"]",
"valid values are [private,public-read,public-read-write,authenticated-read]");*/
}
public void setAcl(Object acl) {
this.acl=acl;
}
public void setStoreacl(Object acl) {
this.acl=acl;
}
/** set the value storage
* used only for s3 resources, for all others ignored
* @param charset value to set
* @throws PageException
**/
public void setStorage(String storage) throws PageException {
try {
this.storage=S3.toIntStorage(storage);
} catch (S3Exception e) {
throw Caster.toPageException(e);
}
}
public void setStorelocation(String storage) throws PageException {
setStorage(storage);
}
public void setServerpassword(String serverPassword) {
this.serverPassword=serverPassword;
}
public void setListinfo(String strListinfo) {
strListinfo=strListinfo.trim().toLowerCase();
this.listInfo="name".equals(strListinfo)?LIST_INFO_QUERY_NAME:LIST_INFO_QUERY_ALL;
}
/** set the value directory
* The name of the directory to perform the action against.
* @param directory value to set
**/
public void setDirectory(String directory) {
this.directory=ResourceUtil.toResourceNotExisting(pageContext ,directory);
//print.ln(this.directory);
}
/** set the value action
* Defines the action to be taken with directory(ies) specified in directory.
* @param action value to set
**/
public void setAction(String action) {
this.action=action.toLowerCase();
}
/** set the value sort
* Optional for action = "list". Ignored by all other actions. The query columns by which to sort
* the directory listing. Any combination of columns from query output can be specified in comma-separated list.
* You can specify ASC (ascending) or DESC (descending) as qualifiers for column names. ASC is the default
* @param sort value to set
**/
public void setSort(String sort) {
if(sort.trim().length()>0)
this.sort=sort;
}
public void setMode(String mode) throws PageException {
try {
this.mode=ModeUtil.toOctalMode(mode);
}
catch (IOException e) {
throw Caster.toPageException(e);
}
}
/** set the value newdirectory
* Required for action = "rename". Ignored by all other actions. The new name of the directory
* specified in the directory attribute.
* @param newdirectory value to set
**/
public void setNewdirectory(String newdirectory) {
//this.newdirectory=ResourceUtil.toResourceNotExisting(pageContext ,newdirectory);
this.strNewdirectory=newdirectory;
}
public void setDestination(String destination) {
this.destination=destination;
}
/** set the value name
* Required for action = "list". Ignored by all other actions. Name of output query for directory
* listing.
* @param name value to set
**/
public void setName(String name) {
this.name=name;
}
/**
* @param recurse The recurse to set.
*/
public void setRecurse(boolean recurse) {
this.recurse = recurse;
}
/**
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/
public int doStartTag() throws PageException {
//securityManager = pageContext.getConfig().getSecurityManager();
if(action.equals("list")) {
Object res=actionList(pageContext,directory,serverPassword,type,filter,nameFilter,listInfo,recurse,sort);
if(!StringUtil.isEmpty(name) && res!=null)pageContext.setVariable(name,res);
}
else if(action.equals("create")) actionCreate(pageContext,directory,serverPassword,true,mode,acl,storage);
else if(action.equals("delete")) actionDelete(pageContext,directory,recurse,serverPassword);
else if(action.equals("forcedelete")) actionDelete(pageContext,directory,true,serverPassword);
else if(action.equals("rename")) actionRename(pageContext,directory,strNewdirectory,serverPassword,acl,storage);
else if(action.equals("copy")) {
if(StringUtil.isEmpty(destination,true) && !StringUtil.isEmpty(strNewdirectory,true)) {
destination=strNewdirectory.trim();
}
actionCopy(pageContext,directory,destination,serverPassword,acl,storage,filter,recurse);
}
else throw new ApplicationException("invalid action ["+action+"] for the tag directory");
return SKIP_BODY;
}
/**
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() {
return EVAL_PAGE;
}
/**
* list all files and directories inside a directory
* @throws PageException
*/
public static Object actionList(PageContext pageContext,Resource directory, String serverPassword, int type,ResourceFilter filter,ResourceAndResourceNameFilter nameFilter,
int listInfo,boolean recurse,String sort) throws PageException {
// check directory
SecurityManager securityManager = pageContext.getConfig().getSecurityManager();
securityManager.checkFileLocation(pageContext.getConfig(),directory,serverPassword);
if(type!=TYPE_ALL) {
ResourceFilter typeFilter = (type==TYPE_DIR)?DIRECTORY_FILTER:FILE_FILTER;
if(filter==null) filter=typeFilter;
else filter=new AndResourceFilter(new ResourceFilter[]{typeFilter,filter});
}
// create query Object
String[] names = new String[]{"name","size","type","dateLastModified","attributes","mode","directory"};
String[] types=new String[]{"VARCHAR","DOUBLE","VARCHAR","DATE","VARCHAR","VARCHAR","VARCHAR"};
boolean hasMeta=directory instanceof ResourceMetaData;
if(hasMeta){
names = new String[]{"name","size","type","dateLastModified","attributes","mode","directory","meta"};
types=new String[]{"VARCHAR","DOUBLE","VARCHAR","DATE","VARCHAR","VARCHAR","VARCHAR","OBJECT"};
}
Array array=null;
Query query=null;
Object rtn;
if(listInfo==LIST_INFO_QUERY_ALL || listInfo==LIST_INFO_QUERY_NAME){
boolean listOnlyNames=listInfo==LIST_INFO_QUERY_NAME;
rtn=query=new QueryImpl(
listOnlyNames?new String[]{"name"}:names,
listOnlyNames?new String[]{"VARCHAR"}:types,
0,"query");
}
else
rtn=array=new ArrayImpl();
if(!directory.exists()){
if(directory instanceof FileResource) return rtn;
throw new ApplicationException("directory ["+directory.toString()+"] doesn't exist");
}
if(!directory.isDirectory()){
if(directory instanceof FileResource) return rtn;
throw new ApplicationException("file ["+directory.toString()+"] exists, but isn't a directory");
}
if(!directory.isReadable()){
if(directory instanceof FileResource) return rtn;
throw new ApplicationException("no access to read directory ["+directory.toString()+"]");
}
long startNS=System.nanoTime();
try {
// Query All
if(listInfo==LIST_INFO_QUERY_ALL)
_fillQueryAll(query,directory,filter,0,hasMeta,recurse);
// Query Name
else if(listInfo==LIST_INFO_QUERY_NAME) {
if(recurse || type!=TYPE_ALL)_fillQueryNamesRec("",query, directory, filter, 0,recurse);
else _fillQueryNames(query, directory, nameFilter, 0);
}
//Array Name/Path
else if(listInfo==LIST_INFO_ARRAY_NAME || listInfo==LIST_INFO_ARRAY_PATH) {
boolean onlyName=listInfo==LIST_INFO_ARRAY_NAME;
if(!onlyName || recurse || type!=TYPE_ALL)_fillArrayPathOrName(array, directory, nameFilter, 0, recurse, onlyName);//QueryNamesRec("",query, directory, filter, 0,recurse);
else _fillArrayName(array, directory, nameFilter, 0);
}
} catch (IOException e) {
throw Caster.toPageException(e);
}
// sort
if(sort!=null && query!=null) {
String[] arr=sort.toLowerCase().split(",");
for(int i=arr.length-1;i>=0;i
try {
String[] col=arr[i].trim().split("\\s+");
if(col.length==1)query.sort(col[0].trim());
else if(col.length==2) {
String order=col[1].toLowerCase().trim();
if(order.equals("asc"))
query.sort(col[0],railo.runtime.type.Query.ORDER_ASC);
else if(order.equals("desc"))
query.sort(col[0],railo.runtime.type.Query.ORDER_DESC);
else
throw new ApplicationException("invalid order type ["+col[1]+"]");
}
}
catch(Throwable t) {}
}
}
if(query!=null)query.setExecutionTime(System.nanoTime()-startNS);
return rtn;
}
private static int _fillQueryAll(Query query, Resource directory, ResourceFilter filter, int count, boolean hasMeta, boolean recurse) throws PageException, IOException {
//long start=System.currentTimeMillis();
Resource[] list=directory.listResources();
if(list==null || list.length==0) return count;
String dir=directory.getCanonicalPath();
// fill data to query
//query.addRow(list.length);
boolean isDir;
for(int i=0;i<list.length;i++) {
if(filter==null || filter.accept(list[i])) {
query.addRow(1);
count++;
query.setAt(KeyConstants._name,count,list[i].getName());
isDir=list[i].isDirectory();
query.setAt(KeyConstants._size,count,new Double(isDir?0:list[i].length()));
query.setAt(KeyConstants._type,count,isDir?"Dir":"File");
if(directory.getResourceProvider().isModeSupported()){
query.setAt(MODE,count,new ModeObjectWrap(list[i]));
}
query.setAt(DATE_LAST_MODIFIED,count,new Date(list[i].lastModified()));
query.setAt(ATTRIBUTES,count,getFileAttribute(list[i],true));
if(hasMeta){
query.setAt(META,count,((ResourceMetaData)list[i]).getMetaData());
}
query.setAt(DIRECTORY,count,dir);
}
if(recurse && list[i].isDirectory())
count=_fillQueryAll(query,list[i],filter,count,hasMeta,recurse);
}
return count;
}
// this method only exists for performance reasion
private static int _fillQueryNames(Query query, Resource directory, ResourceNameFilter filter, int count) throws PageException {
String[] list=directory.list();
if(list==null || list.length==0) return count;
for(int i=0;i<list.length;i++) {
if(filter==null || filter.accept(directory,list[i])) {
query.addRow(1);
count++;
query.setAt(KeyConstants._name,count,list[i]);
}
}
return count;
}
private static int _fillQueryNamesRec(String parent, Query query, Resource directory, ResourceFilter filter, int count, boolean recurse) throws PageException {
Resource[] list=directory.listResources();
if(list==null || list.length==0) return count;
for(int i=0;i<list.length;i++) {
if(filter==null || filter.accept(list[i])) {
query.addRow(1);
count++;
query.setAt(KeyConstants._name,count,parent.concat(list[i].getName()));
}
if(recurse && list[i].isDirectory())
count=_fillQueryNamesRec(parent+list[i].getName()+"/",query,list[i],filter,count,recurse);
}
return count;
}
private static int _fillArrayPathOrName(Array arr, Resource directory, ResourceFilter filter, int count, boolean recurse,boolean onlyName) throws PageException {
Resource[] list=directory.listResources();
if(list==null || list.length==0) return count;
for(int i=0;i<list.length;i++) {
if(filter==null || filter.accept(list[i])) {
arr.appendEL(onlyName?list[i].getName():list[i].getAbsolutePath());
count++;
}
if(recurse && list[i].isDirectory())
count=_fillArrayPathOrName(arr,list[i],filter,count,recurse,onlyName);
}
return count;
}
// this method only exists for performance reasion
private static int _fillArrayName(Array arr, Resource directory, ResourceNameFilter filter, int count) {
String[] list=directory.list();
if(list==null || list.length==0) return count;
for(int i=0;i<list.length;i++) {
if(filter==null || filter.accept(directory,list[i])) {
arr.appendEL(list[i]);
}
}
return count;
}
/**
* create a directory
* @throws PageException
*/
public static void actionCreate(PageContext pc,Resource directory,String serverPassword, boolean doParent,int mode,Object acl,int storage) throws PageException {
SecurityManager securityManager = pc.getConfig().getSecurityManager();
securityManager.checkFileLocation(pc.getConfig(),directory,serverPassword);
if(directory.exists()) {
if(directory.isDirectory())
throw new ApplicationException("directory ["+directory.toString()+"] already exist");
else if(directory.isFile())
throw new ApplicationException("can't create directory ["+directory.toString()+"], it exist a file with same name");
}
//if(!directory.mkdirs()) throw new ApplicationException("can't create directory ["+directory.toString()+"]");
try {
directory.createDirectory(doParent);
} catch (IOException ioe) {
throw Caster.toPageException(ioe);
}
// set S3 stuff
setS3Attrs(directory,acl,storage);
// Set Mode
if(mode!=-1) {
try {
directory.setMode(mode);
//FileUtil.setMode(directory,mode);
} catch (IOException e) {
throw Caster.toPageException(e);
}
}
}
private static void setS3Attrs(Resource res,Object acl,int storage) throws PageException {
String scheme = res.getResourceProvider().getScheme();
if("s3".equalsIgnoreCase(scheme)){
S3Resource s3r=(S3Resource) res;
if(acl!=null){
try {
// old way
if(Decision.isString(acl)) {
if(Decision.isInteger(acl)) s3r.setACL(Caster.toIntValue(acl));
else s3r.setACL(S3.toIntACL(Caster.toString(acl)));
}
// new way
else {
StoreSetACL.invoke(s3r, acl);
}
} catch (IOException e) {
throw Caster.toPageException(e);
}
}
if(storage!=S3Constants.STORAGE_UNKNOW) s3r.setStorage(storage);
}
}
/**
* delete directory
* @param dir
* @param forceDelete
* @throws PageException
*/
public static void actionDelete(PageContext pc,Resource dir, boolean forceDelete,String serverPassword) throws PageException {
SecurityManager securityManager = pc.getConfig().getSecurityManager();
securityManager.checkFileLocation(pc.getConfig(),dir,serverPassword);
// directory doesn't exist
if(!dir.exists()) {
if(dir.isDirectory())
throw new ApplicationException("directory ["+dir.toString()+"] doesn't exist");
else if(dir.isFile())
throw new ApplicationException("file ["+dir.toString()+"] doesn't exist and isn't a directory");
}
// check if file
if(dir.isFile())
throw new ApplicationException("can't delete ["+dir.toString()+"], it isn't a directory it is a file");
// delete directory
try {
dir.remove(forceDelete);
} catch (IOException e) {
throw Caster.toPageException(e);
}
}
/**
* rename a directory to a new Name
* @throws PageException
*/
public static void actionRename(PageContext pc,Resource directory,String strNewdirectory,String serverPassword, Object acl,int storage) throws PageException {
// check directory
SecurityManager securityManager = pc.getConfig().getSecurityManager();
securityManager.checkFileLocation(pc.getConfig(),directory,serverPassword);
if(!directory.exists())
throw new ApplicationException("the directory ["+directory.toString()+"] doesn't exist");
if(!directory.isDirectory())
throw new ApplicationException("the file ["+directory.toString()+"] exists, but it isn't a directory");
if(!directory.canRead())
throw new ApplicationException("no access to read directory ["+directory.toString()+"]");
if(strNewdirectory==null)
throw new ApplicationException("the attribute [newDirectory] is not defined");
// real to source
Resource newdirectory=toDestination(pc,strNewdirectory,directory);
securityManager.checkFileLocation(pc.getConfig(),newdirectory,serverPassword);
if(newdirectory.exists())
throw new ApplicationException("new directory ["+newdirectory.toString()+"] already exists");
try {
directory.moveTo(newdirectory);
}
catch(Throwable t) {
throw new ApplicationException(t.getMessage());
}
// set S3 stuff
setS3Attrs(directory,acl,storage);
}
public static void actionCopy(PageContext pc,Resource directory,String strDestination,String serverPassword, Object acl,int storage, ResourceFilter filter, boolean recurse) throws PageException {
// check directory
SecurityManager securityManager = pc.getConfig().getSecurityManager();
securityManager.checkFileLocation(pc.getConfig(),directory,serverPassword);
if(!directory.exists())
throw new ApplicationException("directory ["+directory.toString()+"] doesn't exist");
if(!directory.isDirectory())
throw new ApplicationException("file ["+directory.toString()+"] exists, but isn't a directory");
if(!directory.canRead())
throw new ApplicationException("no access to read directory ["+directory.toString()+"]");
if(StringUtil.isEmpty(strDestination))
throw new ApplicationException("attribute destination is not defined");
// real to source
Resource newdirectory=toDestination(pc,strDestination,directory);
securityManager.checkFileLocation(pc.getConfig(),newdirectory,serverPassword);
if(newdirectory.exists())
throw new ApplicationException("new directory ["+newdirectory.toString()+"] already exist");
try {
// has already a filter
if(filter!=null) {
if(recurse) filter=new OrResourceFilter(new ResourceFilter[]{
filter,DirectoryResourceFilter.FILTER
});
}
else {
if(!recurse)filter=new NotResourceFilter(DirectoryResourceFilter.FILTER);
}
ResourceUtil.copyRecursive(directory, newdirectory,filter);
}
catch(Throwable t) {
throw new ApplicationException(t.getMessage());
}
// set S3 stuff
setS3Attrs(directory,acl,storage);
}
private static Resource toDestination(PageContext pageContext,String path, Resource source) {
if(source!=null && path.indexOf(File.separatorChar)==-1 && path.indexOf('/')==-1 && path.indexOf('\\')==-1) {
Resource p = source.getParentResource();
if(p!=null)return p.getRealResource(path);
}
return ResourceUtil.toResourceNotExisting(pageContext ,path);
}
private static String getFileAttribute(Resource file, boolean exists){
return exists && !file.isWriteable() ? "R".concat(file.isHidden() ? "H" : "") : file.isHidden() ? "H" : "";
}
/**
* @param type the type to set
*/
public void setType(String strType) throws ApplicationException {
strType=strType.trim().toLowerCase();
if("all".equals(strType)) type=TYPE_ALL;
else if("dir".equals(strType)) type=TYPE_DIR;
else if("directory".equals(strType)) type=TYPE_DIR;
else if("file".equals(strType)) type=TYPE_FILE;
else throw new ApplicationException("invalid type ["+strType+"] for the tag directory");
}
}
|
package net.runelite.api;
public class GraphicID
{
public static final int TELEPORT = 111;
public static final int GREY_BUBBLE_TELEPORT = 86;
public static final int ENTANGLE = 179;
public static final int SNARE = 180;
public static final int BIND = 181;
public static final int ICE_RUSH = 361;
public static final int ICE_BURST = 363;
public static final int ICE_BLITZ = 367;
public static final int ICE_BARRAGE = 369;
public static final int VENGEANCE_OTHER = 725;
public static final int VENGEANCE = 726;
public static final int STAFF_OF_THE_DEAD = 1228;
public static final int IMBUED_HEART = 1316;
public static final int FLYING_FISH = 1387;
}
|
package beast.util;
import beast.core.util.Log;
import beast.evolution.alignment.*;
import beast.evolution.datatype.DataType;
import beast.evolution.datatype.StandardData;
import beast.evolution.datatype.UserDataType;
import beast.evolution.tree.TraitSet;
import beast.evolution.tree.Tree;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* parses nexus file and grabs alignment and calibration from the file *
*/
public class NexusParser {
/**
* keep track of nexus file line number, to report when the file does not parse *
*/
int lineNr;
/**
* Beast II objects reconstructed from the file*
*/
public Alignment m_alignment;
public List<Alignment> filteredAlignments = new ArrayList<Alignment>();
public TraitSet traitSet;
public List<String> taxa;
public List<Tree> trees;
static Set<String> g_sequenceIDs;
public Map<String, String> translationMap = null;
static {
g_sequenceIDs = new HashSet<>();
}
public List<TaxonSet> taxonsets = new ArrayList<>();
private List<NexusParserListener> listeners = new ArrayList<>();
/**
* Adds a listener for client classes that want to monitor progress of the parsing.
* @param listener
*/
public void addListener(final NexusParserListener listener) {
listeners.add(listener);
}
/**
* Try to parse BEAST 2 objects from the given file
*
* @param file the file to parse.
*/
public void parseFile(final File file) throws Exception {
final String fileName = file.getName().replaceAll(".*[\\/\\\\]", "").replaceAll("\\..*", "");
parseFile(fileName, new FileReader(file));
}
/**
* try to reconstruct Beast II objects from the given reader
*
* @param id a name to give to the parsed results
* @param reader a reader to parse from
*/
public void parseFile(final String id, final Reader reader) throws Exception {
lineNr = 0;
final BufferedReader fin;
if (reader instanceof BufferedReader) {
fin = (BufferedReader) reader;
} else {
fin = new BufferedReader(reader);
}
try {
while (fin.ready()) {
final String sStr = nextLine(fin);
if (sStr == null) {
return;
}
final String sLower = sStr.toLowerCase();
if (sLower.matches("^\\s*begin\\s+data;\\s*$") || sLower.matches("^\\s*begin\\s+characters;\\s*$")) {
m_alignment = parseDataBlock(fin);
m_alignment.setID(id);
} else if (sLower.matches("^\\s*begin\\s+calibration;\\s*$")) {
traitSet = parseCalibrationsBlock(fin);
} else if (sLower.matches("^\\s*begin\\s+assumptions;\\s*$") ||
sLower.matches("^\\s*begin\\s+sets;\\s*$") ||
sLower.matches("^\\s*begin\\s+mrbayes;\\s*$")) {
parseAssumptionsBlock(fin);
} else if (sLower.matches("^\\s*begin\\s+taxa;\\s*$")) {
parseTaxaBlock(fin);
} else if (sLower.matches("^\\s*begin\\s+trees;\\s*$")) {
parseTreesBlock(fin);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Around line " + lineNr + "\n" + e.getMessage());
}
} // parseFile
private void parseTreesBlock(final BufferedReader fin) throws Exception {
trees = new ArrayList<Tree>();
// read to first non-empty line within trees block
String sStr = fin.readLine().trim();
while (sStr.equals("")) {
sStr = fin.readLine().trim();
}
int origin = -1;
// if first non-empty line is "translate" then parse translate block
if (sStr.toLowerCase().contains("translate")) {
translationMap = parseTranslateBlock(fin);
origin = getIndexedTranslationMapOrigin(translationMap);
if (origin != -1) {
taxa = getIndexedTranslationMap(translationMap, origin);
}
}
// read trees
while (sStr != null) {
if (sStr.toLowerCase().startsWith("tree ")) {
final int i = sStr.indexOf('(');
if (i > 0) {
sStr = sStr.substring(i);
}
TreeParser treeParser;
if (origin != -1) {
treeParser = new TreeParser(taxa, sStr, origin, false);
} else {
try {
treeParser = new TreeParser(taxa, sStr, 0, false);
} catch (ArrayIndexOutOfBoundsException e) {
treeParser = new TreeParser(taxa, sStr, 1, false);
}
}
// catch (NullPointerException e) {
// treeParser = new TreeParser(m_taxa, sStr, 1);
for (final NexusParserListener listener : listeners) {
listener.treeParsed(trees.size(), treeParser);
}
if (translationMap != null) treeParser.translateLeafIds(translationMap);
trees.add(treeParser);
// Node tree = treeParser.getRoot();
// tree.sort();
// tree.labelInternalNodes(nNrOfLabels);
}
sStr = fin.readLine();
if (sStr != null) sStr = sStr.trim();
}
}
private List<String> getIndexedTranslationMap(final Map<String, String> translationMap, final int origin) {
System.out.println("translation map size = " + translationMap.size());
final String[] taxa = new String[translationMap.size()];
for (final String key : translationMap.keySet()) {
taxa[Integer.parseInt(key) - origin] = translationMap.get(key);
}
return Arrays.asList(taxa);
}
/**
* @param translationMap
* @return minimum key value if keys are a contiguous set of integers starting from zero or one, -1 otherwise
*/
private int getIndexedTranslationMapOrigin(final Map<String, String> translationMap) {
final SortedSet<Integer> indices = new TreeSet<Integer>();
int count = 0;
for (final String key : translationMap.keySet()) {
final int index = Integer.parseInt(key);
indices.add(index);
count += 1;
}
if ((indices.last() - indices.first() == count - 1) && (indices.first() == 0 || indices.first() == 1)) {
return indices.first();
}
return -1;
}
/**
* @param reader a reader
* @return a map of taxa translations, keys are generally integer node number starting from 1
* whereas values are generally descriptive strings.
* @throws IOException
*/
private Map<String, String> parseTranslateBlock(final BufferedReader reader) throws IOException {
final Map<String, String> translationMap = new HashMap<String, String>();
String line = reader.readLine();
final StringBuilder translateBlock = new StringBuilder();
while (line != null && !line.trim().toLowerCase().equals(";")) {
translateBlock.append(line.trim());
line = reader.readLine();
}
final String[] taxaTranslations = translateBlock.toString().split(",");
for (final String taxaTranslation : taxaTranslations) {
final String[] translation = taxaTranslation.split("[\t ]+");
if (translation.length == 2) {
translationMap.put(translation[0], translation[1]);
// System.out.println(translation[0] + " -> " + translation[1]);
} else {
System.err.println("Ignoring translation:" + Arrays.toString(translation));
}
}
return translationMap;
}
private void parseTaxaBlock(final BufferedReader fin) throws Exception {
taxa = new ArrayList<String>();
int nTaxaExpected = -1;
String sStr;
do {
sStr = nextLine(fin);
if (sStr.toLowerCase().matches("\\s*dimensions\\s.*")) {
sStr = sStr.substring(sStr.toLowerCase().indexOf("ntax=") + 5);
sStr = sStr.replaceAll(";", "");
nTaxaExpected = Integer.parseInt(sStr.trim());
} else if (sStr.toLowerCase().trim().equals("taxlabels")) {
do {
sStr = nextLine(fin);
sStr = sStr.replaceAll(";", "");
sStr = sStr.trim();
if (sStr.length() > 0 && !sStr.toLowerCase().equals("end")) {
String [] sStrs = sStr.split("\\s+");
for (int i = 0; i < sStrs.length; i++) {
String taxon = sStrs[i];
if (taxon.charAt(0) == '\'' || taxon.charAt(0) == '\"') {
while (i < sStrs.length && taxon.charAt(0) != taxon.charAt(taxon.length() - 1)) {
i++;
if (i == sStrs.length) {
throw new Exception("Unclosed quote starting with " + taxon);
}
taxon += " " + sStrs[i];
}
taxon = taxon.substring(1, taxon.length() - 1);
}
taxa.add(taxon);
}
}
} while (!sStr.toLowerCase().equals("end"));
}
} while (!sStr.toLowerCase().equals("end"));
if (nTaxaExpected >= 0 && taxa.size() != nTaxaExpected) {
throw new Exception("Number of taxa (" + taxa.size() + ") is not equal to 'dimension' " +
"field (" + nTaxaExpected + ") specified in 'taxa' block");
}
}
/**
* parse calibrations block and create TraitSet *
*/
TraitSet parseCalibrationsBlock(final BufferedReader fin) throws Exception {
final TraitSet traitSet = new TraitSet();
traitSet.traitNameInput.setValue("date", traitSet);
String sStr;
do {
sStr = nextLine(fin);
if (sStr.toLowerCase().contains("options")) {
String sScale = getAttValue("scale", sStr);
if (sScale.endsWith("s")) {
sScale = sScale.substring(0, sScale.length() - 1);
}
traitSet.unitsInput.setValue(sScale, traitSet);
}
} while (sStr.toLowerCase().contains("tipcalibration"));
String sText = "";
while (true) {
sStr = nextLine(fin);
if (sStr.contains(";")) {
break;
}
sText += sStr;
}
final String[] sStrs = sText.split(",");
sText = "";
for (final String sStr2 : sStrs) {
final String[] sParts = sStr2.split(":");
final String sDate = sParts[0].replaceAll(".*=\\s*", "");
final String[] sTaxa = sParts[1].split("\\s+");
for (final String sTaxon : sTaxa) {
if (!sTaxon.matches("^\\s*$")) {
sText += sTaxon + "=" + sDate + ",\n";
}
}
}
sText = sText.substring(0, sText.length() - 2);
traitSet.traitsInput.setValue(sText, traitSet);
final TaxonSet taxa = new TaxonSet();
taxa.initByName("alignment", m_alignment);
traitSet.taxaInput.setValue(taxa, traitSet);
traitSet.initAndValidate();
return traitSet;
} // parseCalibrations
/**
* parse data block and create Alignment *
*/
public Alignment parseDataBlock(final BufferedReader fin) throws Exception {
final Alignment alignment = new Alignment();
String sStr;
int nTaxa = -1;
int nChar = -1;
int nTotalCount = 4;
String sMissing = "?";
String sGap = "-";
// indicates character matches the one in the first sequence
String sMatchChar = null;
do {
sStr = nextLine(fin);
//dimensions ntax=12 nchar=898;
if (sStr.toLowerCase().contains("dimensions")) {
while (sStr.indexOf(';') < 0) {
sStr += nextLine(fin);
}
sStr = sStr.replace(";", " ");
final String sChar = getAttValue("nchar", sStr);
if (sChar == null) {
throw new Exception("nchar attribute expected (e.g. 'dimensions char=123') expected, not " + sStr);
}
nChar = Integer.parseInt(sChar);
final String sTaxa = getAttValue("ntax", sStr);
if (sTaxa != null) {
nTaxa = Integer.parseInt(sTaxa);
}
} else if (sStr.toLowerCase().contains("format")) {
while (sStr.indexOf(';') < 0) {
sStr += nextLine(fin);
}
sStr = sStr.replace(";", " ");
//format datatype=dna interleave=no gap=-;
final String sDataType = getAttValue("datatype", sStr);
final String sSymbols;
if (getAttValue("symbols", sStr) == null) {
sSymbols = getAttValue("symbols", sStr);
} else {
sSymbols = getAttValue("symbols", sStr).replaceAll("\\s", "");
}
if (sDataType == null) {
System.out.println("Warning: expected datatype (e.g. something like 'format datatype=dna;') not '" + sStr + "' Assuming integer dataType");
alignment.dataTypeInput.setValue("integer", alignment);
if (sSymbols != null && (sSymbols.equals("01") || sSymbols.equals("012"))) {
nTotalCount = sSymbols.length();
}
} else if (sDataType.toLowerCase().equals("rna") || sDataType.toLowerCase().equals("dna") || sDataType.toLowerCase().equals("nucleotide")) {
alignment.dataTypeInput.setValue("nucleotide", alignment);
nTotalCount = 4;
} else if (sDataType.toLowerCase().equals("aminoacid") || sDataType.toLowerCase().equals("protein")) {
alignment.dataTypeInput.setValue("aminoacid", alignment);
nTotalCount = 20;
} else if (sDataType.toLowerCase().equals("standard")) {
alignment.dataTypeInput.setValue("standard", alignment);
nTotalCount = sSymbols.length();
// if (sSymbols == null || sSymbols.equals("01")) {
// alignment.dataTypeInput.setValue("binary", alignment);
// nTotalCount = 2;
// } else {
// alignment.dataTypeInput.setValue("standard", alignment);
// nTotalCount = sSymbols.length();
} else if (sDataType.toLowerCase().equals("binary")) {
alignment.dataTypeInput.setValue("binary", alignment);
nTotalCount = 2;
} else {
alignment.dataTypeInput.setValue("integer", alignment);
if (sSymbols != null && (sSymbols.equals("01") || sSymbols.equals("012"))) {
nTotalCount = sSymbols.length();
}
}
final String sMissingChar = getAttValue("missing", sStr);
if (sMissingChar != null) {
sMissing = sMissingChar;
}
final String sGapChar = getAttValue("gap", sStr);
if (sGapChar != null) {
sGap = sGapChar;
}
sMatchChar = getAttValue("matchchar", sStr);
}
} while (!sStr.trim().toLowerCase().startsWith("matrix") && !sStr.toLowerCase().contains("charstatelabels"));
if (alignment.dataTypeInput.get().equals("standard")) {
StandardData type = new StandardData();
type.setInputValue("nrOfStates", nTotalCount);
type.initAndValidate();
alignment.setInputValue("userDataType", type);
}
//reading CHARSTATELABELS block
if (sStr.toLowerCase().contains("charstatelabels")) {
if (!alignment.dataTypeInput.get().equals("standard")) {
new Exception("If CHATSTATELABELS block is specified then DATATYPE has to be Standard");
}
StandardData standardDataType = (StandardData)alignment.userDataTypeInput.get();
int[] maxNumberOfStates = new int[] {0};
ArrayList<String> tokens = readInCharstatelablesTokens(fin);
ArrayList<UserDataType> charDescriptions = processCharstatelabelsTokens(tokens, maxNumberOfStates);
// while (true) {
// sStr = nextLine(fin);
// if (sStr.contains(";")) {
// break;
// String[] sStrSplit = sStr.split("/");
// ArrayList<String> states = new ArrayList<>();
// if (sStrSplit.length < 2) {
// charDescriptions.add(new UserDataType(sStrSplit[0], states));
// continue;
// String stateStr = sStrSplit[1];
// //add a comma at the end of the string if the last non-whitespace character is not a comma or all the
// // characters are whitespaces in the string. Also remove whitespaces at the end of the string.
// for (int i=stateStr.length()-1; i>=0; i--) {
// if (!Character.isWhitespace(stateStr.charAt(i))) {
// if (stateStr.charAt(i-1) != ',') {
// stateStr = stateStr.substring(0, i)+",";
// break;
// if (i==0) {
// stateStr = stateStr.substring(0, i)+",";
// if (stateStr.isEmpty()) {
// stateStr = stateStr+",";
// final int WAITING=0, WORD=1, PHRASE_IN_QUOTES=2;
// int mode =WAITING; //0 waiting for non-space letter, 1 reading a word; 2 reading a phrase in quotes
// int begin =0, end;
// for (int i=0; i< stateStr.length(); i++) {
// switch (mode) {
// case WAITING:
// while (stateStr.charAt(i) == ' ') {
// mode = stateStr.charAt(i) == '\'' ? PHRASE_IN_QUOTES : WORD;
// begin = i;
// break;
// case WORD:
// end = stateStr.indexOf(" ", begin) != -1 ? stateStr.indexOf(" ", begin) : stateStr.indexOf(",", begin);
// states.add(stateStr.substring(begin, end));
// i=end;
// mode = WAITING;
// break;
// case PHRASE_IN_QUOTES:
// end = begin;
// end = stateStr.indexOf("'", end+2);
// } while (stateStr.charAt(end+1) == '\'' || end == -1);
// if (end == -1) {
// System.out.println("Incorrect description in charstatelabels. Single quote found in line ");
// end++;
// states.add(stateStr.substring(begin, end));
// i=end;
// mode=WAITING;
// break;
// default:
// break;
// // oldTODO make sStrSplit[0] look nicer (remove whitespaces and may be numbers at the beginning)
// charDescriptions.add(new UserDataType(sStrSplit[0], states));
// maxNumberOfStates = Math.max(maxNumberOfStates, states.size());
standardDataType.setInputValue("charstatelabels", charDescriptions);
standardDataType.setInputValue("nrOfStates", Math.max(maxNumberOfStates[0], nTotalCount));
standardDataType.initAndValidate();
for (UserDataType dataType : standardDataType.charStateLabelsInput.get()) {
dataType.initAndValidate();
}
}
//skipping before MATRIX block
while (!sStr.toLowerCase().contains(("matrix"))) {
sStr = nextLine(fin);
}
// read character data
// Use string builder for efficiency
final Map<String, StringBuilder> seqMap = new HashMap<String, StringBuilder>();
final List<String> sTaxa = new ArrayList<String>();
String sPrevTaxon = null;
int seqLen = 0;
while (true) {
sStr = nextLine(fin);
if (sStr.contains(";")) {
break;
}
int iStart = 0, iEnd;
final String sTaxon;
while (Character.isWhitespace(sStr.charAt(iStart))) {
iStart++;
}
if (sStr.charAt(iStart) == '\'' || sStr.charAt(iStart) == '\"') {
final char c = sStr.charAt(iStart);
iStart++;
iEnd = iStart;
while (sStr.charAt(iEnd) != c) {
iEnd++;
}
sTaxon = sStr.substring(iStart, iEnd);
seqLen = 0;
iEnd++;
} else {
iEnd = iStart;
while (iEnd < sStr.length() && !Character.isWhitespace(sStr.charAt(iEnd))) {
iEnd++;
}
if (iEnd < sStr.length()) {
sTaxon = sStr.substring(iStart, iEnd);
seqLen = 0;
} else if ((sPrevTaxon == null || seqLen == nChar) && iEnd == sStr.length()) {
sTaxon = sStr.substring(iStart, iEnd);
seqLen = 0;
} else {
sTaxon = sPrevTaxon;
if (sTaxon == null) {
throw new Exception("Could not recognise taxon");
}
iEnd = iStart;
}
}
sPrevTaxon = sTaxon;
final String sData = sStr.substring(iEnd);
for (int k = 0; k < sData.length(); k++) {
if (!Character.isWhitespace(sData.charAt(k))) {
seqLen++;
}
}
// Do this once outside loop- save on multiple regex compilations
//sData = sData.replaceAll("\\s", "");
// String [] sStrs = sStr.split("\\s+");
// String sTaxon = sStrs[0];
// for (int k = 1; k < sStrs.length - 1; k++) {
// sTaxon += sStrs[k];
// sTaxon = sTaxon.replaceAll("'", "");
// System.err.println(sTaxon);
// String sData = sStrs[sStrs.length - 1];
if (seqMap.containsKey(sTaxon)) {
seqMap.put(sTaxon, seqMap.get(sTaxon).append(sData));
} else {
seqMap.put(sTaxon, new StringBuilder(sData));
sTaxa.add(sTaxon);
}
}
if (nTaxa > 0 && sTaxa.size() > nTaxa) {
throw new Exception("Wrong number of taxa. Perhaps a typo in one of the taxa: " + sTaxa);
}
HashSet<String> sortedAmbiguities = new HashSet<>();
for (final String sTaxon : sTaxa) {
final StringBuilder bsData = seqMap.get(sTaxon);
String sData = bsData.toString().replaceAll("\\s", "");
seqMap.put(sTaxon, new StringBuilder(sData));
//collect all ambiguities in the sequence
List<String> ambiguities = new ArrayList<String>();
Matcher m = Pattern.compile("\\{(.*?)\\}").matcher(sData);
while (m.find()) {
int mLength = m.group().length();
ambiguities.add(m.group().substring(1, mLength-1));
}
//sort elements of ambiguity sets
String sData_without_ambiguities = sData.replaceAll("\\{(.*?)\\}", "?");
for (String amb : ambiguities) {
List<Integer> ambInt = new ArrayList<>();
for (int i=0; i<amb.length(); i++) {
char c = amb.charAt(i);
if (c >= '0' && c <= '9') {
ambInt.add(Integer.parseInt(amb.charAt(i) + ""));
} else {
// ignore
if (sData != sData_without_ambiguities) {
Log.warning.println("Ambiguity found in " + sTaxon + " that is treated as missing value");
}
sData = sData_without_ambiguities;
}
}
Collections.sort(ambInt);
String ambStr = "";
for (int i=0; i<ambInt.size(); i++) {
ambStr += Integer.toString(ambInt.get(i));
}
sortedAmbiguities.add(ambStr);
}
//check the length of the sequence (treat ambiguity sets as single characters)
if (sData_without_ambiguities.length() != nChar) {
throw new Exception(sStr + "\nExpected sequence of length " + nChar + " instead of " + sData.length() + " for taxon " + sTaxon);
}
// map to standard missing and gap chars
sData = sData.replace(sMissing.charAt(0), DataType.MISSING_CHAR);
sData = sData.replace(sGap.charAt(0), DataType.GAP_CHAR);
// resolve matching char, if any
if (sMatchChar != null && sData.contains(sMatchChar)) {
final char cMatchChar = sMatchChar.charAt(0);
final String sBaseData = seqMap.get(sTaxa.get(0)).toString();
for (int i = 0; i < sData.length(); i++) {
if (sData.charAt(i) == cMatchChar) {
final char cReplaceChar = sBaseData.charAt(i);
sData = sData.substring(0, i) + cReplaceChar + (i + 1 < sData.length() ? sData.substring(i + 1) : "");
}
}
}
// alignment.setInputValue(sTaxon, sData);
final Sequence sequence = new Sequence();
sequence.init(nTotalCount, sTaxon, sData);
sequence.setID(generateSequenceID(sTaxon));
alignment.sequenceInput.setValue(sequence, alignment);
}
if (alignment.dataTypeInput.get().equals("standard")) {
//convert sortedAmbiguities to a whitespace separated string of ambiguities
String ambiguitiesStr = "";
for (String sAmb: sortedAmbiguities) {
ambiguitiesStr += sAmb + " ";
}
if (ambiguitiesStr.length() > 0) {
ambiguitiesStr = ambiguitiesStr.substring(0, ambiguitiesStr.length()-1);
}
alignment.userDataTypeInput.get().initByName("ambiguities", ambiguitiesStr);
}
alignment.initAndValidate();
if (nTaxa > 0 && nTaxa != alignment.getNrTaxa()) {
throw new Exception("dimensions block says there are " + nTaxa + " taxa, but there were " + alignment.getNrTaxa() + " taxa found");
}
return alignment;
} // parseDataBlock
/**
* parse assumptions block
* begin assumptions;
* charset firsthalf = 1-449;
* charset secondhalf = 450-898;
* charset third = 1-457\3 662-896\3;
* end;
*
* begin assumptions;
* wtset MySoapWeights (VECTOR) = 13 13 13 50 50 88 8
* end;
*
*/
void parseAssumptionsBlock(final BufferedReader fin) throws Exception {
String sStr;
do {
sStr = nextLine(fin);
if (sStr.toLowerCase().matches("\\s*charset\\s.*")) {
// remove text in brackets (as TreeBase files are wont to contain)
sStr = sStr.replaceAll("\\(.*\\)", "");
// clean up spaces
sStr = sStr.replaceAll("^\\s+", "");
sStr = sStr.replaceAll("\\s*-\\s*", "-");
sStr = sStr.replaceAll("\\s*\\\\\\s*", "\\\\");
sStr = sStr.replaceAll("\\s*;", "");
final String[] sStrs = sStr.trim().split("\\s+");
final String sID = sStrs[1];
String sRange = "";
for (int i = 3; i < sStrs.length; i++) {
sRange += sStrs[i] + " ";
}
sRange = sRange.trim().replace(' ', ',');
final FilteredAlignment alignment = new FilteredAlignment();
alignment.setID(sID);
alignment.alignmentInput.setValue(m_alignment, alignment);
alignment.filterInput.setValue(sRange, alignment);
alignment.initAndValidate();
filteredAlignments.add(alignment);
} else if (sStr.toLowerCase().matches("\\s*wtset\\s.*")) {
String [] strs = sStr.split("=");
if (strs.length > 1) {
sStr = strs[strs.length - 1].trim();
strs = sStr.split("\\s+");
int [] weights = new int[strs.length];
for (int i = 0; i< strs.length; i++) {
weights[i] = Integer.parseInt(strs[i]);
}
if (m_alignment != null) {
if (weights.length != m_alignment.getSiteCount()) {
throw new RuntimeException("Number of weights (" + weights.length+ ") " +
"does not match number of sites in alignment(" + m_alignment.getSiteCount()+ ")");
}
StringBuilder weightStr = new StringBuilder();
for (String str : strs) {
weightStr.append(str);
weightStr.append(',');
}
weightStr.delete(weightStr.length() - 1, weightStr.length());
m_alignment.siteWeightsInput.setValue(weightStr.toString(), m_alignment);
m_alignment.initAndValidate();
} else {
Log.warning.println("WTSET was specified before alignment. WTSET is ignored.");
}
}
}
} while (!sStr.toLowerCase().contains("end;"));
}
/**
* parse sets block
* BEGIN Sets;
* TAXSET 'con' = 'con_SL_Gert2' 'con_SL_Tran6' 'con_SL_Tran7' 'con_SL_Gert6';
* TAXSET 'spa' = 'spa_138a_Cerb' 'spa_JB_Eyre1' 'spa_JB_Eyre2';
* END; [Sets]
*/
void parseSetsBlock(final BufferedReader fin) throws Exception {
String sStr;
do {
sStr = nextLine(fin);
if (sStr.toLowerCase().matches("\\s*taxset\\s.*")) {
sStr = sStr.replaceAll("^\\s+", "");
sStr = sStr.replaceAll(";", "");
final String[] sStrs = sStr.split("\\s+");
String sID = sStrs[1];
sID = sID.replaceAll("'\"", "");
final TaxonSet set = new TaxonSet();
set.setID(sID);
for (int i = 3; i < sStrs.length; i++) {
sID = sStrs[i];
sID = sID.replaceAll("'\"", "");
final Taxon taxon = new Taxon();
taxon.setID(sID);
set.taxonsetInput.setValue(taxon, set);
}
taxonsets.add(set);
}
} while (!sStr.toLowerCase().contains("end;"));
}
public static String generateSequenceID(final String sTaxon) {
String sID = "seq_" + sTaxon;
int i = 0;
while (g_sequenceIDs.contains(sID + (i > 0 ? i : ""))) {
i++;
}
sID = sID + (i > 0 ? i : "");
g_sequenceIDs.add(sID);
return sID;
}
/**
* read line from nexus file *
*/
String readLine(final BufferedReader fin) throws Exception {
if (!fin.ready()) {
return null;
}
lineNr++;
return fin.readLine();
}
/**
* read next line from nexus file that is not a comment and not empty *
*/
String nextLine(final BufferedReader fin) throws Exception {
String sStr = readLine(fin);
if (sStr == null) {
return null;
}
if (sStr.contains("[")) {
final int iStart = sStr.indexOf('[');
int iEnd = sStr.indexOf(']', iStart);
while (iEnd < 0) {
sStr += readLine(fin);
iEnd = sStr.indexOf(']', iStart);
}
sStr = sStr.substring(0, iStart) + sStr.substring(iEnd + 1);
if (sStr.matches("^\\s*$")) {
return nextLine(fin);
}
}
if (sStr.matches("^\\s*$")) {
return nextLine(fin);
}
return sStr;
}
/**
* return attribute value as a string *
*/
String getAttValue(final String sAttribute, final String sStr) {
final Pattern pattern = Pattern.compile(".*" + sAttribute + "\\s*=\\s*([^\\s;]+).*");
final Matcher matcher = pattern.matcher(sStr.toLowerCase());
if (!matcher.find()) {
return null;
}
String sAtt = matcher.group(1);
if (sAtt.startsWith("\"") && sAtt.endsWith("\"")) {
final int iStart = matcher.start(1);
sAtt = sStr.substring(iStart + 1, sStr.indexOf('"', iStart + 1));
}
return sAtt;
}
private ArrayList<String> readInCharstatelablesTokens(final BufferedReader fin) throws Exception {
ArrayList<String> tokens = new ArrayList<>();
String token="";
final int READING=0, OPENQUOTE=1, WAITING=2;
int mode = WAITING;
int numberOfQuotes=0;
boolean endOfBlock=false;
String sStr;
while (!endOfBlock) {
sStr = nextLine(fin);
Character nextChar;
for (int i=0; i< sStr.length(); i++) {
nextChar=sStr.charAt(i);
switch (mode) {
case WAITING:
if (!Character.isWhitespace(nextChar)) {
if (nextChar == '\'') {
mode=OPENQUOTE;
} else if (nextChar == '/' || nextChar == ',') {
tokens.add(nextChar.toString());
token="";
} else if (nextChar == ';') {
endOfBlock = true;
} else {
token=token+nextChar;
mode=READING;
}
}
break;
case READING:
if (nextChar == '\'') {
tokens.add(token);
token="";
mode=OPENQUOTE;
} else if (nextChar == '/' || nextChar == ',') {
tokens.add(token);
tokens.add(nextChar.toString());
token="";
mode=WAITING;
} else if (nextChar == ';') {
tokens.add(token);
endOfBlock = true;
} else if (Character.isWhitespace(nextChar)) {
tokens.add(token);
token="";
mode=WAITING;
} else {
token=token+nextChar;
}
break;
case OPENQUOTE:
if (nextChar == '\'') {
numberOfQuotes++;
} else {
if (numberOfQuotes % 2 == 0) {
for (int ind=0; ind< numberOfQuotes/2; ind++) {
token=token+"'";
}
token=token+nextChar;
} else {
for (int ind=0; ind< numberOfQuotes/2; ind++) {
token=token+"'";
}
tokens.add(token);
token="";
if (nextChar == '/' || nextChar == ',') {
tokens.add(nextChar.toString());
mode=WAITING;
} else if (nextChar == ';') {
endOfBlock = true;
} else if (Character.isWhitespace(nextChar)) {
mode=WAITING;
} else {
token=token+nextChar;
mode=READING;
}
}
numberOfQuotes=0;
}
break;
default:
break;
}
}
}
if (!tokens.get(tokens.size()-1).equals(",")) {
tokens.add(",");
}
return tokens;
}
private ArrayList<UserDataType> processCharstatelabelsTokens(ArrayList<String> tokens, int[] maxNumberOfStates) throws Exception {
ArrayList<UserDataType> charDescriptions = new ArrayList<>();
final int CHAR_NR=0, CHAR_NAME=1, STATES=2;
int mode = CHAR_NR;
int charNumber = -1;
String charName = "";
ArrayList<String> states = new ArrayList<>();
for (String token:tokens) {
switch (mode) {
case CHAR_NR:
charNumber = Integer.parseInt(token);
mode = CHAR_NAME;
break;
case CHAR_NAME:
if (token.equals("/")) {
mode = STATES;
} else if (token.equals(",")) {
if (charNumber > charDescriptions.size()+1) {
throw new Exception("Character descriptions should go in the ascending order and there " +
"should not be any description missing.");
}
charDescriptions.add(new UserDataType(charName, states));
maxNumberOfStates[0] = Math.max(maxNumberOfStates[0], states.size());
charNumber = -1;
charName = "";
states = new ArrayList<>();
mode = CHAR_NR;
} else {
charName = token;
}
break;
case STATES:
if (token.equals(",")) {
if (charNumber > charDescriptions.size()+1) {
throw new Exception("Character descriptions should go in the ascending order and there " +
"should not be any description missing.");
}
charDescriptions.add(new UserDataType(charName, states));
maxNumberOfStates[0] = Math.max(maxNumberOfStates[0], states.size());
charNumber = -1;
charName = "";
states = new ArrayList<>();
mode = CHAR_NR;
} else {
states.add(token);
}
default:
break;
}
}
return charDescriptions;
}
public static void main(final String[] args) {
try {
final NexusParser parser = new NexusParser();
parser.parseFile(new File(args[0]));
if (parser.taxa != null) {
System.out.println(parser.taxa.size() + " taxa");
System.out.println(Arrays.toString(parser.taxa.toArray(new String[parser.taxa.size()])));
}
if (parser.trees != null) {
System.out.println(parser.trees.size() + " trees");
}
if (parser.m_alignment != null) {
final String sXML = new XMLProducer().toXML(parser.m_alignment);
System.out.println(sXML);
}
if (parser.traitSet != null) {
final String sXML = new XMLProducer().toXML(parser.traitSet);
System.out.println(sXML);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // main
} // class NexusParser
|
package api.web.gw2.mapping.core;
public final class ContinentDimensions {
/**
* The empty instance singleton.
*/
private static final ContinentDimensions EMPTY = new ContinentDimensions();
/**
* The width.
*/
private final double width;
/**
* The height.
*/
private final double height;
/**
* Creates a new empty instance.
*/
private ContinentDimensions() {
this(0, 0);
}
/**
* Creates a new instance.
* @param width The width.
* @param height The height.
*/
private ContinentDimensions(final double width, final double height) {
this.width = width;
this.height = height;
}
/**
* Gets the empty singleton instance.
* @return A {@code ContinentDimensions} instance, never {@code null}.
*/
public static ContinentDimensions empty() {
return EMPTY;
}
/**
* Factory method.
* <br>Negatives values will be shifted back to 0.
* @param width The width.
* @param height The height.
* @return A {@code ContinentDimensions} instance, never {@code null}.
* If {@code width} and {@code height} ≤ 0 the empty instance is returned.
*/
public static ContinentDimensions of(final double width, final double height) {
final double w = Math.max(0, width);
final double h = Math.max(0, height);
if (w == 0 && h == 0) {
return empty();
} else {
return new ContinentDimensions(width, height);
}
}
/**
* Gets the width of this continent dimension.
* @return A {@code double} ≥ 0.
*/
public double getWidth() {
return width;
}
/**
* Gets the height of this continent dimension.
* @return A {@code double} ≥ 0.
*/
public double getHeight() {
return height;
}
}
|
package be.ibridge.kettle.core.dialog;
import java.util.ArrayList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Props;
import be.ibridge.kettle.core.WindowProperty;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.database.DatabaseMeta;
import be.ibridge.kettle.core.database.GenericDatabaseMeta;
import be.ibridge.kettle.core.database.SAPR3DatabaseMeta;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.trans.step.BaseStepDialog;
/**
*
* Dialog that allows you to edit the settings of a database connection.
*
* @see <code>DatabaseInfo</code>
* @author Matt
* @since 18-05-2003
*
*/
public class DatabaseDialog extends Dialog
{
private DatabaseMeta connection;
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wDbTab, wOracleTab, wIfxTab, wSAPTab, wGenericTab;
private Composite wDbComp, wOracleComp, wIfxComp, wSAPComp, wGenericComp;
private FormData fdDbComp, fdOracleComp, fdIfxComp, fdSAPComp, fdGenericComp;
private Shell shell;
private Label wlConn, wlConnType, wlConnAcc, wlHostName, wlDBName, wlPort, wlServername, wlUsername, wlPassword, wlData, wlIndex;
private Text wConn, wHostName, wDBName, wPort, wServername, wUsername, wPassword, wData, wIndex;
private List wConnType, wConnAcc;
private FormData fdlConn, fdlConnType, fdlConnAcc, fdlPort, fdlHostName, fdlDBName, fdlServername, fdlUsername, fdlPassword, fdlData, fdlIndex;
private FormData fdConn, fdConnType, fdConnAcc, fdPort, fdHostName, fdDBName, fdServername, fdUsername, fdPassword, fdData, fdIndex;
// SAP
private Label wlSAPLanguage, wlSAPSystemNumber, wlSAPClient;
private Text wSAPLanguage, wSAPSystemNumber, wSAPClient;
private FormData fdlSAPLanguage, fdlSAPSystemNumber, fdlSAPClient;
private FormData fdSAPLanguage, fdSAPSystemNumber, fdSAPClient;
// Generic
private Label wlURL, wlDriverClass;
private Text wURL, wDriverClass;
private FormData fdlURL, fdlDriverClass;
private FormData fdURL, fdDriverClass;
private Button wOK, wTest, wExp, wList, wCancel;
private String connectionName;
private ModifyListener lsMod;
private boolean changed;
private Props props;
private String previousDatabaseType;
private ArrayList databases;
public DatabaseDialog(Shell par, int style, LogWriter lg, DatabaseMeta conn, Props pr)
{
super(par, style);
connection=conn;
connectionName=conn.getName();
props=pr;
this.databases = null;
}
public String open()
{
Shell parent = getParent();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN );
props.setLook(shell);
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
connection.setChanged();
}
};
changed = connection.hasChanged();
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setText("Connection information");
shell.setLayout (formLayout);
// First, add the buttons...
// Buttons
wOK = new Button(shell, SWT.PUSH);
wOK.setText(" &OK ");
wTest = new Button(shell, SWT.PUSH);
wTest.setText(" &Test ");
wExp = new Button(shell, SWT.PUSH);
wExp.setText(" &Explore ");
wList = new Button(shell, SWT.PUSH);
wList.setText(" Feature &List ");
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(" &Cancel ");
Button[] buttons = new Button[] { wOK, wTest, wExp, wList, wCancel };
BaseStepDialog.positionBottomButtons(shell, buttons, margin, null);
// The rest stays above the buttons...
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TABLE);
// START OF DB TAB ///
wDbTab=new CTabItem(wTabFolder, SWT.NONE);
wDbTab.setText("General");
wDbComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wDbComp);
FormLayout GenLayout = new FormLayout();
GenLayout.marginWidth = 3;
GenLayout.marginHeight = 3;
wDbComp.setLayout(GenLayout);
// What's the connection name?
wlConn = new Label(wDbComp, SWT.RIGHT);
props.setLook(wlConn);
wlConn.setText("Connection name: ");
fdlConn = new FormData();
fdlConn.top = new FormAttachment(0, 0);
fdlConn.left = new FormAttachment(0, 0); // First one in the left top corner
fdlConn.right = new FormAttachment(middle, -margin);
wlConn.setLayoutData(fdlConn);
wConn = new Text(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook(wConn);
wConn.addModifyListener(lsMod);
fdConn = new FormData();
fdConn.top = new FormAttachment(0, 0);
fdConn.left = new FormAttachment(middle, 0); // To the right of the label
fdConn.right= new FormAttachment(95, 0);
wConn.setLayoutData(fdConn);
// What types are there?
wlConnType = new Label(wDbComp, SWT.RIGHT);
wlConnType.setText("Connection type: ");
props.setLook(wlConnType);
fdlConnType = new FormData();
fdlConnType.top = new FormAttachment(wConn, margin); // below the line above
fdlConnType.left = new FormAttachment(0,0);
fdlConnType.right = new FormAttachment(middle, -margin);
wlConnType.setLayoutData(fdlConnType);
wConnType = new List(wDbComp, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE | SWT.V_SCROLL);
props.setLook(wConnType);
String[] dbtypes=DatabaseMeta.getDBTypeDescLongList();
for (int i=0;i<dbtypes.length;i++)
{
wConnType.add( dbtypes[i] );
}
props.setLook(wConnType);
fdConnType = new FormData();
fdConnType.top = new FormAttachment(wConn, margin);
fdConnType.left = new FormAttachment(middle, 0); // right of the label
fdConnType.right = new FormAttachment(95, 0);
fdConnType.bottom = new FormAttachment(wConn, 150);
wConnType.setLayoutData(fdConnType);
// What access types are there?
wlConnAcc = new Label(wDbComp, SWT.RIGHT);
wlConnAcc.setText("Method of access: ");
props.setLook(wlConnAcc);
fdlConnAcc = new FormData();
fdlConnAcc.top = new FormAttachment(wConnType, margin); // below the line above
fdlConnAcc.left = new FormAttachment(0,0);
fdlConnAcc.right= new FormAttachment(middle, -margin);
wlConnAcc.setLayoutData(fdlConnAcc);
wConnAcc = new List(wDbComp, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE | SWT.V_SCROLL);
props.setLook(wConnAcc);
props.setLook(wConnAcc);
fdConnAcc = new FormData();
fdConnAcc.top = new FormAttachment(wConnType, margin);
fdConnAcc.left = new FormAttachment(middle, 0); // right of the label
fdConnAcc.right = new FormAttachment(95, 0);
//fdConnAcc.bottom = new FormAttachment(wConnType, 50);
wConnAcc.setLayoutData(fdConnAcc);
// Hostname
wlHostName = new Label(wDbComp, SWT.RIGHT);
wlHostName.setText("Server host name: ");
props.setLook(wlHostName);
fdlHostName = new FormData();
fdlHostName.top = new FormAttachment(wConnAcc, margin);
fdlHostName.left = new FormAttachment(0,0);
fdlHostName.right= new FormAttachment(middle, -margin);
wlHostName.setLayoutData(fdlHostName);
wHostName = new Text(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook(wHostName);
wHostName.addModifyListener(lsMod);
fdHostName = new FormData();
fdHostName.top = new FormAttachment(wConnAcc, margin);
fdHostName.left = new FormAttachment(middle, 0);
fdHostName.right= new FormAttachment(95, 0);
wHostName.setLayoutData(fdHostName);
// DBName
wlDBName = new Label(wDbComp, SWT.RIGHT );
wlDBName.setText("Database name: ");
props.setLook(wlDBName);
fdlDBName = new FormData();
fdlDBName.top = new FormAttachment(wHostName, margin);
fdlDBName.left = new FormAttachment(0,0);
fdlDBName.right= new FormAttachment(middle, -margin);
wlDBName.setLayoutData(fdlDBName);
wDBName = new Text(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook(wDBName);
wDBName.addModifyListener(lsMod);
fdDBName = new FormData();
fdDBName.top = new FormAttachment(wHostName, margin);
fdDBName.left = new FormAttachment(middle, 0);
fdDBName.right= new FormAttachment(95, 0);
wDBName.setLayoutData(fdDBName);
// Port
wlPort = new Label(wDbComp, SWT.RIGHT );
wlPort.setText("Port number: ");
props.setLook(wlPort);
fdlPort = new FormData();
fdlPort.top = new FormAttachment(wDBName, margin);
fdlPort.left = new FormAttachment(0,0);
fdlPort.right= new FormAttachment(middle, -margin);
wlPort.setLayoutData(fdlPort);
wPort = new Text(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook(wPort);
wPort.addModifyListener(lsMod);
fdPort = new FormData();
fdPort.top = new FormAttachment(wDBName, margin);
fdPort.left = new FormAttachment(middle, 0);
fdPort.right= new FormAttachment(95, 0);
wPort.setLayoutData(fdPort);
// Username
wlUsername = new Label(wDbComp, SWT.RIGHT );
wlUsername.setText("Username: ");
props.setLook(wlUsername);
fdlUsername = new FormData();
fdlUsername.top = new FormAttachment(wPort, margin);
fdlUsername.left = new FormAttachment(0,0);
fdlUsername.right= new FormAttachment(middle, -margin);
wlUsername.setLayoutData(fdlUsername);
wUsername = new Text(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook(wUsername);
wUsername.addModifyListener(lsMod);
fdUsername = new FormData();
fdUsername.top = new FormAttachment(wPort, margin);
fdUsername.left = new FormAttachment(middle, 0);
fdUsername.right= new FormAttachment(95, 0);
wUsername.setLayoutData(fdUsername);
// Password
wlPassword = new Label(wDbComp, SWT.RIGHT );
wlPassword.setText("Password: ");
props.setLook(wlPassword);
fdlPassword = new FormData();
fdlPassword.top = new FormAttachment(wUsername, margin);
fdlPassword.left = new FormAttachment(0,0);
fdlPassword.right= new FormAttachment(middle, -margin);
wlPassword.setLayoutData(fdlPassword);
wPassword = new Text(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook(wPassword);
wPassword.setEchoChar('*');
wPassword.addModifyListener(lsMod);
fdPassword = new FormData();
fdPassword.top = new FormAttachment(wUsername, margin);
fdPassword.left = new FormAttachment(middle, 0);
fdPassword.right= new FormAttachment(95, 0);
wPassword.setLayoutData(fdPassword);
fdDbComp=new FormData();
fdDbComp.left = new FormAttachment(0, 0);
fdDbComp.top = new FormAttachment(0, 0);
fdDbComp.right = new FormAttachment(100, 0);
fdDbComp.bottom= new FormAttachment(100, 0);
wDbComp.setLayoutData(fdDbComp);
wDbComp.layout();
wDbTab.setControl(wDbComp);
/// END OF GEN TAB
// START OF ORACLE TAB///
wOracleTab=new CTabItem(wTabFolder, SWT.NONE);
wOracleTab.setText("Oracle");
FormLayout oracleLayout = new FormLayout ();
oracleLayout.marginWidth = 3;
oracleLayout.marginHeight = 3;
wOracleComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wOracleComp);
wOracleComp.setLayout(oracleLayout);
// What's the data tablespace name?
wlData = new Label(wOracleComp, SWT.RIGHT);
props.setLook(wlData);
wlData.setText("Tablespace for data: ");
fdlData = new FormData();
fdlData.top = new FormAttachment(0, 0);
fdlData.left = new FormAttachment(0, 0); // First one in the left top corner
fdlData.right = new FormAttachment(middle, -margin);
wlData.setLayoutData(fdlData);
wData = new Text(wOracleComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wData.setText( NVL(connection.getDataTablespace()==null?"":connection.getDataTablespace(), "") );
props.setLook(wData);
wData.addModifyListener(lsMod);
fdData = new FormData();
fdData.top = new FormAttachment(0, 0);
fdData.left = new FormAttachment(middle, 0); // To the right of the label
fdData.right= new FormAttachment(95, 0);
wData.setLayoutData(fdData);
// What's the index tablespace name?
wlIndex = new Label(wOracleComp, SWT.RIGHT);
props.setLook(wlIndex);
wlIndex.setText("Tablespace for indexes: ");
fdlIndex = new FormData();
fdlIndex.top = new FormAttachment(wData, margin);
fdlIndex.left = new FormAttachment(0, 0); // First one in the left top corner
fdlIndex.right = new FormAttachment(middle, -margin);
wlIndex.setLayoutData(fdlIndex);
wIndex = new Text(wOracleComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wIndex.setText( NVL(connection.getIndexTablespace()==null?"":connection.getIndexTablespace(), "") );
props.setLook(wIndex);
wIndex.addModifyListener(lsMod);
fdIndex = new FormData();
fdIndex.top = new FormAttachment(wData, margin);
fdIndex.left = new FormAttachment(middle, 0); // To the right of the label
fdIndex.right= new FormAttachment(95, 0);
wIndex.setLayoutData(fdIndex);
fdOracleComp = new FormData();
fdOracleComp.left = new FormAttachment(0, 0);
fdOracleComp.top = new FormAttachment(0, 0);
fdOracleComp.right = new FormAttachment(100, 0);
fdOracleComp.bottom= new FormAttachment(100, 0);
wOracleComp.setLayoutData(fdOracleComp);
wOracleComp.layout();
wOracleTab.setControl(wOracleComp);
// START OF INFORMIX TAB///
wIfxTab=new CTabItem(wTabFolder, SWT.NONE);
wIfxTab.setText("Informix");
FormLayout ifxLayout = new FormLayout ();
ifxLayout.marginWidth = 3;
ifxLayout.marginHeight = 3;
wIfxComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wIfxComp);
wIfxComp.setLayout(ifxLayout);
// Servername
wlServername = new Label(wIfxComp, SWT.RIGHT );
wlServername.setText("Informix Servername: ");
props.setLook(wlServername);
fdlServername = new FormData();
fdlServername.top = new FormAttachment(0, margin);
fdlServername.left = new FormAttachment(0,0);
fdlServername.right= new FormAttachment(middle, -margin);
wlServername.setLayoutData(fdlServername);
wServername = new Text(wIfxComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook(wServername);
wServername.addModifyListener(lsMod);
fdServername = new FormData();
fdServername.top = new FormAttachment(0, margin);
fdServername.left = new FormAttachment(middle, 0);
fdServername.right= new FormAttachment(95, 0);
wServername.setLayoutData(fdServername);
fdIfxComp = new FormData();
fdIfxComp.left = new FormAttachment(0, 0);
fdIfxComp.top = new FormAttachment(0, 0);
fdIfxComp.right = new FormAttachment(100, 0);
fdIfxComp.bottom= new FormAttachment(100, 0);
wIfxComp.setLayoutData(fdIfxComp);
wIfxComp.layout();
wIfxTab.setControl(wIfxComp);
// START OF SAP TAB///
wSAPTab=new CTabItem(wTabFolder, SWT.NONE);
wSAPTab.setText("SAP R/3");
FormLayout sapLayout = new FormLayout ();
sapLayout.marginWidth = 3;
sapLayout.marginHeight = 3;
wSAPComp = new Composite(wTabFolder, SWT.NONE);
props.setLook( wSAPComp);
wSAPComp.setLayout(sapLayout);
// wSAPLanguage, wSSAPystemNumber, wSAPSystemID
// Language
wlSAPLanguage = new Label(wSAPComp, SWT.RIGHT );
wlSAPLanguage.setText("Language ");
props.setLook( wlSAPLanguage);
fdlSAPLanguage = new FormData();
fdlSAPLanguage.top = new FormAttachment(0, margin);
fdlSAPLanguage.left = new FormAttachment(0,0);
fdlSAPLanguage.right= new FormAttachment(middle, -margin);
wlSAPLanguage.setLayoutData(fdlSAPLanguage);
wSAPLanguage = new Text(wSAPComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wSAPLanguage);
wSAPLanguage.addModifyListener(lsMod);
fdSAPLanguage = new FormData();
fdSAPLanguage.top = new FormAttachment(0, margin);
fdSAPLanguage.left = new FormAttachment(middle, 0);
fdSAPLanguage.right= new FormAttachment(95, 0);
wSAPLanguage.setLayoutData(fdSAPLanguage);
// SystemNumber
wlSAPSystemNumber = new Label(wSAPComp, SWT.RIGHT );
wlSAPSystemNumber.setText("System Number ");
props.setLook( wlSAPSystemNumber);
fdlSAPSystemNumber = new FormData();
fdlSAPSystemNumber.top = new FormAttachment(wSAPLanguage, margin);
fdlSAPSystemNumber.left = new FormAttachment(0,0);
fdlSAPSystemNumber.right= new FormAttachment(middle, -margin);
wlSAPSystemNumber.setLayoutData(fdlSAPSystemNumber);
wSAPSystemNumber = new Text(wSAPComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wSAPSystemNumber);
wSAPSystemNumber.addModifyListener(lsMod);
fdSAPSystemNumber = new FormData();
fdSAPSystemNumber.top = new FormAttachment(wSAPLanguage, margin);
fdSAPSystemNumber.left = new FormAttachment(middle, 0);
fdSAPSystemNumber.right= new FormAttachment(95, 0);
wSAPSystemNumber.setLayoutData(fdSAPSystemNumber);
// SystemID
wlSAPClient = new Label(wSAPComp, SWT.RIGHT );
wlSAPClient.setText("SAP Client");
props.setLook( wlSAPClient);
fdlSAPClient = new FormData();
fdlSAPClient.top = new FormAttachment(wSAPSystemNumber, margin);
fdlSAPClient.left = new FormAttachment(0,0);
fdlSAPClient.right= new FormAttachment(middle, -margin);
wlSAPClient.setLayoutData(fdlSAPClient);
wSAPClient = new Text(wSAPComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wSAPClient);
wSAPClient.addModifyListener(lsMod);
fdSAPClient = new FormData();
fdSAPClient.top = new FormAttachment(wSAPSystemNumber, margin);
fdSAPClient.left = new FormAttachment(middle, 0);
fdSAPClient.right= new FormAttachment(95, 0);
wSAPClient.setLayoutData(fdSAPClient);
fdSAPComp = new FormData();
fdSAPComp.left = new FormAttachment(0, 0);
fdSAPComp.top = new FormAttachment(0, 0);
fdSAPComp.right = new FormAttachment(100, 0);
fdSAPComp.bottom= new FormAttachment(100, 0);
wSAPComp.setLayoutData(fdSAPComp);
wSAPComp.layout();
wSAPTab.setControl(wSAPComp);
// START OF DB TAB///
wGenericTab=new CTabItem(wTabFolder, SWT.NONE);
wGenericTab.setText("Generic");
wGenericTab.setToolTipText("Settings in case you want to use a generic database with a non-supported JDBC driver");
FormLayout genericLayout = new FormLayout ();
genericLayout.marginWidth = 3;
genericLayout.marginHeight = 3;
wGenericComp = new Composite(wTabFolder, SWT.NONE);
props.setLook( wGenericComp );
wGenericComp.setLayout(genericLayout);
// URL
wlURL = new Label(wGenericComp, SWT.RIGHT );
wlURL.setText("URL ");
props.setLook(wlURL);
fdlURL = new FormData();
fdlURL.top = new FormAttachment(0, margin);
fdlURL.left = new FormAttachment(0,0);
fdlURL.right= new FormAttachment(middle, -margin);
wlURL.setLayoutData(fdlURL);
wURL = new Text(wGenericComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wURL);
wURL.addModifyListener(lsMod);
fdURL = new FormData();
fdURL.top = new FormAttachment(0, margin);
fdURL.left = new FormAttachment(middle, 0);
fdURL.right= new FormAttachment(95, 0);
wURL.setLayoutData(fdURL);
// Driver class
wlDriverClass = new Label(wGenericComp, SWT.RIGHT );
wlDriverClass.setText("Driver class ");
props.setLook( wlDriverClass);
fdlDriverClass = new FormData();
fdlDriverClass.top = new FormAttachment(wURL, margin);
fdlDriverClass.left = new FormAttachment(0,0);
fdlDriverClass.right= new FormAttachment(middle, -margin);
wlDriverClass.setLayoutData(fdlDriverClass);
wDriverClass = new Text(wGenericComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wDriverClass);
wDriverClass.addModifyListener(lsMod);
fdDriverClass = new FormData();
fdDriverClass.top = new FormAttachment(wURL, margin);
fdDriverClass.left = new FormAttachment(middle, 0);
fdDriverClass.right= new FormAttachment(95, 0);
wDriverClass.setLayoutData(fdDriverClass);
fdGenericComp = new FormData();
fdGenericComp.left = new FormAttachment(0, 0);
fdGenericComp.top = new FormAttachment(0, 0);
fdGenericComp.right = new FormAttachment(100, 0);
fdGenericComp.bottom= new FormAttachment(100, 0);
wGenericComp.setLayoutData(fdGenericComp);
wGenericComp.layout();
wGenericTab.setControl(wGenericComp);
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(0, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(wOK, -margin);
wTabFolder.setLayoutData(fdTabFolder);
// Add listeners
wOK.addListener(SWT.Selection, new Listener ()
{
public void handleEvent (Event e)
{
handleOK();
}
}
);
wCancel.addListener(SWT.Selection, new Listener ()
{
public void handleEvent (Event e)
{
cancel();
}
}
);
wTest.addListener(SWT.Selection, new Listener ()
{
public void handleEvent (Event e)
{
test();
}
}
);
wExp.addListener(SWT.Selection, new Listener ()
{
public void handleEvent (Event e)
{
explore();
}
}
);
wList.addListener(SWT.Selection, new Listener ()
{
public void handleEvent (Event e)
{
showFeatureList();
}
}
);
SelectionAdapter selAdapter=new SelectionAdapter()
{
public void widgetDefaultSelected(SelectionEvent e)
{
handleOK();
}
};
wHostName.addSelectionListener(selAdapter);
wDBName.addSelectionListener(selAdapter);
wPort.addSelectionListener(selAdapter);
wUsername.addSelectionListener(selAdapter);
wPassword.addSelectionListener(selAdapter);
wConn.addSelectionListener(selAdapter);
wData.addSelectionListener(selAdapter);
wIndex.addSelectionListener(selAdapter);
SelectionAdapter lsTypeAcc =
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
enableFields();
setPortNumber();
}
};
wConnType.addSelectionListener( lsTypeAcc );
wConnAcc.addSelectionListener( lsTypeAcc );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
wTabFolder.setSelection(0);
getData();
enableFields();
WindowProperty winprop = props.getScreen(shell.getText());
if (winprop!=null) winprop.setShell(shell); else shell.pack();
connection.setChanged(changed);
shell.open();
Display display = parent.getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
return connectionName;
}
public void dispose()
{
props.setScreen(new WindowProperty(shell));
shell.dispose();
}
public void setDatabases(ArrayList databases)
{
this.databases = databases;
}
public void getData()
{
wConn.setText( NVL(connection==null?"":connection.getName(), "") );
wConnType.select( connection.getDatabaseType() - 1);
wConnType.showSelection();
previousDatabaseType = DatabaseMeta.getDBTypeDesc(wConnType.getSelectionIndex()+1);
setAccessList();
String accessList[] = wConnAcc.getItems();
int accessIndex = Const.indexOfString(connection.getAccessTypeDesc(), accessList);
wConnAcc.select( accessIndex );
wConnAcc.showSelection();
wHostName.setText( NVL(connection.getHostname(), "") );
wDBName.setText( NVL(connection.getDatabaseName(), "") );
wPort.setText( NVL(connection.getDatabasePortNumberString(), "") );
wServername.setText( NVL(connection.getServername(), "") );
wUsername.setText( NVL(connection.getUsername(), "") );
wPassword.setText( NVL(connection.getPassword(), "") );
wData.setText( NVL(connection.getDataTablespace(), "") );
wIndex.setText( NVL(connection.getIndexTablespace(), "") );
wSAPLanguage.setText( connection.getAttributes().getProperty(SAPR3DatabaseMeta.ATTRIBUTE_SAP_LANGUAGE, ""));
wSAPSystemNumber.setText( connection.getAttributes().getProperty(SAPR3DatabaseMeta.ATTRIBUTE_SAP_SYSTEM_NUMBER, ""));
wSAPClient.setText( connection.getAttributes().getProperty(SAPR3DatabaseMeta.ATTRIBUTE_SAP_CLIENT, ""));
wURL.setText( connection.getAttributes().getProperty(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL, ""));
wDriverClass.setText( connection.getAttributes().getProperty(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS, ""));
wConn.setFocus();
wConn.selectAll();
}
public void enableFields()
{
// See if we need to refresh the access list...
String type = DatabaseMeta.getDBTypeDesc(wConnType.getSelectionIndex()+1);
if (!type.equalsIgnoreCase(previousDatabaseType)) setAccessList();
previousDatabaseType=type;
// If the type is not Informix: disable the servername field!
int idxDBType = wConnType.getSelectionIndex();
if (idxDBType>=0)
{
int dbtype = DatabaseMeta.getDatabaseType( wConnType.getItem(idxDBType) );
int idxAccType = wConnAcc.getSelectionIndex();
int acctype = -1;
if (idxAccType>=0)
{
acctype = DatabaseMeta.getAccessType( wConnAcc.getItem(idxAccType) );
}
wlServername.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_INFORMIX );
wServername.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_INFORMIX );
wlData.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_ORACLE );
wData.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_ORACLE );
wlIndex.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_ORACLE );
wIndex.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_ORACLE );
wlSAPLanguage.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_SAPR3 );
wSAPLanguage.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_SAPR3 );
wlSAPSystemNumber.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_SAPR3 );
wSAPSystemNumber.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_SAPR3 );
wlSAPClient.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_SAPR3 );
wSAPClient.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_SAPR3 );
wlDBName.setEnabled( dbtype!=DatabaseMeta.TYPE_DATABASE_SAPR3 );
wDBName.setEnabled( dbtype!=DatabaseMeta.TYPE_DATABASE_SAPR3 );
wlPort.setEnabled( dbtype!=DatabaseMeta.TYPE_DATABASE_SAPR3 );
wPort.setEnabled( dbtype!=DatabaseMeta.TYPE_DATABASE_SAPR3 );
wTest.setEnabled( dbtype!=DatabaseMeta.TYPE_DATABASE_SAPR3 );
wExp.setEnabled( dbtype!=DatabaseMeta.TYPE_DATABASE_SAPR3 );
wlHostName.setEnabled( !(dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wHostName.setEnabled( !(dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wlDBName.setEnabled( !(dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wDBName.setEnabled( !(dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wlPort.setEnabled( !(dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wPort.setEnabled( !(dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wlURL.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
wURL.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
wlDriverClass.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
wDriverClass.setEnabled( dbtype==DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
}
}
public void setPortNumber()
{
String type = DatabaseMeta.getDBTypeDesc(wConnType.getSelectionIndex()+1);
// What port should we select?
String acce = wConnAcc.getItem(wConnAcc.getSelectionIndex());
int port=DatabaseMeta.getPortForDBType(type, acce);
if (port<0) wPort.setText("");
else wPort.setText(""+port);
}
public void setAccessList()
{
if (wConnType.getSelectionCount()<1) return;
int acc[] = DatabaseMeta.getAccessTypeList(wConnType.getSelection()[0]);
wConnAcc.removeAll();
for (int i=0;i<acc.length;i++)
{
wConnAcc.add( DatabaseMeta.getAccessTypeDescLong(acc[i]) );
}
// If nothing is selected: select the first item (mostly the native driver)
if (wConnAcc.getSelectionIndex()<0)
{
wConnAcc.select(0);
}
}
private void cancel()
{
connectionName=null;
connection.setChanged(changed);
dispose();
}
public void getInfo(DatabaseMeta info)
throws KettleException
{
// Name:
info.setName(wConn.getText());
// Connection type:
String contype[] = wConnType.getSelection();
if (contype.length>0)
{
info.setDatabaseType( contype[0] );
}
// Access type:
String acctype[] = wConnAcc.getSelection();
if (acctype.length>0)
{
info.setAccessType( DatabaseMeta.getAccessType(acctype[0]) );
}
// Hostname
info.setHostname( wHostName.getText() );
// Database name
info.setDBName( wDBName.getText() );
// Port number
info.setDBPort( wPort.getText() );
// Username
info.setUsername( wUsername.getText() );
// Password
info.setPassword( wPassword.getText() );
// Servername
info.setServername( wServername.getText() );
// Data tablespace
info.setDataTablespace( wData.getText() );
// Index tablespace
info.setIndexTablespace( wIndex.getText() );
// SAP Attributes...
info.getAttributes().put(SAPR3DatabaseMeta.ATTRIBUTE_SAP_LANGUAGE, wSAPLanguage.getText());
info.getAttributes().put(SAPR3DatabaseMeta.ATTRIBUTE_SAP_SYSTEM_NUMBER, wSAPSystemNumber.getText());
info.getAttributes().put(SAPR3DatabaseMeta.ATTRIBUTE_SAP_CLIENT, wSAPClient.getText());
// Generic settings...
info.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL, wURL.getText());
info.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS, wDriverClass.getText());
String[] remarks = info.checkParameters();
if (remarks.length!=0)
{
String message = "";
for (int i=0;i<remarks.length;i++) message+=" * "+remarks[i]+Const.CR;
throw new KettleException("Incorrect database parameter(s)! Check these settings :"+Const.CR+message);
}
}
public void handleOK()
{
try
{
getInfo(connection);
connectionName = connection.getName();
dispose();
}
catch(KettleException e)
{
new ErrorDialog(shell, props, "Error!", "Please make sure all required parameters are entered correctly!", e);
}
}
public String NVL(String str, String rep)
{
if (str==null) return rep;
return str;
}
public void test()
{
try
{
System.out.println("Creating new database info object");
DatabaseMeta dbinfo=new DatabaseMeta();
System.out.println("Getting info");
getInfo(dbinfo);
test(shell, dbinfo, props);
}
catch(KettleException e)
{
new ErrorDialog(shell, props, "Error", "Unable to get the connection information", e);
}
}
/**
* Test the database connection
*/
public static final void test(Shell shell, DatabaseMeta dbinfo, Props props)
{
System.out.println("Checking parameters");
String[] remarks = dbinfo.checkParameters();
if (remarks.length==0)
{
System.out.println("Creating database connection");
Database db = new Database(dbinfo);
try
{
System.out.println("Connecting to database");
db.connect();
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setText("Connected!");
mb.setMessage("OK!" + Const.CR);
mb.open();
}
catch (KettleException e)
{
// e.printStackTrace();
new ErrorDialog(shell, props, "Error!", "An error occurred connecting to the database: ", e);
}
finally
{
db.disconnect();
}
}
else
{
String message = "";
for (int i=0;i<remarks.length;i++) message+=" * "+remarks[i]+Const.CR;
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setText("Error!");
mb.setMessage("Please make sure all required parameters are entered correctly: " + Const.CR+remarks);
mb.open();
}
}
public void explore()
{
DatabaseMeta dbinfo = new DatabaseMeta();
try
{
getInfo(dbinfo);
DatabaseExplorerDialog ded = new DatabaseExplorerDialog(shell, props, SWT.NONE, dbinfo, databases, true );
ded.open();
}
catch(KettleException e)
{
new ErrorDialog(shell, props, "Error!", "Please make sure all required parameters are entered correctly!", e);
}
}
public void showFeatureList()
{
DatabaseMeta dbinfo = new DatabaseMeta();
try
{
getInfo(dbinfo);
ArrayList buffer = (ArrayList) dbinfo.getFeatureSummary();
PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, "Feature list", buffer);
prd.setTitleMessage("Feature list", "The list of features:");
prd.open();
}
catch(KettleException e)
{
new ErrorDialog(shell, props, "Error!", "Unable to get feature list. Please make sure all required parameters are entered correctly!", e);
}
}
}
|
package com.android.email.activity;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import android.app.ExpandableListActivity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.util.Config;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import com.android.email.Account;
import com.android.email.Email;
import com.android.email.MessagingController;
import com.android.email.MessagingListener;
import com.android.email.R;
import com.android.email.Utility;
import com.android.email.Preferences;
import com.android.email.activity.FolderMessageList.FolderMessageListAdapter.FolderInfoHolder;
import com.android.email.activity.FolderMessageList.FolderMessageListAdapter.MessageInfoHolder;
import com.android.email.activity.setup.AccountSettings;
import com.android.email.mail.Address;
import com.android.email.mail.Flag;
import com.android.email.mail.Folder;
import com.android.email.mail.Message;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Message.RecipientType;
import com.android.email.mail.store.LocalStore.LocalMessage;
import com.android.email.mail.store.LocalStore;
/**
* FolderMessageList is the primary user interface for the program. This Activity shows
* a two level list of the Account's folders and each folder's messages. From this
* Activity the user can perform all standard message operations.
*
*
* TODO some things that are slowing us down:
* Need a way to remove state such as progress bar and per folder progress on
* resume if the command has completed.
*
* TODO
* Break out seperate functions for:
* refresh local folders
* refresh remote folders
* refresh open folder local messages
* refresh open folder remote messages
*
* And don't refresh remote folders ever unless the user runs a refresh. Maybe not even then.
*/
public class FolderMessageList extends ExpandableListActivity {
private static final String EXTRA_ACCOUNT = "account";
private static final String EXTRA_CLEAR_NOTIFICATION = "clearNotification";
private static final String EXTRA_INITIAL_FOLDER = "initialFolder";
private static final String STATE_KEY_LIST =
"com.android.email.activity.folderlist_expandableListState";
private static final String STATE_KEY_EXPANDED_GROUP =
"com.android.email.activity.folderlist_expandedGroup";
private static final String STATE_KEY_EXPANDED_GROUP_SELECTION =
"com.android.email.activity.folderlist_expandedGroupSelection";
private static final int UPDATE_FOLDER_ON_EXPAND_INTERVAL_MS = (1000 * 60 * 3);
private static final int[] colorChipResIds = new int[] {
R.drawable.appointment_indicator_leftside_1,
R.drawable.appointment_indicator_leftside_2,
R.drawable.appointment_indicator_leftside_3,
R.drawable.appointment_indicator_leftside_4,
R.drawable.appointment_indicator_leftside_5,
R.drawable.appointment_indicator_leftside_6,
R.drawable.appointment_indicator_leftside_7,
R.drawable.appointment_indicator_leftside_8,
R.drawable.appointment_indicator_leftside_9,
R.drawable.appointment_indicator_leftside_10,
R.drawable.appointment_indicator_leftside_11,
R.drawable.appointment_indicator_leftside_12,
R.drawable.appointment_indicator_leftside_13,
R.drawable.appointment_indicator_leftside_14,
R.drawable.appointment_indicator_leftside_15,
R.drawable.appointment_indicator_leftside_16,
R.drawable.appointment_indicator_leftside_17,
R.drawable.appointment_indicator_leftside_18,
R.drawable.appointment_indicator_leftside_19,
R.drawable.appointment_indicator_leftside_20,
R.drawable.appointment_indicator_leftside_21,
};
private ExpandableListView mListView;
private int colorChipResId;
private FolderMessageListAdapter mAdapter;
private LayoutInflater mInflater;
private Account mAccount;
/**
* Stores the name of the folder that we want to open as soon as possible after load. It is
* set to null once the folder has been opened once.
*/
private String mInitialFolder;
private DateFormat mDateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
private DateFormat mTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
private int mExpandedGroup = -1;
private boolean mRestoringState;
private boolean mRefreshRemote;
private FolderMessageListHandler mHandler = new FolderMessageListHandler();
class FolderMessageListHandler extends Handler {
private static final int MSG_PROGRESS = 2;
private static final int MSG_DATA_CHANGED = 3;
private static final int MSG_EXPAND_GROUP = 5;
private static final int MSG_FOLDER_LOADING = 7;
private static final int MSG_REMOVE_MESSAGE = 11;
private static final int MSG_SYNC_MESSAGES = 13;
private static final int MSG_FOLDER_STATUS = 17;
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_PROGRESS:
setProgressBarIndeterminateVisibility(msg.arg1 != 0);
break;
case MSG_DATA_CHANGED:
mAdapter.notifyDataSetChanged();
break;
case MSG_EXPAND_GROUP:
mListView.expandGroup(msg.arg1);
break;
/*
* The following functions modify the state of the adapter's underlying list and
* must be run here, in the main thread, so that notifyDataSetChanged is run
* before any further requests are made to the adapter.
*/
case MSG_FOLDER_LOADING: {
FolderInfoHolder folder = mAdapter.getFolder((String) msg.obj);
if (folder != null) {
folder.loading = msg.arg1 != 0;
mAdapter.notifyDataSetChanged();
}
break;
}
case MSG_REMOVE_MESSAGE: {
FolderInfoHolder folder = (FolderInfoHolder) ((Object[]) msg.obj)[0];
MessageInfoHolder message = (MessageInfoHolder) ((Object[]) msg.obj)[1];
folder.messages.remove(message);
mAdapter.notifyDataSetChanged();
break;
}
case MSG_SYNC_MESSAGES: {
FolderInfoHolder folder = (FolderInfoHolder) ((Object[]) msg.obj)[0];
Message[] messages = (Message[]) ((Object[]) msg.obj)[1];
folder.messages.clear();
for (Message message : messages) {
mAdapter.addOrUpdateMessage(folder, message, false, false);
}
Collections.sort(folder.messages);
mAdapter.notifyDataSetChanged();
break;
}
case MSG_FOLDER_STATUS: {
String folderName = (String) ((Object[]) msg.obj)[0];
String status = (String) ((Object[]) msg.obj)[1];
FolderInfoHolder folder = mAdapter.getFolder(folderName);
if (folder != null) {
folder.status = status;
mAdapter.notifyDataSetChanged();
}
break;
}
default:
super.handleMessage(msg);
}
}
public void synchronizeMessages(FolderInfoHolder folder, Message[] messages) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_SYNC_MESSAGES;
msg.obj = new Object[] { folder, messages };
sendMessage(msg);
}
public void removeMessage(FolderInfoHolder folder, MessageInfoHolder message) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_REMOVE_MESSAGE;
msg.obj = new Object[] { folder, message };
sendMessage(msg);
}
public void folderLoading(String folder, boolean loading) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_FOLDER_LOADING;
msg.arg1 = loading ? 1 : 0;
msg.obj = folder;
sendMessage(msg);
}
public void progress(boolean progress) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_PROGRESS;
msg.arg1 = progress ? 1 : 0;
sendMessage(msg);
}
public void dataChanged() {
sendEmptyMessage(MSG_DATA_CHANGED);
}
public void expandGroup(int groupPosition) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_EXPAND_GROUP;
msg.arg1 = groupPosition;
sendMessage(msg);
}
public void folderStatus(String folder, String status) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_FOLDER_STATUS;
msg.obj = new String[] { folder, status };
sendMessage(msg);
}
}
/**
* This class is responsible for reloading the list of local messages for a given folder,
* notifying the adapter that the message have been loaded and queueing up a remote
* update of the folder.
*/
class FolderUpdateWorker implements Runnable {
String mFolder;
boolean mSynchronizeRemote;
/**
* Create a worker for the given folder and specifying whether the
* worker should synchronize the remote folder or just the local one.
* @param folder
* @param synchronizeRemote
*/
public FolderUpdateWorker(String folder, boolean synchronizeRemote) {
mFolder = folder;
mSynchronizeRemote = synchronizeRemote;
}
public void run() {
// Lower our priority
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
// Synchronously load the list of local messages
MessagingController.getInstance(getApplication()).listLocalMessages(
mAccount,
mFolder,
mAdapter.mListener);
if (mSynchronizeRemote) {
// Tell the MessagingController to run a remote update of this folder
// at it's leisure
MessagingController.getInstance(getApplication()).synchronizeMailbox(
mAccount,
mFolder,
mAdapter.mListener);
}
}
}
public static void actionHandleAccount(Context context, Account account, String initialFolder) {
Intent intent = new Intent(context, FolderMessageList.class);
intent.putExtra(EXTRA_ACCOUNT, account);
if (initialFolder != null) {
intent.putExtra(EXTRA_INITIAL_FOLDER, initialFolder);
}
context.startActivity(intent);
}
public static void actionHandleAccount(Context context, Account account) {
actionHandleAccount(context, account, null);
}
public static Intent actionHandleAccountIntent(Context context, Account account, String initialFolder) {
Intent intent = new Intent(context, FolderMessageList.class);
intent.putExtra(EXTRA_ACCOUNT, account);
intent.putExtra(EXTRA_CLEAR_NOTIFICATION, true);
if (initialFolder != null) {
intent.putExtra(EXTRA_INITIAL_FOLDER, initialFolder);
}
return intent;
}
public static Intent actionHandleAccountIntent(Context context, Account account) {
return actionHandleAccountIntent(context, account, null);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
mListView = getExpandableListView();
mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
mListView.setLongClickable(true);
registerForContextMenu(mListView);
/*
* We manually save and restore the list's state because our adapter is slow.
*/
mListView.setSaveEnabled(false);
getExpandableListView().setGroupIndicator(
getResources().getDrawable(R.drawable.expander_ic_folder));
mInflater = getLayoutInflater();
Intent intent = getIntent();
mAccount = (Account)intent.getSerializableExtra(EXTRA_ACCOUNT);
// Take the initial folder into account only if we are *not* restoring the activity already
if (savedInstanceState == null) {
mInitialFolder = intent.getStringExtra(EXTRA_INITIAL_FOLDER);
}
/*
* Since the color chip is always the same color for a given account we just cache the id
* of the chip right here.
*/
colorChipResId = colorChipResIds[mAccount.getAccountNumber() % colorChipResIds.length];
mAdapter = new FolderMessageListAdapter();
final Object previousData = getLastNonConfigurationInstance();
if (previousData != null) {
//noinspection unchecked
mAdapter.mFolders = (ArrayList<FolderInfoHolder>) previousData;
}
setListAdapter(mAdapter);
if (savedInstanceState != null) {
mRestoringState = true;
onRestoreListState(savedInstanceState);
mRestoringState = false;
}
setTitle(mAccount.getDescription());
}
private void onRestoreListState(Bundle savedInstanceState) {
final int expandedGroup = savedInstanceState.getInt(STATE_KEY_EXPANDED_GROUP, -1);
if (expandedGroup >= 0 && mAdapter.getGroupCount() > expandedGroup) {
mListView.expandGroup(expandedGroup);
long selectedChild = savedInstanceState.getLong(STATE_KEY_EXPANDED_GROUP_SELECTION, -1);
if (selectedChild != ExpandableListView.PACKED_POSITION_VALUE_NULL) {
mListView.setSelection(mListView.getFlatListPosition(selectedChild));
}
}
mListView.onRestoreInstanceState(savedInstanceState.getParcelable(STATE_KEY_LIST));
}
@Override
public Object onRetainNonConfigurationInstance() {
return mAdapter.mFolders;
}
@Override
public void onPause() {
super.onPause();
MessagingController.getInstance(getApplication()).removeListener(mAdapter.mListener);
}
/**
* On resume we refresh the folder list (in the background) and we refresh the messages
* for any folder that is currently open. This guarantees that things like unread message
* count and read status are updated.
*/
@Override
public void onResume() {
super.onResume();
NotificationManager notifMgr = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(1);
MessagingController.getInstance(getApplication()).addListener(mAdapter.mListener);
mAccount.refresh(Preferences.getPreferences(this));
onRefresh(false);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(STATE_KEY_LIST, mListView.onSaveInstanceState());
outState.putInt(STATE_KEY_EXPANDED_GROUP, mExpandedGroup);
outState.putLong(STATE_KEY_EXPANDED_GROUP_SELECTION, mListView.getSelectedPosition());
}
@Override
public void onGroupCollapse(int groupPosition) {
super.onGroupCollapse(groupPosition);
mExpandedGroup = -1;
}
@Override
public void onGroupExpand(int groupPosition) {
super.onGroupExpand(groupPosition);
if (mExpandedGroup != -1) {
mListView.collapseGroup(mExpandedGroup);
}
mExpandedGroup = groupPosition;
if (!mRestoringState) {
/*
* Scroll the selected item to the top of the screen.
*/
int position = mListView.getFlatListPosition(
ExpandableListView.getPackedPositionForGroup(groupPosition));
mListView.setSelectionFromTop(position, 0);
}
final FolderInfoHolder folder = (FolderInfoHolder) mAdapter.getGroup(groupPosition);
/*
* We'll only do a hard refresh of a particular folder every 3 minutes or if the user
* specifically asks for a refresh.
*/
if (System.currentTimeMillis() - folder.lastChecked
> UPDATE_FOLDER_ON_EXPAND_INTERVAL_MS) {
folder.lastChecked = System.currentTimeMillis();
// TODO: If the previous thread is already running, we should cancel it
new Thread(new FolderUpdateWorker(folder.name, true)).start();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
int group = mListView.getPackedPositionGroup(mListView.getSelectedId());
int item =(mListView.getSelectedItemPosition() -1 );
if (item >= 0) { // Guard against hitting delete on group names
switch (keyCode) {
case KeyEvent.KEYCODE_DEL: {
if (true) {
MessageInfoHolder message = (MessageInfoHolder) mAdapter.getChild(group, item);
onDelete(message);
}
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
FolderInfoHolder folder = (FolderInfoHolder) mAdapter.getGroup(groupPosition);
if (folder.outbox) {
return false;
}
if (childPosition == folder.messages.size() && !folder.loading) {
if (folder.status == null) {
MessagingController.getInstance(getApplication()).loadMoreMessages(
mAccount,
folder.name,
mAdapter.mListener);
return false;
}
else {
MessagingController.getInstance(getApplication()).synchronizeMailbox(
mAccount,
folder.name,
mAdapter.mListener);
return false;
}
}
else if (childPosition >= folder.messages.size()) {
return false;
}
MessageInfoHolder message = (MessageInfoHolder) mAdapter.getChild(groupPosition, childPosition);
onOpenMessage(folder, message);
return true;
}
private void onRefresh(final boolean forceRemote) {
if (forceRemote) {
mRefreshRemote = true;
}
new Thread() {
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
MessagingController.getInstance(getApplication()).listFolders(
mAccount,
forceRemote,
mAdapter.mListener);
if (forceRemote) {
MessagingController.getInstance(getApplication()).sendPendingMessages(
mAccount,
null);
}
}
}.start();
}
private void onOpenMessage(FolderInfoHolder folder, MessageInfoHolder message) {
/*
* We set read=true here for UI performance reasons. The actual value will get picked up
* on the refresh when the Activity is resumed but that may take a second or so and we
* don't want this to show and then go away.
* I've gone back and forth on this, and this gives a better UI experience, so I am
* putting it back in.
*/
if (!message.read) {
message.read = true;
mHandler.dataChanged();
}
if (folder.name.equals(mAccount.getDraftsFolderName())) {
MessageCompose.actionEditDraft(this, mAccount, message.message);
}
else {
ArrayList<String> folderUids = new ArrayList<String>();
for (MessageInfoHolder holder : folder.messages) {
folderUids.add(holder.uid);
}
MessageView.actionView(this, mAccount, folder.name, message.uid, folderUids);
}
}
private void onEditAccount() {
AccountSettings.actionSettings(this, mAccount);
}
private void onAccounts() {
startActivity(new Intent(this, Accounts.class));
finish();
}
private void onCompose() {
MessageCompose.actionCompose(this, mAccount);
}
private void onDelete(MessageInfoHolder holder) {
MessagingController.getInstance(getApplication()).deleteMessage(
mAccount,
holder.message.getFolder().getName(),
holder.message,
null);
mAdapter.removeMessage(holder.message.getFolder().getName(), holder.uid);
Toast.makeText(this, R.string.message_deleted_toast, Toast.LENGTH_SHORT).show();
}
private void onReply(MessageInfoHolder holder) {
MessageCompose.actionReply(this, mAccount, holder.message, false);
}
private void onReplyAll(MessageInfoHolder holder) {
MessageCompose.actionReply(this, mAccount, holder.message, true);
}
private void onForward(MessageInfoHolder holder) {
MessageCompose.actionForward(this, mAccount, holder.message);
}
private void onToggleRead(MessageInfoHolder holder) {
MessagingController.getInstance(getApplication()).markMessageRead(
mAccount,
holder.message.getFolder().getName(),
holder.uid,
!holder.read);
holder.read = !holder.read;
onRefresh(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
onRefresh(true);
return true;
case R.id.accounts:
onAccounts();
return true;
case R.id.compose:
onCompose();
return true;
case R.id.account_settings:
onEditAccount();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.folder_message_list_option, menu);
return true;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
ExpandableListContextMenuInfo info =
(ExpandableListContextMenuInfo) item.getMenuInfo();
int groupPosition =
ExpandableListView.getPackedPositionGroup(info.packedPosition);
int childPosition =
ExpandableListView.getPackedPositionChild(info.packedPosition);
FolderInfoHolder folder = (FolderInfoHolder) mAdapter.getGroup(groupPosition);
if (childPosition < mAdapter.getChildrenCount(groupPosition)) {
MessageInfoHolder holder =
(MessageInfoHolder) mAdapter.getChild(groupPosition, childPosition);
switch (item.getItemId()) {
case R.id.open:
onOpenMessage(folder, holder);
break;
case R.id.delete:
onDelete(holder);
break;
case R.id.reply:
onReply(holder);
break;
case R.id.reply_all:
onReplyAll(holder);
break;
case R.id.forward:
onForward(holder);
break;
case R.id.mark_as_read:
onToggleRead(holder);
break;
}
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo;
if (ExpandableListView.getPackedPositionType(info.packedPosition) ==
ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
long packedPosition = info.packedPosition;
int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
FolderInfoHolder folder = (FolderInfoHolder) mAdapter.getGroup(groupPosition);
if (folder.outbox) {
return;
}
if (childPosition < folder.messages.size()) {
getMenuInflater().inflate(R.menu.folder_message_list_context, menu);
MessageInfoHolder message =
(MessageInfoHolder) mAdapter.getChild(groupPosition, childPosition);
if (message.read) {
menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action);
}
}
}
}
class FolderMessageListAdapter extends BaseExpandableListAdapter {
private ArrayList<FolderInfoHolder> mFolders = new ArrayList<FolderInfoHolder>();
private MessagingListener mListener = new MessagingListener() {
@Override
public void listFoldersStarted(Account account) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(true);
}
@Override
public void listFoldersFailed(Account account, String message) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(false);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "listFoldersFailed " + message);
}
}
@Override
public void listFoldersFinished(Account account) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(false);
if (mInitialFolder != null) {
int groupPosition = getFolderPosition(mInitialFolder);
mInitialFolder = null;
if (groupPosition != -1) {
mHandler.expandGroup(groupPosition);
}
}
}
@Override
public void listFolders(Account account, Folder[] folders) {
if (!account.equals(mAccount)) {
return;
}
for (Folder folder : folders) {
FolderInfoHolder holder = getFolder(folder.getName());
if (holder == null) {
holder = new FolderInfoHolder();
mFolders.add(holder);
}
holder.name = folder.getName();
if (holder.name.equalsIgnoreCase(Email.INBOX)) {
holder.displayName = getString(R.string.special_mailbox_name_inbox);
}
else {
holder.displayName = folder.getName();
}
if (holder.name.equals(mAccount.getOutboxFolderName())) {
holder.outbox = true;
}
if (holder.messages == null) {
holder.messages = new ArrayList<MessageInfoHolder>();
}
try {
folder.open(Folder.OpenMode.READ_WRITE);
holder.unreadMessageCount = folder.getUnreadMessageCount();
folder.close(false);
}
catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Folder.getUnreadMessageCount() failed", me);
}
}
Collections.sort(mFolders);
mHandler.dataChanged();
/*
* We will do this eventually. This restores the state of the list in the
* case of a killed Activity but we have some message sync issues to take care of.
*/
// if (mRestoredState != null) {
// if (Config.LOGV) {
// Log.v(Email.LOG_TAG, "Attempting to restore list state");
// Parcelable listViewState =
// mListView.onRestoreInstanceState(mListViewState);
// mListViewState = null;
/*
* Now we need to refresh any folders that are currently expanded. We do this
* in case the status or amount of messages has changed.
*/
for (int i = 0, count = getGroupCount(); i < count; i++) {
if (mListView.isGroupExpanded(i)) {
final FolderInfoHolder folder = (FolderInfoHolder) mAdapter.getGroup(i);
new Thread(new FolderUpdateWorker(folder.name, mRefreshRemote)).start();
}
}
mRefreshRemote = false;
}
@Override
public void listLocalMessagesStarted(Account account, String folder) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(true);
mHandler.folderLoading(folder, true);
}
@Override
public void listLocalMessagesFailed(Account account, String folder, String message) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(false);
mHandler.folderLoading(folder, false);
}
@Override
public void listLocalMessagesFinished(Account account, String folder) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(false);
mHandler.folderLoading(folder, false);
}
@Override
public void listLocalMessages(Account account, String folder, Message[] messages) {
if (!account.equals(mAccount)) {
return;
}
synchronizeMessages(folder, messages);
}
@Override
public void synchronizeMailboxStarted(
Account account,
String folder) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(true);
mHandler.folderLoading(folder, true);
mHandler.folderStatus(folder, null);
}
@Override
public void synchronizeMailboxFinished(
Account account,
String folder,
int totalMessagesInMailbox,
int numNewMessages) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(false);
mHandler.folderLoading(folder, false);
mHandler.folderStatus(folder, null);
onRefresh(false);
}
@Override
public void synchronizeMailboxFailed(
Account account,
String folder,
String message) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(false);
mHandler.folderLoading(folder, false);
mHandler.folderStatus(folder, getString(R.string.status_network_error));
FolderInfoHolder holder = getFolder(folder);
if (holder != null) {
/*
* Reset the last checked time to 0 so that the next expand will attempt to
* refresh this folder.
*/
holder.lastChecked = 0;
}
}
@Override
public void synchronizeMailboxNewMessage(
Account account,
String folder,
Message message) {
if (!account.equals(mAccount)) {
return;
}
addOrUpdateMessage(folder, message);
}
@Override
public void synchronizeMailboxRemovedMessage(
Account account,
String folder,
Message message) {
if (!account.equals(mAccount)) {
return;
}
removeMessage(folder, message.getUid());
}
@Override
public void emptyTrashCompleted(Account account) {
if (!account.equals(mAccount)) {
return;
}
onRefresh(false);
}
@Override
public void sendPendingMessagesCompleted(Account account) {
if (!account.equals(mAccount)) {
return;
}
onRefresh(false);
}
@Override
public void messageUidChanged(
Account account,
String folder,
String oldUid,
String newUid) {
if (mAccount.equals(account)) {
FolderInfoHolder holder = getFolder(folder);
if (folder != null) {
for (MessageInfoHolder message : holder.messages) {
if (message.uid.equals(oldUid)) {
message.uid = newUid;
message.message.setUid(newUid);
}
}
}
}
}
};
private Drawable mAttachmentIcon;
FolderMessageListAdapter() {
mAttachmentIcon = getResources().getDrawable(R.drawable.ic_mms_attachment_small);
}
public void removeMessage(String folder, String messageUid) {
FolderInfoHolder f = getFolder(folder);
if (f == null) {
return;
}
MessageInfoHolder m = getMessage(f, messageUid);
if (m == null) {
return;
}
mHandler.removeMessage(f, m);
}
public void synchronizeMessages(String folder, Message[] messages) {
FolderInfoHolder f = getFolder(folder);
if (f == null) {
return;
}
mHandler.synchronizeMessages(f, messages);
}
public void addOrUpdateMessage(String folder, Message message) {
addOrUpdateMessage(folder, message, true, true);
}
private void addOrUpdateMessage(FolderInfoHolder folder, Message message,
boolean sort, boolean notify) {
MessageInfoHolder m = getMessage(folder, message.getUid());
if (m == null) {
m = new MessageInfoHolder(message, folder);
folder.messages.add(m);
}
else {
m.populate(message, folder);
}
if (sort) {
Collections.sort(folder.messages);
}
if (notify) {
mHandler.dataChanged();
}
}
private void addOrUpdateMessage(String folder, Message message,
boolean sort, boolean notify) {
FolderInfoHolder f = getFolder(folder);
if (f == null) {
return;
}
addOrUpdateMessage(f, message, sort, notify);
}
public MessageInfoHolder getMessage(FolderInfoHolder folder, String messageUid) {
for (MessageInfoHolder message : folder.messages) {
if (message.uid.equals(messageUid)) {
return message;
}
}
return null;
}
public int getGroupCount() {
return mFolders.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public Object getGroup(int groupPosition) {
return mFolders.get(groupPosition);
}
public FolderInfoHolder getFolder(String folder) {
FolderInfoHolder folderHolder = null;
for (int i = 0, count = getGroupCount(); i < count; i++) {
FolderInfoHolder holder = (FolderInfoHolder) getGroup(i);
if (holder.name.equals(folder)) {
folderHolder = holder;
}
}
return folderHolder;
}
/**
* Gets the group position of the given folder or returns -1 if the folder is not
* found.
* @param folder
* @return
*/
public int getFolderPosition(String folder) {
for (int i = 0, count = getGroupCount(); i < count; i++) {
FolderInfoHolder holder = (FolderInfoHolder) getGroup(i);
if (holder.name.equals(folder)) {
return i;
}
}
return -1;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
FolderInfoHolder folder = (FolderInfoHolder) getGroup(groupPosition);
View view;
if (convertView != null) {
view = convertView;
} else {
view = mInflater.inflate(R.layout.folder_message_list_group, parent, false);
}
FolderViewHolder holder = (FolderViewHolder) view.getTag();
if (holder == null) {
holder = new FolderViewHolder();
holder.folderName = (TextView) view.findViewById(R.id.folder_name);
holder.newMessageCount = (TextView) view.findViewById(R.id.new_message_count);
holder.folderStatus = (TextView) view.findViewById(R.id.folder_status);
view.setTag(holder);
}
holder.folderName.setText(folder.displayName);
if (folder.status == null) {
holder.folderStatus.setVisibility(View.GONE);
}
else {
holder.folderStatus.setText(folder.status);
holder.folderStatus.setVisibility(View.VISIBLE);
}
if (folder.unreadMessageCount != 0) {
holder.newMessageCount.setText(Integer.toString(folder.unreadMessageCount));
holder.newMessageCount.setVisibility(View.VISIBLE);
}
else {
holder.newMessageCount.setVisibility(View.GONE);
}
return view;
}
public int getChildrenCount(int groupPosition) {
FolderInfoHolder folder = (FolderInfoHolder) getGroup(groupPosition);
return folder.messages.size() + 1;
}
public long getChildId(int groupPosition, int childPosition) {
FolderInfoHolder folder = (FolderInfoHolder) getGroup(groupPosition);
if (childPosition < folder.messages.size()) {
MessageInfoHolder holder = folder.messages.get(childPosition);
return ((LocalStore.LocalMessage) holder.message).getId();
} else {
return -1;
}
}
public Object getChild(int groupPosition, int childPosition) {
FolderInfoHolder folder = (FolderInfoHolder) getGroup(groupPosition);
return folder.messages.get(childPosition);
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
FolderInfoHolder folder = (FolderInfoHolder) getGroup(groupPosition);
if (isLastChild) {
View view;
if ((convertView != null)
&& (convertView.getId()
== R.layout.folder_message_list_child_footer)) {
view = convertView;
}
else {
view = mInflater.inflate(R.layout.folder_message_list_child_footer,
parent, false);
view.setId(R.layout.folder_message_list_child_footer);
}
FooterViewHolder holder = (FooterViewHolder) view.getTag();
if (holder == null) {
holder = new FooterViewHolder();
holder.progress = (ProgressBar) view.findViewById(R.id.progress);
holder.main = (TextView) view.findViewById(R.id.main_text);
view.setTag(holder);
}
if (folder.loading) {
holder.main.setText(getString(R.string.status_loading_more));
holder.progress.setVisibility(View.VISIBLE);
}
else {
if (folder.status == null) {
holder.main.setText(getString(R.string.message_list_load_more_messages_action));
}
else {
holder.main.setText(getString(R.string.status_loading_more_failed));
}
holder.progress.setVisibility(View.GONE);
}
return view;
}
else {
MessageInfoHolder message =
(MessageInfoHolder) getChild(groupPosition, childPosition);
View view;
if ((convertView != null)
&& (convertView.getId() != R.layout.folder_message_list_child_footer)) {
view = convertView;
} else {
view = mInflater.inflate(R.layout.folder_message_list_child, parent, false);
}
MessageViewHolder holder = (MessageViewHolder) view.getTag();
if (holder == null) {
holder = new MessageViewHolder();
holder.subject = (TextView) view.findViewById(R.id.subject);
holder.from = (TextView) view.findViewById(R.id.from);
holder.date = (TextView) view.findViewById(R.id.date);
holder.chip = view.findViewById(R.id.chip);
/*
* TODO
* The line below and the commented lines a bit further down are work
* in progress for outbox status. They should not be removed.
*/
// holder.status = (TextView) view.findViewById(R.id.status);
/*
* This will need to move to below if we ever convert this whole thing
* to a combined inbox.
*/
holder.chip.setBackgroundResource(colorChipResId);
view.setTag(holder);
}
holder.chip.getBackground().setAlpha(message.read ? 0 : 255);
holder.subject.setText(message.subject);
holder.subject.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD);
holder.from.setText(message.sender);
holder.from.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD);
holder.date.setText(message.date);
holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null,
message.hasAttachments ? mAttachmentIcon : null, null);
// if (folder.outbox) {
// holder.status.setText("Sending");
// else {
// holder.status.setText("");
return view;
}
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return childPosition < getChildrenCount(groupPosition);
}
public class FolderInfoHolder implements Comparable<FolderInfoHolder> {
public String name;
public String displayName;
public ArrayList<MessageInfoHolder> messages;
public long lastChecked;
public int unreadMessageCount;
public boolean loading;
public String status;
public boolean lastCheckFailed;
/**
* Outbox is handled differently from any other folder.
*/
public boolean outbox;
public int compareTo(FolderInfoHolder o) {
String s1 = this.name;
String s2 = o.name;
if (Email.INBOX.equalsIgnoreCase(s1)) {
return -1;
} else if (Email.INBOX.equalsIgnoreCase(s2)) {
return 1;
} else
return s1.toUpperCase().compareTo(s2.toUpperCase());
}
}
public class MessageInfoHolder implements Comparable<MessageInfoHolder> {
public String subject;
public String date;
public Date compareDate;
public String sender;
public boolean hasAttachments;
public String uid;
public boolean read;
public Message message;
public MessageInfoHolder(Message m, FolderInfoHolder folder) {
populate(m, folder);
}
public void populate(Message m, FolderInfoHolder folder) {
try {
LocalMessage message = (LocalMessage) m;
Date date = message.getSentDate();
this.compareDate = date;
if (Utility.isDateToday(date)) {
this.date = mTimeFormat.format(date);
}
else {
this.date = mDateFormat.format(date);
}
this.hasAttachments = message.getAttachmentCount() > 0;
this.read = message.isSet(Flag.SEEN);
if (folder.outbox) {
this.sender = Address.toFriendly(
message.getRecipients(RecipientType.TO));
}
else {
this.sender = Address.toFriendly(message.getFrom());
}
this.subject = message.getSubject();
this.uid = message.getUid();
this.message = m;
}
catch (MessagingException me) {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "Unable to load message info", me);
}
}
}
public int compareTo(MessageInfoHolder o) {
return this.compareDate.compareTo(o.compareDate) * -1;
}
}
class FolderViewHolder {
public TextView folderName;
public TextView folderStatus;
public TextView newMessageCount;
}
class MessageViewHolder {
public TextView subject;
public TextView preview;
public TextView from;
public TextView date;
public View chip;
}
class FooterViewHolder {
public ProgressBar progress;
public TextView main;
}
}
}
|
package cellsociety_team05;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import toolsForGui.GuiBoxContainer;
import toolsForGui.GuiChoiceDialog;
import toolsForGui.TopMenu;
public class GUI {
/**
* @author Emanuele Macchi
*/
private Stage myStage;
private BorderPane root;
private final String[] simulationTypes = {"Segregation", "GameOfLife", "PredatorPrey", "Fire"};
private Simulation mySimulation;
private long simulationSpeed;
private GridPane myGridPane;
private GuiBoxContainer myBoxContainer;
private ResourceBundle myResources;
private String currentSimulationName;
public GUI(Stage primaryStage){
GuiChoiceDialog myGuiChoiceDialog = new GuiChoiceDialog(this, simulationTypes);
myResources = ResourceBundle.getBundle("resources.window");
myStage = primaryStage;
myStage.setTitle(myResources.getString("Title"));
myStage.setResizable(false);
root = new BorderPane();
Scene scene = new Scene(root, 720, 480, Color.WHITE);
TopMenu myTopMenu = new TopMenu(myStage, simulationTypes, this);
root.setTop(myTopMenu.getMenuBar());
//different layout
HBox h = new HBox();
int height = 440;
int length = 440;
myGridPane = new GridPane();
myGridPane.setMaxSize(440, 440);
initializeEmptyGridPane(height, length);
h.getChildren().add(myGridPane);
myBoxContainer = new GuiBoxContainer(this, myStage);
h.getChildren().add(myBoxContainer.getVBox());
root.setCenter(h);
myGuiChoiceDialog.display();
myStage.setScene(scene);
myStage.show();
/** Alternative design - Second choice for now
* myBoxContainer = new GuiBoxContainer(this, myStage);
* root.setBottom(myBoxContainer.getVBox());
* myGridPane = new GridPane();
* root.setCenter(myGridPane);
*/
}
public void loadSimulationValue(String letter){
myGridPane.getChildren().clear();
System.out.println(letter + "Sim type");
currentSimulationName = letter;
Setup setup = new Setup(letter,this,myGridPane);
System.out.println("Start");
mySimulation = setup.getSimulation();
}
/**
* The following two methods have been modified to show how the triangle display.
*/
public void startSimulation(){
mySimulation.start();
/**
* If you want to test the triangle grid, choose one of the following
* (Only one at the time)
*/
//testUpdateTriangle();
//testRowTriangle();
}
public void step(){
mySimulation.step();
}
/**
* updates state of graph (called in simulation)
*/
public void updateGraph(){
myBoxContainer.getPCB().AddToQueue(mySimulation.getStats());
myBoxContainer.getPCB().addDataToSeries();
}
/**
* End of modifications
*/
public void restartSimulation(){
loadSimulationValue(currentSimulationName);
startSimulation();
}
public void updateSimulationSpeed(double speed){
System.out.println(speed);
mySimulation.updateSpeed(speed);
}
public void nextStep() {
mySimulation.step();
}
public Simulation getCurrentSimulation(){
return mySimulation;
}
public void changeSimulationFlow(){
mySimulation.changeFlow();
}
public long getSimulationSpeed() {
return simulationSpeed;
}
public void startNewSimulation(String simulation){
loadSimulationValue(simulation);
startSimulation();
}
/**
* The following methods show the functionality of two
* different triangle grids
*/
private void initializeEmptyGridPane(int height, int length){
Rectangle size = new Rectangle(height, length);
myGridPane.getChildren().add(size);
}
private void testRowTriangle(){
myGridPane.getChildren().clear();
for(int i=0; i<8; i++){
TriangleRow t = new TriangleRow(i, myGridPane, 8, 440);
}
}
}
|
package com.bitsofproof.supernode.model;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.bitsofproof.supernode.core.Discovery;
import com.mysema.query.jpa.impl.JPAQuery;
@Component ("jpaPeerStore")
public class JpaPeerStore implements Discovery, PeerStore
{
private static final Logger log = LoggerFactory.getLogger (JpaPeerStore.class);
@PersistenceContext
private EntityManager entityManager;
@Autowired
private PlatformTransactionManager transactionManager;
@Override
public List<KnownPeer> getConnectablePeers ()
{
QKnownPeer kp = QKnownPeer.knownPeer;
JPAQuery q = new JPAQuery (entityManager);
List<KnownPeer> pl =
q.from (kp).where (kp.banned.lt (System.currentTimeMillis () / 1000)).orderBy (kp.preference.desc ()).orderBy (kp.height.desc ())
.orderBy (kp.responseTime.desc ()).orderBy (kp.connected.desc ()).list (kp);
log.trace ("Retrieved " + pl.size () + " peers from store");
return pl;
}
@Override
@Transactional (propagation = Propagation.REQUIRED)
public synchronized void store (KnownPeer peer)
{
try
{
entityManager.merge (peer);
log.trace ("Stored peer " + peer.getAddress ());
}
catch ( ConstraintViolationException e )
{
}
}
@Override
@Transactional (propagation = Propagation.REQUIRED)
public KnownPeer findPeer (InetAddress address)
{
QKnownPeer kp = QKnownPeer.knownPeer;
JPAQuery q = new JPAQuery (entityManager);
KnownPeer peer = q.from (kp).where (kp.address.eq (address.getHostAddress ())).uniqueResult (kp);
if ( peer != null )
{
log.trace ("Retrieved peer " + peer.getAddress ());
}
return peer;
}
@Override
@Transactional (propagation = Propagation.REQUIRED)
public List<InetAddress> discover ()
{
log.trace ("Discovering stored peers");
List<InetAddress> peers = new ArrayList<InetAddress> ();
for ( KnownPeer kp : getConnectablePeers () )
{
try
{
peers.add (InetAddress.getByName (kp.getAddress ()));
}
catch ( UnknownHostException e )
{
}
}
return peers;
}
}
|
package com.bryanjswift.simplenote.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import com.bryanjswift.simplenote.Constants;
import com.bryanjswift.simplenote.R;
import com.bryanjswift.simplenote.model.Note;
import com.bryanjswift.simplenote.persistence.SimpleNoteDao;
import com.bryanjswift.simplenote.view.ScrollWrappableEditText;
import com.bryanjswift.simplenote.widget.NotesAdapter;
import java.util.Date;
/**
* Handle the note editing
* @author bryanjswift
*/
public class SimpleNoteEdit extends Activity {
private static final String LOGGING_TAG = Constants.TAG + "SimpleNoteEdit";
// Final variables
private final SimpleNoteDao dao;
// Mutable instance variables
private long mNoteId = 0L;
private String mOriginalBody = "";
private boolean mActivityStateSaved = false;
private boolean mNoteSaved = false;
private boolean mKeyboardOpen = false;
private final View.OnTouchListener trashTouch = new View.OnTouchListener() {
/**
* Handle special events when touching the trash button
* @param view being touched
* @param motionEvent information about touch event
* @return whether or not the event was handled (it wasn't)
*/
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
View titleRow = findViewById(R.id.note_title_row);
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
if (isInsideView(view, motionEvent)) {
Log.d(LOGGING_TAG, "ACTION_UP MotionEvent inside view - letting onClick handle deleting note");
} else {
titleRow.setPressed(false);
}
break;
case MotionEvent.ACTION_OUTSIDE:
case MotionEvent.ACTION_CANCEL:
titleRow.setPressed(false);
break;
case MotionEvent.ACTION_DOWN:
titleRow.setPressed(true);
break;
}
return false;
}
/**
* Check the evt occurred within the bounds of view
* @param view to check motion event coordinates against
* @param evt to test against view bounds
* @return true if (view.getTop() > evt.getY() < view.getBottom()) && (view.getLeft() > evt.getX() < view.getRight())
*/
private boolean isInsideView(View view, MotionEvent evt) {
return evt.getRawY() > view.getTop() && evt.getRawY() < view.getBottom()
&& evt.getRawX() > view.getLeft() && evt.getRawX() < view.getRight();
}
};
private final View.OnClickListener trashClick = new View.OnClickListener() {
/**
* Perform deletion of the note
* @param view being clicked
*/
@Override
public void onClick(View view) {
Log.d(LOGGING_TAG, "OnClick firing for trash icon");
delete();
}
};
private final View.OnTouchListener scrollTouch = new View.OnTouchListener() {
/**
* Try to open the keyboard
* @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
*/
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Log.d(LOGGING_TAG, "touching the ScrollView");
openKeyboard(findViewById(R.id.note_body));
return false;
}
};
/**
* Default constructor to setup final fields
*/
public SimpleNoteEdit() {
this.dao = new SimpleNoteDao(this);
}
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOGGING_TAG, "Running creating new SimpleNoteEdit Activity");
getWindow().setFormat(PixelFormat.RGBA_8888);
setContentView(R.layout.edit_note);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
mNoteId = extras.getLong(BaseColumns._ID);
mOriginalBody = extras.getString(SimpleNoteDao.BODY);
} else {
mNoteId = savedInstanceState.getLong(BaseColumns._ID);
}
final Note dbNote = dao.retrieve(mNoteId);
if (savedInstanceState == null && mOriginalBody == null) {
mOriginalBody = dbNote.getBody();
} else if (savedInstanceState != null && mOriginalBody == null) {
mOriginalBody = savedInstanceState.getString(SimpleNoteDao.BODY);
}
final String title;
final ScrollWrappableEditText noteBody = ((ScrollWrappableEditText) findViewById(R.id.note_body));
final TextView noteTitle = ((TextView) findViewById(R.id.note_title));
if (dbNote != null) {
title = dbNote.getTitle();
noteBody.setText(dbNote.getBody());
} else {
title = getString(R.string.new_note);
}
noteTitle.setText(NotesAdapter.ellipsizeTitle(this, title));
noteBody.setOnChangeListener(new ScrollWrappableEditText.OnChangeListener() {
@Override
public void onChange(View v, String oldText, String newText) {
noteTitle.setText(NotesAdapter.ellipsizeTitle(SimpleNoteEdit.this, Note.extractTitle(newText)));
}
});
final ImageButton trash = (ImageButton) findViewById(R.id.note_delete);
trash.setOnClickListener(trashClick);
trash.setOnTouchListener(trashTouch);
findViewById(R.id.note_body_scroll).setOnTouchListener(scrollTouch);
}
/**
* @see android.app.Activity#onPostResume()
*/
@Override
protected void onPostResume() {
super.onPostResume();
if (mNoteId == Constants.DEFAULT_ID && !hasHardwareKeyboard()) {
openKeyboard(findViewById(R.id.note_body));
}
}
/**
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.d(LOGGING_TAG, "Resuming SimpleNoteEdit");
mActivityStateSaved = false;
}
/**
* Called before on pause, save data here so SimpleEditNote can be relaunched
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(LOGGING_TAG, "Saving instance state");
mActivityStateSaved = true;
// Make sure the note id is set in the saved state
outState.putLong(BaseColumns._ID, mNoteId);
outState.putString(SimpleNoteDao.BODY, mOriginalBody);
outState.putInt(Constants.REQUEST_KEY, Constants.REQUEST_EDIT);
}
/**
* When user leaves this view save the note and set a result
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.d(LOGGING_TAG, "Firing onPause and handling note saving if needed");
// if text is unchanged send a CANCELLED result, otherwise save and send an OK result
if (needsSave() && !mActivityStateSaved) {
saveAndFinish();
} else {
final Intent intent = getIntent();
setResult(RESULT_CANCELED, intent);
}
}
/**
* @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean handled = false;
if (keyCode == KeyEvent.KEYCODE_BACK) {
handled = handleBackPressed();
}
if (!handled) {
handled = super.onKeyDown(keyCode, event);
}
return handled;
}
/**
* The logic to handle the press of the back button
* @return whether or not the event was handled
*/
private boolean handleBackPressed() {
Log.d(LOGGING_TAG, "Back button pressed");
boolean handled = false;
if (needsSave()) {
// save finishes the Activity with an OK result
saveAndFinish();
handled = true;
}
return handled;
}
/**
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_edit, menu);
return true;
}
/**
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
saveAndFinish(); // save returns ok
return true;
case R.id.menu_delete:
delete(); // delete returns ok if there was a note to delete, cancelled otherwise
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Checks if the body of the note has been updated compared to what was in the DB
* when this Activity was created
* @return whether or note the note body has changed
*/
private boolean needsSave() {
final String body = ((EditText) findViewById(R.id.note_body)).getText().toString();
return !(mNoteSaved || mOriginalBody.equals(body));
}
/**
* Saves the note with data from the view
* @return the note as it is now saved in the DB
*/
private Note save() {
final String body = ((EditText) findViewById(R.id.note_body)).getText().toString();
final String now = Constants.serverDateFormat.format(new Date());
final Note dbNote = dao.retrieve(mNoteId);
final Note note;
if (!(dbNote == null || dbNote.getKey().equals(Constants.DEFAULT_KEY))) {
note = dao.save(dbNote.setBody(body).setDateModified(now).setSynced(false));
Log.d(LOGGING_TAG, String.format("Saved the note '%d' with updated values", note.getId()));
} else {
note = dao.save(new Note(body, now));
Log.d(LOGGING_TAG, String.format("Created the note '%d'", note.getId()));
}
mNoteId = note.getId();
mNoteSaved = true;
return note;
}
/**
* Saves the note with data from the view and finishes this Activity with an OK result
*/
private void saveAndFinish() {
final Intent intent = getIntent();
// get the note as it is from the db, set new fields values and save it
final Note note = save();
intent.putExtra(Note.class.getName(), note);
setResult(RESULT_OK, intent);
finish();
}
/**
* Deletes the note if it exists in the db otherwise cancel
*/
private void delete() {
final Note dbNote = dao.retrieve(mNoteId);
final Intent intent = getIntent();
if (dbNote != null) {
Log.d(LOGGING_TAG, "Note exists, marking it as deleted and finishing successfully");
dao.delete(dbNote);
// Have to re-retrieve because deleting doesn't update the note passed to delete
intent.putExtra(Note.class.getName(), dao.retrieve(mNoteId));
setResult(RESULT_OK, intent);
} else {
Log.d(LOGGING_TAG, "Note doesn't exist, cancelling");
setResult(RESULT_CANCELED, intent);
}
mNoteSaved = true;
finish();
}
/**
* Checks for the presence of any hardware keyboard
* @return whether or not a hardware keyboard exists
*/
private boolean hasHardwareKeyboard() {
return getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS;
}
/**
* Request to open or show the soft keyboard
* @param view to show for?
*/
private void openKeyboard(final View view) {
if (!mKeyboardOpen) {
Log.d(LOGGING_TAG, "Trying to open keyboard");
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
mKeyboardOpen = true;
}
}
|
package com.ecyrd.jspwiki.parser;
import java.io.*;
import java.util.*;
import javax.xml.transform.Result;
import org.apache.log4j.Logger;
import org.apache.oro.text.GlobCompiler;
import org.apache.oro.text.regex.*;
import org.jdom.*;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.attachment.Attachment;
import com.ecyrd.jspwiki.attachment.AttachmentManager;
import com.ecyrd.jspwiki.auth.WikiSecurityException;
import com.ecyrd.jspwiki.auth.acl.Acl;
import com.ecyrd.jspwiki.plugin.PluginException;
import com.ecyrd.jspwiki.plugin.PluginManager;
import com.ecyrd.jspwiki.providers.ProviderException;
import com.ecyrd.jspwiki.render.CleanTextRenderer;
/**
* This is a new class which replaces the TranslatorReader at some point.
* It is not yet functional, but it's getting there. The aim is to produce
* a parser class to an internal DOM tree; then cache this tree and only
* evaluate it at output.
*
* @author jalkanen
*
*/
public class JSPWikiMarkupParser
extends MarkupParser
{
private static final int READ = 0;
private static final int EDIT = 1;
private static final int EMPTY = 2; // Empty message
private static final int LOCAL = 3;
private static final int LOCALREF = 4;
private static final int IMAGE = 5;
private static final int EXTERNAL = 6;
private static final int INTERWIKI = 7;
private static final int IMAGELINK = 8;
private static final int IMAGEWIKILINK = 9;
private static final int ATTACHMENT = 10;
// private static final int ATTACHMENTIMAGE = 11;
/** Lists all punctuation characters allowed in WikiMarkup. These
will not be cleaned away. */
private static final String PUNCTUATION_CHARS_ALLOWED = "._";
private static Logger log = Logger.getLogger( JSPWikiMarkupParser.class );
//private boolean m_iscode = false;
private boolean m_isbold = false;
private boolean m_isitalic = false;
private boolean m_istable = false;
private boolean m_isPre = false;
private boolean m_isEscaping = false;
private boolean m_isdefinition = false;
private boolean m_isPreBlock = false;
/** Contains style information, in multiple forms. */
private Stack m_styleStack = new Stack();
// general list handling
private int m_genlistlevel = 0;
private StringBuffer m_genlistBulletBuffer = new StringBuffer(); // stores the # and * pattern
private boolean m_allowPHPWikiStyleLists = true;
private boolean m_isOpenParagraph = false;
/** Keeps image regexp Patterns */
private ArrayList m_inlineImagePatterns;
private PatternMatcher m_inlineMatcher = new Perl5Matcher();
/** Keeps track of any plain text that gets put in the Text nodes */
private StringBuffer m_plainTextBuf = new StringBuffer();
private Element m_currentElement;
/**
* This property defines the inline image pattern. It's current value
* is jspwiki.translatorReader.inlinePattern
*/
public static final String PROP_INLINEIMAGEPTRN = "jspwiki.translatorReader.inlinePattern";
/** If true, consider CamelCase hyperlinks as well. */
public static final String PROP_CAMELCASELINKS = "jspwiki.translatorReader.camelCaseLinks";
/** If true, all hyperlinks are translated as well, regardless whether they
are surrounded by brackets. */
public static final String PROP_PLAINURIS = "jspwiki.translatorReader.plainUris";
/** If true, all outward links (external links) have a small link image appended. */
public static final String PROP_USEOUTLINKIMAGE = "jspwiki.translatorReader.useOutlinkImage";
/** If set to "true", allows using raw HTML within Wiki text. Be warned,
this is a VERY dangerous option to set - never turn this on in a publicly
allowable Wiki, unless you are absolutely certain of what you're doing. */
public static final String PROP_ALLOWHTML = "jspwiki.translatorReader.allowHTML";
/** If set to "true", all external links are tagged with 'rel="nofollow"' */
public static final String PROP_USERELNOFOLLOW = "jspwiki.translatorReader.useRelNofollow";
/** If set to "true", enables plugins during parsing */
public static final String PROP_RUNPLUGINS = "jspwiki.translatorReader.runPlugins";
/** If true, then considers CamelCase links as well. */
private boolean m_camelCaseLinks = false;
/** If true, consider URIs that have no brackets as well. */
// FIXME: Currently reserved, but not used.
private boolean m_plainUris = false;
/** If true, all outward links use a small link image. */
private boolean m_useOutlinkImage = true;
/** If true, allows raw HTML. */
private boolean m_allowHTML = false;
private boolean m_useRelNofollow = false;
private PatternCompiler m_compiler = new Perl5Compiler();
static final String WIKIWORD_REGEX = "(^|[[:^alnum:]]+)([[:upper:]]+[[:lower:]]+[[:upper:]]+[[:alnum:]]*|(http://|https://|mailto:)([A-Za-z0-9_/\\.\\+\\?\\
private PatternMatcher m_camelCaseMatcher = new Perl5Matcher();
private Pattern m_camelCasePattern;
/**
* The default inlining pattern. Currently "*.png"
*/
public static final String DEFAULT_INLINEPATTERN = "*.png";
/**
* This list contains all IANA registered URI protocol
* types as of September 2004 + a few well-known extra types.
*
* JSPWiki recognises all of them as external links.
*
* This array is sorted during class load, so you can just dump
* here whatever you want in whatever order you want.
*/
static final String[] c_externalLinks = {
"http:", "ftp:", "https:", "mailto:",
"news:", "file:", "rtsp:", "mms:", "ldap:",
"gopher:", "nntp:", "telnet:", "wais:",
"prospero:", "z39.50s", "z39.50r", "vemmi:",
"imap:", "nfs:", "acap:", "tip:", "pop:",
"dav:", "opaquelocktoken:", "sip:", "sips:",
"tel:", "fax:", "modem:", "soap.beep:", "soap.beeps",
"xmlrpc.beep", "xmlrpc.beeps", "urn:", "go:",
"h323:", "ipp:", "tftp:", "mupdate:", "pres:",
"im:", "mtqp", "smb:" };
/**
* This Comparator is used to find an external link from c_externalLinks. It
* checks if the link starts with the other arraythingie.
*/
private static Comparator c_startingComparator = new StartingComparator();
static
{
Arrays.sort( c_externalLinks );
}
/**
* Creates a markup parser.
*/
public JSPWikiMarkupParser( WikiContext context, Reader in )
{
super( context, in );
initialize();
}
/**
* @param engine The WikiEngine this reader is attached to. Is
* used to figure out of a page exits.
*/
// FIXME: parsers should be pooled for better performance.
private void initialize()
{
PatternCompiler compiler = new GlobCompiler();
ArrayList compiledpatterns = new ArrayList();
Collection ptrns = getImagePatterns( m_engine );
// Make them into Regexp Patterns. Unknown patterns
// are ignored.
for( Iterator i = ptrns.iterator(); i.hasNext(); )
{
try
{
compiledpatterns.add( compiler.compile( (String)i.next() ) );
}
catch( MalformedPatternException e )
{
log.error("Malformed pattern in properties: ", e );
}
}
m_inlineImagePatterns = compiledpatterns;
try
{
m_camelCasePattern = m_compiler.compile( WIKIWORD_REGEX );
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: Someone put in a faulty pattern.",e);
throw new InternalWikiException("Faulty camelcasepattern in TranslatorReader");
}
// Set the properties.
Properties props = m_engine.getWikiProperties();
String cclinks = (String)m_context.getPage().getAttribute( PROP_CAMELCASELINKS );
if( cclinks != null )
{
m_camelCaseLinks = TextUtil.isPositive( cclinks );
}
else
{
m_camelCaseLinks = TextUtil.getBooleanProperty( props,
PROP_CAMELCASELINKS,
m_camelCaseLinks );
}
m_plainUris = TextUtil.getBooleanProperty( props,
PROP_PLAINURIS,
m_plainUris );
m_useOutlinkImage = TextUtil.getBooleanProperty( props,
PROP_USEOUTLINKIMAGE,
m_useOutlinkImage );
m_allowHTML = TextUtil.getBooleanProperty( props,
PROP_ALLOWHTML,
m_allowHTML );
m_useRelNofollow = TextUtil.getBooleanProperty( props,
PROP_USERELNOFOLLOW,
m_useRelNofollow );
if( m_engine.getUserDatabase() == null || m_engine.getAuthorizationManager() == null )
{
disableAccessRules();
}
m_context.getPage().setHasMetadata();
}
/**
* Figure out which image suffixes should be inlined.
* @return Collection of Strings with patterns.
*/
protected static Collection getImagePatterns( WikiEngine engine )
{
Properties props = engine.getWikiProperties();
ArrayList ptrnlist = new ArrayList();
for( Enumeration e = props.propertyNames(); e.hasMoreElements(); )
{
String name = (String) e.nextElement();
if( name.startsWith( PROP_INLINEIMAGEPTRN ) )
{
String ptrn = props.getProperty( name );
ptrnlist.add( ptrn );
}
}
if( ptrnlist.size() == 0 )
{
ptrnlist.add( DEFAULT_INLINEPATTERN );
}
return ptrnlist;
}
/**
* Returns link name, if it exists; otherwise it returns null.
*/
private String linkExists( String page )
{
try
{
if( page == null || page.length() == 0 ) return null;
return m_engine.getFinalPageName( page );
}
catch( ProviderException e )
{
log.warn("TranslatorReader got a faulty page name!",e);
return page; // FIXME: What would be the correct way to go back?
}
}
/**
* Calls a transmutator chain.
*
* @param list Chain to call
* @param text Text that should be passed to the mutate() method
* of each of the mutators in the chain.
* @return The result of the mutation.
*/
private String callMutatorChain( Collection list, String text )
{
if( list == null || list.size() == 0 )
{
return text;
}
for( Iterator i = list.iterator(); i.hasNext(); )
{
StringTransmutator m = (StringTransmutator) i.next();
text = m.mutate( m_context, text );
}
return text;
}
private void callHeadingListenerChain( Heading param )
{
List list = m_headingListenerChain;
for( Iterator i = list.iterator(); i.hasNext(); )
{
HeadingListener h = (HeadingListener) i.next();
h.headingAdded( m_context, param );
}
}
private Element makeLink( int type, String link, String text, String section )
{
Element el = null;
if( text == null ) text = link;
section = (section != null) ? ("#"+section) : "";
// Make sure we make a link name that can be accepted
// as a valid URL.
String encodedlink = m_engine.encodeName( link );
if( encodedlink.length() == 0 )
{
type = EMPTY;
}
switch(type)
{
case READ:
el = new Element("a").setAttribute("class", "wikipage");
el.setAttribute("href",m_context.getURL(WikiContext.VIEW, link)+section);
el.addContent(text);
break;
case EDIT:
el = new Element("a").setAttribute("class", "editpage");
el.setAttribute("title","Create '"+link+"'");
el.setAttribute("href", m_context.getURL(WikiContext.EDIT,link));
el.addContent(text);
break;
case EMPTY:
el = new Element("u").addContent(text);
break;
// These two are for local references - footnotes and
// references to footnotes.
// We embed the page name (or whatever WikiContext gives us)
// to make sure the links are unique across Wiki.
case LOCALREF:
el = new Element("a").setAttribute("class","footnoteref");
el.setAttribute("href","#ref-"+m_context.getPage().getName()+"-"+link);
el.addContent("["+text+"]");
break;
case LOCAL:
el = new Element("a").setAttribute("class","footnote");
el.setAttribute("name", "ref-"+m_context.getPage().getName()+"-"+link.substring(1));
el.addContent("["+text+"]");
break;
// With the image, external and interwiki types we need to
// make sure nobody can put in Javascript or something else
// annoying into the links themselves. We do this by preventing
// a haxor from stopping the link name short with quotes in
// fillBuffer().
case IMAGE:
el = new Element("img").setAttribute("class","inline");
el.setAttribute("src",link);
el.setAttribute("alt",text);
break;
case IMAGELINK:
el = new Element("img").setAttribute("class","inline");
el.setAttribute("src",link);
el.setAttribute("alt",text);
el = new Element("a").setAttribute("href",text).addContent(el);
break;
case IMAGEWIKILINK:
String pagelink = m_context.getURL(WikiContext.VIEW,text);
el = new Element("img").setAttribute("class","inline");
el.setAttribute("src",link);
el.setAttribute("alt",text);
el = new Element("a").setAttribute("class","wikipage").setAttribute("href",pagelink).addContent(el);
break;
case EXTERNAL:
el = new Element("a").setAttribute("class","external");
if( m_useRelNofollow ) el.setAttribute("rel","nofollow");
el.setAttribute("href",link+section);
el.addContent(text);
break;
case INTERWIKI:
el = new Element("a").setAttribute("class","interwiki");
el.setAttribute("href",link+section);
el.addContent(text);
break;
case ATTACHMENT:
String attlink = m_context.getURL( WikiContext.ATTACH,
link );
String infolink = m_context.getURL( WikiContext.INFO,
link );
String imglink = m_context.getURL( WikiContext.NONE,
"images/attachment_small.png" );
el = new Element("a").setAttribute("class","attachment");
el.setAttribute("href",attlink);
el.addContent(text);
pushElement(el);
popElement(el.getName());
el = new Element("img").setAttribute("src",imglink);
el.setAttribute("border","0");
el.setAttribute("alt","(info)");
el = new Element("a").setAttribute("href",infolink).addContent(el);
break;
default:
break;
}
if( el != null )
{
flushPlainText();
m_currentElement.addContent( el );
}
return el;
}
/**
* Cleans a Wiki name.
* <P>
* [ This is a link ] -> ThisIsALink
*
* @param link Link to be cleared. Null is safe, and causes this to return null.
* @return A cleaned link.
*
* @since 2.0
*/
public static String cleanLink( String link )
{
StringBuffer clean = new StringBuffer();
if( link == null ) return null;
// Compress away all whitespace and capitalize
// all words in between.
StringTokenizer st = new StringTokenizer( link, " -" );
while( st.hasMoreTokens() )
{
StringBuffer component = new StringBuffer(st.nextToken());
component.setCharAt(0, Character.toUpperCase( component.charAt(0) ) );
// We must do this, because otherwise compiling on JDK 1.4 causes
// a downwards incompatibility to JDK 1.3.
clean.append( component.toString() );
}
// Remove non-alphanumeric characters that should not
// be put inside WikiNames. Note that all valid
// Unicode letters are considered okay for WikiNames.
// It is the problem of the WikiPageProvider to take
// care of actually storing that information.
for( int i = 0; i < clean.length(); i++ )
{
char ch = clean.charAt(i);
if( !(Character.isLetterOrDigit(ch) ||
PUNCTUATION_CHARS_ALLOWED.indexOf(ch) != -1 ))
{
clean.deleteCharAt(i);
--i; // We just shortened this buffer.
}
}
return clean.toString();
}
/**
* Figures out if a link is an off-site link. This recognizes
* the most common protocols by checking how it starts.
*/
private boolean isExternalLink( String link )
{
int idx = Arrays.binarySearch( c_externalLinks, link,
c_startingComparator );
// We need to check here once again; otherwise we might
// get a match for something like "h".
if( idx >= 0 && link.startsWith(c_externalLinks[idx]) ) return true;
return false;
}
/**
* Returns true, if the link in question is an access
* rule.
*/
private static boolean isAccessRule( String link )
{
return link.startsWith("{ALLOW") || link.startsWith("{DENY");
}
/**
* Matches the given link to the list of image name patterns
* to determine whether it should be treated as an inline image
* or not.
*/
private boolean isImageLink( String link )
{
if( m_inlineImages )
{
for( Iterator i = m_inlineImagePatterns.iterator(); i.hasNext(); )
{
if( m_inlineMatcher.matches( link, (Pattern) i.next() ) )
return true;
}
}
return false;
}
private static boolean isMetadata( String link )
{
return link.startsWith("{SET");
}
/**
* Returns true, if the argument contains a number, otherwise false.
* In a quick test this is roughly the same speed as Integer.parseInt()
* if the argument is a number, and roughly ten times the speed, if
* the argument is NOT a number.
*/
private boolean isNumber( String s )
{
if( s == null ) return false;
if( s.length() > 1 && s.charAt(0) == '-' )
s = s.substring(1);
for( int i = 0; i < s.length(); i++ )
{
if( !Character.isDigit(s.charAt(i)) )
return false;
}
return true;
}
/**
* This method peeks ahead in the stream until EOL and returns the result.
* It will keep the buffers untouched.
*
* @return The string from the current position to the end of line.
*/
// FIXME: Always returns an empty line, even if the stream is full.
private String peekAheadLine()
throws IOException
{
String s = readUntilEOL().toString();
pushBack( s );
return s;
}
/**
* Writes HTML for error message.
*/
public static Element makeError( String error )
{
return new Element("span").setAttribute("class","error").addContent(error);
}
private void flushPlainText()
{
if( m_plainTextBuf.length() > 0 )
{
// We must first empty the buffer because the side effect of
// calling makeCamelCaseLink() is to call this routine.
String buf = m_plainTextBuf.toString();
m_plainTextBuf = new StringBuffer();
// If there might be HTML in it, disable the output escaping
// process here (yes, this does increase the DOM tree quite a lot,
// if you allow HTML.)
if( m_allowHTML )
{
m_currentElement.addContent( new ProcessingInstruction( Result.PI_DISABLE_OUTPUT_ESCAPING, "" ));
}
if( m_camelCaseLinks && !m_isEscaping )
{
// System.out.println("Buffer="+buf);
while( m_camelCaseMatcher.contains( buf, m_camelCasePattern ) )
{
MatchResult result = m_camelCaseMatcher.getMatch();
String firstPart = buf.substring(0,result.beginOffset(0));
String prefix = result.group(1);
if( prefix == null ) prefix = "";
String camelCase = result.group(2);
String protocol = result.group(3);
String uri = protocol+result.group(4);
buf = buf.substring(result.endOffset(0));
m_currentElement.addContent( firstPart );
// Check if the user does not wish to do URL or WikiWord expansion
if( prefix.endsWith("~") || prefix.indexOf('[') != -1 )
{
if( prefix.endsWith("~") ) prefix = prefix.substring(0,prefix.length()-1);
if( camelCase != null )
{
m_currentElement.addContent( prefix+camelCase );
}
else if( protocol != null )
{
m_currentElement.addContent( prefix+uri );
}
continue;
}
// Fine, then let's check what kind of a link this was
// and emit the proper elements
if( protocol != null )
{
char c = uri.charAt(uri.length()-1);
if( c == '.' || c == ',' )
{
uri = uri.substring(0,uri.length()-1);
buf = c + buf;
}
// System.out.println("URI match "+uri);
m_currentElement.addContent( prefix );
makeDirectURILink( uri );
}
else
{
// System.out.println("Matched: '"+camelCase+"'");
// System.out.println("Split to '"+firstPart+"', and '"+buf+"'");
// System.out.println("prefix="+prefix);
m_currentElement.addContent( prefix );
makeCamelCaseLink( camelCase );
}
}
m_currentElement.addContent( buf );
}
else
{
// No camelcase asked for, just add the elements
m_currentElement.addContent( buf );
}
}
}
private Element pushElement( Element e )
{
flushPlainText();
m_currentElement.addContent( e );
m_currentElement = e;
return e;
}
private Element addElement( Content e )
{
if( e != null )
{
flushPlainText();
m_currentElement.addContent( e );
}
return m_currentElement;
}
private Element popElement( String s )
{
flushPlainText();
Element currEl = m_currentElement;
while( currEl.getParentElement() != null )
{
if( currEl.getName().equals(s) && !currEl.isRootElement() )
{
m_currentElement = currEl.getParentElement();
return m_currentElement;
}
currEl = currEl.getParentElement();
}
return m_currentElement;
}
/**
* Reads the stream until it meets one of the specified
* ending characters, or stream end. The ending character will be left
* in the stream.
*/
private String readUntil( String endChars )
throws IOException
{
StringBuffer sb = new StringBuffer();
int ch = nextToken();
while( ch != -1 )
{
if( ch == '\\' )
{
ch = nextToken();
if( ch == -1 )
{
break;
}
}
else
{
if( endChars.indexOf((char)ch) != -1 )
{
pushBack( ch );
break;
}
}
sb.append( (char) ch );
ch = nextToken();
}
return sb.toString();
}
/**
* Reads the stream while the characters that have been specified are
* in the stream, returning then the result as a String.
*/
private String readWhile( String endChars )
throws IOException
{
StringBuffer sb = new StringBuffer();
int ch = nextToken();
while( ch != -1 )
{
if( endChars.indexOf((char)ch) == -1 )
{
pushBack( ch );
break;
}
sb.append( (char) ch );
ch = nextToken();
}
return sb.toString();
}
private JSPWikiMarkupParser m_cleanTranslator;
/**
* Does a lazy init. Otherwise, we would get into a situation
* where HTMLRenderer would try and boot a TranslatorReader before
* the TranslatorReader it is contained by is up.
*/
private JSPWikiMarkupParser getCleanTranslator()
{
if( m_cleanTranslator == null )
{
WikiContext dummyContext = new WikiContext( m_engine,
m_context.getPage() );
m_cleanTranslator = new JSPWikiMarkupParser( dummyContext, null );
m_cleanTranslator.m_allowHTML = true;
}
return m_cleanTranslator;
}
/**
* Modifies the "hd" parameter to contain proper values. Because
* an "id" tag may only contain [a-zA-Z0-9:_-], we'll replace the
* % after url encoding with '_'.
*/
private String makeHeadingAnchor( String baseName, String title, Heading hd )
{
hd.m_titleText = title;
title = cleanLink( title );
hd.m_titleSection = m_engine.encodeName(title);
hd.m_titleAnchor = "section-"+m_engine.encodeName(baseName)+
"-"+hd.m_titleSection;
hd.m_titleAnchor = hd.m_titleAnchor.replace( '%', '_' );
return hd.m_titleAnchor;
}
private String makeSectionTitle( String title )
{
title = title.trim();
String outTitle;
try
{
JSPWikiMarkupParser dtr = getCleanTranslator();
dtr.setInputReader( new StringReader(title) );
CleanTextRenderer ctt = new CleanTextRenderer(m_context, dtr.parse());
outTitle = ctt.getString();
}
catch( IOException e )
{
log.fatal("CleanTranslator not working", e);
throw new InternalWikiException("CleanTranslator not working as expected, when cleaning title"+ e.getMessage() );
}
return outTitle;
}
/**
* Returns XHTML for the start of the heading. Also sets the
* line-end emitter.
* @param level
* @param headings A List to which heading should be added.
*/
public Element makeHeading( int level, String title, Heading hd )
{
Element el = null;
String pageName = m_context.getPage().getName();
String outTitle = makeSectionTitle( title );
hd.m_level = level;
switch( level )
{
case Heading.HEADING_SMALL:
el = new Element("h4").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ));
break;
case Heading.HEADING_MEDIUM:
el = new Element("h3").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ));
break;
case Heading.HEADING_LARGE:
el = new Element("h2").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ));
break;
}
return el;
}
/**
* Checks for the existence of a traditional style CamelCase link.
* <P>
* We separate all white-space -separated words, and feed it to this
* routine to find if there are any possible camelcase links.
* For example, if "word" is "__HyperLink__" we return "HyperLink".
*
* @param word A phrase to search in.
* @return The match within the phrase. Returns null, if no CamelCase
* hyperlink exists within this phrase.
*/
/*
private String checkForCamelCaseLink( String word )
{
PatternMatcherInput input;
input = new PatternMatcherInput( word );
if( m_matcher.contains( input, m_camelCasePtrn ) )
{
MatchResult res = m_matcher.getMatch();
String link = res.group(2);
if( res.group(1) != null )
{
if( res.group(1).endsWith("~") ||
res.group(1).indexOf('[') != -1 )
{
// Delete the (~) from beginning.
// We'll make '~' the generic kill-processing-character from
// now on.
return null;
}
}
return link;
} // if match
return null;
}
*/
/**
* When given a link to a WikiName, we just return
* a proper HTML link for it. The local link mutator
* chain is also called.
*/
private Element makeCamelCaseLink( String wikiname )
{
String matchedLink;
callMutatorChain( m_localLinkMutatorChain, wikiname );
if( (matchedLink = linkExists( wikiname )) != null )
{
makeLink( READ, matchedLink, wikiname, null );
}
else
{
makeLink( EDIT, wikiname, wikiname, null );
}
return m_currentElement;
}
private Element outlinkImage()
{
Element el = null;
if( m_useOutlinkImage )
{
el = new Element("img").setAttribute("class", "outlink");
el.setAttribute( "src", m_context.getURL( WikiContext.NONE,"images/out.png" ) );
el.setAttribute("alt","");
}
return el;
}
private Element makeDirectURILink( String url )
{
Element result;
String last = null;
if( url.endsWith(",") || url.endsWith(".") )
{
last = url.substring( url.length()-1 );
url = url.substring( 0, url.length()-1 );
}
callMutatorChain( m_externalLinkMutatorChain, url );
if( isImageLink( url ) )
{
result = handleImageLink( url, url, false );
}
else
{
result = makeLink( EXTERNAL, url, url,null );
addElement( outlinkImage() );
}
if( last != null )
m_plainTextBuf.append(last);
return result;
}
/**
* Image links are handled differently:
* 1. If the text is a WikiName of an existing page,
* it gets linked.
* 2. If the text is an external link, then it is inlined.
* 3. Otherwise it becomes an ALT text.
*
* @param reallink The link to the image.
* @param link Link text portion, may be a link to somewhere else.
* @param hasLinkText If true, then the defined link had a link text available.
* This means that the link text may be a link to a wiki page,
* or an external resource.
*/
// FIXME: isExternalLink() is called twice.
private Element handleImageLink( String reallink, String link, boolean hasLinkText )
{
String possiblePage = cleanLink( link );
String matchedLink;
if( isExternalLink( link ) && hasLinkText )
{
return makeLink( IMAGELINK, reallink, link, null );
}
else if( (matchedLink = linkExists( possiblePage )) != null &&
hasLinkText )
{
// System.out.println("Orig="+link+", Matched: "+matchedLink);
callMutatorChain( m_localLinkMutatorChain, possiblePage );
return makeLink( IMAGEWIKILINK, reallink, link, null );
}
else
{
return makeLink( IMAGE, reallink, link, null );
}
}
private Element handleAccessRule( String ruleLine )
{
if( !m_parseAccessRules ) return m_currentElement;
Acl acl;
WikiPage page = m_context.getPage();
// UserDatabase db = m_context.getEngine().getUserDatabase();
if( ruleLine.startsWith( "{" ) )
ruleLine = ruleLine.substring( 1 );
if( ruleLine.endsWith( "}" ) )
ruleLine = ruleLine.substring( 0, ruleLine.length() - 1 );
log.debug("page="+page.getName()+", ACL = "+ruleLine);
try
{
acl = m_engine.getAclManager().parseAcl( page, ruleLine );
page.setAcl( acl );
log.debug( acl.toString() );
}
catch( WikiSecurityException wse )
{
return makeError( wse.getMessage() );
}
return m_currentElement;
}
/**
* Handles metadata setting [{SET foo=bar}]
*/
private Element handleMetadata( String link )
{
try
{
String args = link.substring( link.indexOf(' '), link.length()-1 );
String name = args.substring( 0, args.indexOf('=') );
String val = args.substring( args.indexOf('=')+1, args.length() );
name = name.trim();
val = val.trim();
if( val.startsWith("'") ) val = val.substring( 1 );
if( val.endsWith("'") ) val = val.substring( 0, val.length()-1 );
// log.debug("SET name='"+name+"', value='"+val+"'.");
if( name.length() > 0 && val.length() > 0 )
{
val = m_engine.getVariableManager().expandVariables( m_context,
val );
m_context.getPage().setAttribute( name, val );
}
}
catch( Exception e )
{
return makeError(" Invalid SET found: "+link);
}
return m_currentElement;
}
/**
* Gobbles up all hyperlinks that are encased in square brackets.
*/
private Element handleHyperlinks( String link )
{
StringBuffer sb = new StringBuffer();
String reallink;
int cutpoint;
if( isAccessRule( link ) )
{
return handleAccessRule( link );
}
if( isMetadata( link ) )
{
return handleMetadata( link );
}
if( PluginManager.isPluginLink( link ) )
{
try
{
Content pluginContent = m_engine.getPluginManager().parsePluginLine( m_context, link );
addElement( new ProcessingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, "") );
addElement( pluginContent );
addElement( new ProcessingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, "") );
}
catch( PluginException e )
{
log.info( "Failed to insert plugin", e );
log.info( "Root cause:",e.getRootThrowable() );
return addElement( makeError("Plugin insertion failed: "+e.getMessage()) );
}
return m_currentElement;
}
// link = TextUtil.replaceEntities( link );
if( (cutpoint = link.indexOf('|')) != -1 )
{
reallink = link.substring( cutpoint+1 ).trim();
link = link.substring( 0, cutpoint );
}
else
{
reallink = link.trim();
}
int interwikipoint = -1;
// Yes, we now have the components separated.
// link = the text the link should have
// reallink = the url or page name.
// In many cases these are the same. [link|reallink].
if( VariableManager.isVariableLink( link ) )
{
Content el = new VariableContent(link);
addElement( new ProcessingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, "") );
addElement( el );
addElement( new ProcessingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, "") );
}
else if( isExternalLink( reallink ) )
{
// It's an external link, out of this Wiki
callMutatorChain( m_externalLinkMutatorChain, reallink );
if( isImageLink( reallink ) )
{
handleImageLink( reallink, link, (cutpoint != -1) );
}
else
{
makeLink( EXTERNAL, reallink, link, null );
addElement( outlinkImage() );
}
}
else if( (interwikipoint = reallink.indexOf(":")) != -1 )
{
// It's an interwiki link
// InterWiki links also get added to external link chain
// after the links have been resolved.
// FIXME: There is an interesting issue here: We probably should
// URLEncode the wikiPage, but we can't since some of the
// Wikis use slashes (/), which won't survive URLEncoding.
// Besides, we don't know which character set the other Wiki
// is using, so you'll have to write the entire name as it appears
// in the URL. Bugger.
String extWiki = reallink.substring( 0, interwikipoint );
String wikiPage = reallink.substring( interwikipoint+1 );
String urlReference = m_engine.getInterWikiURL( extWiki );
if( urlReference != null )
{
urlReference = TextUtil.replaceString( urlReference, "%s", wikiPage );
callMutatorChain( m_externalLinkMutatorChain, urlReference );
makeLink( INTERWIKI, urlReference, link, null );
if( isExternalLink(urlReference) )
{
addElement( outlinkImage() );
}
}
else
{
addElement( makeError("No InterWiki reference defined in properties for Wiki called '"+extWiki+"'!)") );
}
}
else if( reallink.startsWith("
{
// It defines a local footnote
makeLink( LOCAL, reallink, link, null );
}
else if( isNumber( reallink ) )
{
// It defines a reference to a local footnote
makeLink( LOCALREF, reallink, link, null );
}
else
{
int hashMark = -1;
// Internal wiki link, but is it an attachment link?
String attachment = findAttachment( reallink );
if( attachment != null )
{
callMutatorChain( m_attachmentLinkMutatorChain, attachment );
if( isImageLink( reallink ) )
{
attachment = m_context.getURL( WikiContext.ATTACH, attachment );
sb.append( handleImageLink( attachment, link, (cutpoint != -1) ) );
}
else
{
makeLink( ATTACHMENT, attachment, link, null );
}
}
else if( (hashMark = reallink.indexOf('
{
// It's an internal Wiki link, but to a named section
String namedSection = reallink.substring( hashMark+1 );
reallink = reallink.substring( 0, hashMark );
reallink = cleanLink( reallink );
callMutatorChain( m_localLinkMutatorChain, reallink );
String matchedLink;
if( (matchedLink = linkExists( reallink )) != null )
{
String sectref = "section-"+m_engine.encodeName(matchedLink)+"-"+namedSection;
sectref = sectref.replace('%', '_');
makeLink( READ, matchedLink, link, sectref );
}
else
{
makeLink( EDIT, reallink, link, null );
}
}
else
{
// It's an internal Wiki link
reallink = cleanLink( reallink );
callMutatorChain( m_localLinkMutatorChain, reallink );
String matchedLink = linkExists( reallink );
if( matchedLink != null )
{
makeLink( READ, matchedLink, link, null );
}
else
{
makeLink( EDIT, reallink, link, null );
}
}
}
return m_currentElement;
}
private String findAttachment( String link )
{
AttachmentManager mgr = m_engine.getAttachmentManager();
Attachment att = null;
try
{
att = mgr.getAttachmentInfo( m_context, link );
}
catch( ProviderException e )
{
log.warn("Finding attachments failed: ",e);
return null;
}
if( att != null )
{
return att.getName();
}
else if( link.indexOf('/') != -1 )
{
return link;
}
return null;
}
private int nextToken()
throws IOException
{
if( m_in == null ) return -1;
return m_in.read();
}
/**
* Push back any character to the current input. Does not
* push back a read EOF, though.
*/
private void pushBack( int c )
throws IOException
{
if( c != -1 && m_in != null )
{
m_in.unread( c );
}
}
/**
* Pushes back any string that has been read. It will obviously
* be pushed back in a reverse order.
*
* @since 2.1.77
*/
private void pushBack( String s )
throws IOException
{
for( int i = s.length()-1; i >= 0; i
{
pushBack( s.charAt(i) );
}
}
private Element handleBackslash()
throws IOException
{
int ch = nextToken();
if( ch == '\\' )
{
int ch2 = nextToken();
if( ch2 == '\\' )
{
pushElement( new Element("br").setAttribute("clear","all"));
return popElement("br");
}
pushBack( ch2 );
pushElement( new Element("br") );
return popElement("br");
}
pushBack( ch );
return null;
}
private Element handleUnderscore()
throws IOException
{
int ch = nextToken();
Element el = null;
if( ch == '_' )
{
if( m_isbold )
{
el = popElement("b");
}
else
{
el = pushElement( new Element("b") );
}
m_isbold = !m_isbold;
}
else
{
pushBack( ch );
}
return el;
}
/**
* For example: italics.
*/
private Element handleApostrophe()
throws IOException
{
int ch = nextToken();
Element el = null;
if( ch == '\'' )
{
if( m_isitalic )
{
el = popElement("i");
}
else
{
el = pushElement( new Element("i") );
}
m_isitalic = !m_isitalic;
}
else
{
pushBack( ch );
}
return el;
}
private Element handleOpenbrace( boolean isBlock )
throws IOException
{
int ch = nextToken();
if( ch == '{' )
{
int ch2 = nextToken();
if( ch2 == '{' )
{
m_isPre = true;
m_isEscaping = true;
m_isPreBlock = isBlock;
if( isBlock )
{
startBlockLevel();
return pushElement( new Element("pre") );
}
else
{
return pushElement( new Element("span").setAttribute("style","font-family:monospace; whitespace:pre;") );
}
}
else
{
pushBack( ch2 );
return pushElement( new Element("tt") );
}
}
else
{
pushBack( ch );
}
return null;
}
/**
* Handles both }} and }}}
*/
private Element handleClosebrace()
throws IOException
{
int ch2 = nextToken();
if( ch2 == '}' )
{
int ch3 = nextToken();
if( ch3 == '}' )
{
if( m_isPre )
{
if( m_isPreBlock )
{
popElement( "pre" );
}
else
{
popElement( "span" );
}
m_isPre = false;
m_isEscaping = false;
return m_currentElement;
}
else
{
m_plainTextBuf.append("}}}");
return m_currentElement;
}
}
else
{
pushBack( ch3 );
if( !m_isEscaping )
{
return popElement("tt");
}
else
{
pushBack( ch2 );
}
}
}
else
{
pushBack( ch2 );
}
return null;
}
private Element handleDash()
throws IOException
{
int ch = nextToken();
if( ch == '-' )
{
int ch2 = nextToken();
if( ch2 == '-' )
{
int ch3 = nextToken();
if( ch3 == '-' )
{
// Empty away all the rest of the dashes.
// Do not forget to return the first non-match back.
while( (ch = nextToken()) == '-' );
pushBack(ch);
startBlockLevel();
pushElement( new Element("hr") );
return popElement( "hr" );
}
pushBack( ch3 );
}
pushBack( ch2 );
}
pushBack( ch );
return null;
}
private Element handleHeading()
throws IOException
{
Element el = null;
int ch = nextToken();
Heading hd = new Heading();
if( ch == '!' )
{
int ch2 = nextToken();
if( ch2 == '!' )
{
String title = peekAheadLine();
el = makeHeading( Heading.HEADING_LARGE, title, hd);
}
else
{
pushBack( ch2 );
String title = peekAheadLine();
el = makeHeading( Heading.HEADING_MEDIUM, title, hd );
}
}
else
{
pushBack( ch );
String title = peekAheadLine();
el = makeHeading( Heading.HEADING_SMALL, title, hd );
}
callHeadingListenerChain( hd );
if( el != null ) pushElement(el);
return el;
}
/**
* Reads the stream until the next EOL or EOF. Note that it will also read the
* EOL from the stream.
*/
private StringBuffer readUntilEOL()
throws IOException
{
int ch;
StringBuffer buf = new StringBuffer();
while( true )
{
ch = nextToken();
if( ch == -1 )
break;
buf.append( (char) ch );
if( ch == '\n' )
break;
}
return buf;
}
/**
* Starts a block level element, therefore closing the
* a potential open paragraph tag.
*/
private void startBlockLevel()
{
popElement("i"); m_isitalic = false;
popElement("b"); m_isbold = false;
popElement("tt");
if( m_isOpenParagraph )
{
m_isOpenParagraph = false;
popElement("p");
m_plainTextBuf.append("\n"); // Just small beautification
}
}
private static String getListType( char c )
{
if( c == '*' )
{
return "ul";
}
else if( c == '
{
return "ol";
}
throw new InternalWikiException("Parser got faulty list type: "+c);
}
/**
* Like original handleOrderedList() and handleUnorderedList()
* however handles both ordered ('#') and unordered ('*') mixed together.
*/
// FIXME: Refactor this; it's a bit messy.
private Element handleGeneralList()
throws IOException
{
startBlockLevel();
String strBullets = readWhile( "*
// String strBulletsRaw = strBullets; // to know what was original before phpwiki style substitution
int numBullets = strBullets.length();
// override the beginning portion of bullet pattern to be like the previous
// to simulate PHPWiki style lists
if(m_allowPHPWikiStyleLists)
{
// only substitute if different
if(!( strBullets.substring(0,Math.min(numBullets,m_genlistlevel)).equals
(m_genlistBulletBuffer.substring(0,Math.min(numBullets,m_genlistlevel)) ) ) )
{
if(numBullets <= m_genlistlevel)
{
// Substitute all but the last character (keep the expressed bullet preference)
strBullets = (numBullets > 1 ? m_genlistBulletBuffer.substring(0, numBullets-1) : "")
+ strBullets.substring(numBullets-1, numBullets);
}
else
{
strBullets = m_genlistBulletBuffer + strBullets.substring(m_genlistlevel, numBullets);
}
}
}
// Check if this is still of the same type
if( strBullets.substring(0,Math.min(numBullets,m_genlistlevel)).equals
(m_genlistBulletBuffer.substring(0,Math.min(numBullets,m_genlistlevel)) ) )
{
if( numBullets > m_genlistlevel )
{
pushElement( new Element( getListType(strBullets.charAt(m_genlistlevel++) ) ) );
// buf.append( m_renderer.openList(strBullets.charAt(m_genlistlevel++)) );
for( ; m_genlistlevel < numBullets; m_genlistlevel++ )
{
// bullets are growing, get from new bullet list
pushElement( new Element("li") );
// buf.append( m_renderer.openListItem() );
pushElement( new Element( getListType(strBullets.charAt(m_genlistlevel)) ));
// buf.append( m_renderer.openList(strBullets.charAt(m_genlistlevel)) );
}
}
else if( numBullets < m_genlistlevel )
{
// Close the previous list item.
// buf.append( m_renderer.closeListItem() );
popElement( "li" );
for( ; m_genlistlevel > numBullets; m_genlistlevel
{
// bullets are shrinking, get from old bullet list
// buf.append( m_renderer.closeList(m_genlistBulletBuffer.charAt(m_genlistlevel - 1)) );
popElement( getListType(m_genlistBulletBuffer.charAt(m_genlistlevel-1)) );
if( m_genlistlevel > 0 )
{
// buf.append( m_renderer.closeListItem() );
popElement( "li" );
}
}
}
else
{
if( m_genlistlevel > 0 )
{
popElement( "li" );
// buf.append( m_renderer.closeListItem() );
}
}
}
else
{
// The pattern has changed, unwind and restart
int numEqualBullets;
int numCheckBullets;
// find out how much is the same
numEqualBullets = 0;
numCheckBullets = Math.min(numBullets,m_genlistlevel);
while( numEqualBullets < numCheckBullets )
{
// if the bullets are equal so far, keep going
if( strBullets.charAt(numEqualBullets) == m_genlistBulletBuffer.charAt(numEqualBullets))
numEqualBullets++;
// otherwise giveup, we have found how many are equal
else
break;
}
//unwind
for( ; m_genlistlevel > numEqualBullets; m_genlistlevel
{
popElement( getListType( m_genlistBulletBuffer.charAt(m_genlistlevel-1) ) );
// buf.append( m_renderer.closeList( m_genlistBulletBuffer.charAt(m_genlistlevel - 1) ) );
if( m_genlistlevel > 0 )
{
//buf.append( m_renderer.closeListItem() );
popElement("li");
}
}
//rewind
// buf.append( m_renderer.openList( strBullets.charAt(numEqualBullets++) ) );
pushElement( new Element(getListType( strBullets.charAt(numEqualBullets++) ) ) );
for(int i = numEqualBullets; i < numBullets; i++)
{
pushElement( new Element("li") );
pushElement( new Element( getListType( strBullets.charAt(i) ) ) );
// buf.append( m_renderer.openListItem() );
// buf.append( m_renderer.openList( strBullets.charAt(i) ) );
}
m_genlistlevel = numBullets;
}
//buf.append( m_renderer.openListItem() );
pushElement( new Element("li") );
// work done, remember the new bullet list (in place of old one)
m_genlistBulletBuffer.setLength(0);
m_genlistBulletBuffer.append(strBullets);
return m_currentElement;
}
private Element unwindGeneralList()
{
//unwind
for( ; m_genlistlevel > 0; m_genlistlevel
{
popElement( "li" );
popElement( getListType(m_genlistBulletBuffer.charAt(m_genlistlevel-1)) );
}
m_genlistBulletBuffer.setLength(0);
return null;
}
private Element handleDefinitionList()
throws IOException
{
if( !m_isdefinition )
{
m_isdefinition = true;
startBlockLevel();
pushElement( new Element("dl") );
return pushElement( new Element("dt") );
}
return null;
}
private Element handleOpenbracket()
throws IOException
{
StringBuffer sb = new StringBuffer();
int ch;
boolean isPlugin = false;
while( (ch = nextToken()) == '[' )
{
sb.append( (char)ch );
}
if( ch == '{' )
{
isPlugin = true;
}
pushBack( ch );
if( sb.length() > 0 )
{
m_plainTextBuf.append( sb );
return m_currentElement;
}
// Find end of hyperlink
ch = nextToken();
while( ch != -1 )
{
if( ch == ']' && (!isPlugin || sb.charAt( sb.length()-1 ) == '}' ) )
{
break;
}
sb.append( (char) ch );
ch = nextToken();
}
// If the link is never finished, do some tricks to display the rest of the line
// unchanged.
if( ch == -1 )
{
log.debug("Warning: unterminated link detected!");
m_isEscaping = true;
m_plainTextBuf.append( sb );
flushPlainText();
m_isEscaping = false;
return m_currentElement;
}
return handleHyperlinks( sb.toString() );
}
/**
* Reads the stream until the current brace is closed or stream end.
*/
private String readBraceContent( char opening, char closing )
throws IOException
{
StringBuffer sb = new StringBuffer();
int braceLevel = 1;
int ch;
while(( ch = nextToken() ) != -1 )
{
if( ch == '\\' )
{
continue;
}
else if ( ch == opening )
{
braceLevel++;
}
else if ( ch == closing )
{
braceLevel
if (braceLevel==0)
{
break;
}
}
sb.append( (char)ch );
}
return sb.toString();
}
/**
* Handles constructs of type %%(style) and %%class
* @param newLine
* @return
* @throws IOException
*/
private Element handleDiv( boolean newLine )
throws IOException
{
int ch = nextToken();
Element el = null;
if( ch == '%' )
{
String style = null;
String clazz = null;
ch = nextToken();
// Style or class?
if( ch == '(' )
{
style = readBraceContent('(',')');
}
else if( Character.isLetter( (char) ch ) )
{
pushBack( ch );
clazz = readUntil( " \t\n\r" );
ch = nextToken();
// Pop out only spaces, so that the upcoming EOL check does not check the
// next line.
if( ch == '\n' || ch == '\r' )
{
pushBack(ch);
}
}
else
{
// Anything else stops.
pushBack(ch);
try
{
Boolean isSpan = (Boolean)m_styleStack.pop();
if( isSpan == null )
{
// Fail quietly
}
else if( isSpan.booleanValue() )
{
el = popElement( "span" );
}
else
{
el = popElement( "div" );
}
}
catch( EmptyStackException e )
{
log.debug("Page '"+m_context.getPage().getName()+"' closes a %%-block that has not been opened.");
}
return el;
}
// Decide if we should open a div or a span?
String eol = peekAheadLine();
if( eol.trim().length() > 0 )
{
// There is stuff after the class
el = new Element("span");
m_styleStack.push( Boolean.TRUE );
}
else
{
startBlockLevel();
el = new Element("div");
m_styleStack.push( Boolean.FALSE );
}
if( style != null ) el.setAttribute("style", style);
if( clazz != null ) el.setAttribute("class", clazz );
el = pushElement( el );
return el;
}
pushBack(ch);
return el;
}
private Element handleBar( boolean newLine )
throws IOException
{
Element el = null;
if( !m_istable && !newLine )
{
return null;
}
if( newLine )
{
if( !m_istable )
{
startBlockLevel();
el = pushElement( new Element("table").setAttribute("class","wikitable").setAttribute("border","1") );
m_istable = true;
}
el = pushElement( new Element("tr") );
// m_closeTag = m_renderer.closeTableItem()+m_renderer.closeTableRow();
}
int ch = nextToken();
if( ch == '|' )
{
if( !newLine )
{
el = popElement("th");
}
el = pushElement( new Element("th") );
}
else
{
if( !newLine )
{
el = popElement("td");
}
el = pushElement( new Element("td") );
pushBack( ch );
}
return el;
}
/**
* Generic escape of next character or entity.
*/
private Element handleTilde()
throws IOException
{
int ch = nextToken();
if( ch == '|' || ch == '~' || ch == '\\' || ch == '*' || ch == '
ch == '-' || ch == '!' || ch == '\'' || ch == '_' || ch == '[' ||
ch == '{' || ch == ']' || ch == '}' || ch == '%' )
{
m_plainTextBuf.append( (char)ch );
m_plainTextBuf.append(readWhile( ""+(char)ch ));
return m_currentElement;
}
// No escape.
pushBack( ch );
return null;
}
private void fillBuffer( Element startElement )
throws IOException
{
m_currentElement = startElement;
boolean quitReading = false;
boolean newLine = true; // FIXME: not true if reading starts in middle of buffer
while(!quitReading)
{
int ch = nextToken();
String s = null;
Element el = null;
// Check if we're actually ending the preformatted mode.
// We still must do an entity transformation here.
if( m_isEscaping )
{
if( ch == '}' )
{
if( handleClosebrace() == null ) m_plainTextBuf.append( (char) ch );
}
else if( ch == -1 )
{
quitReading = true;
}
else if( ch == '\r' )
{
// DOS line feeds we ignore.
}
else
{
m_plainTextBuf.append( (char) ch );
}
continue;
}
// An empty line stops a list
if( newLine && ch != '*' && ch != '#' && ch != ' ' && m_genlistlevel > 0 )
{
m_plainTextBuf.append(unwindGeneralList());
}
if( newLine && ch != '|' && m_istable )
{
el = popElement("table");
m_istable = false;
}
// Now, check the incoming token.
switch( ch )
{
case '\r':
// DOS linefeeds we forget
continue;
case '\n':
// Close things like headings, etc.
// FIXME: This is not really very fast
popElement("dl"); // Close definition lists.
popElement("h2");
popElement("h3");
popElement("h4");
if( m_istable )
{
popElement("tr");
}
m_isdefinition = false;
if( newLine )
{
// Paragraph change.
startBlockLevel();
// Figure out which elements cannot be enclosed inside
// a <p></p> pair according to XHTML rules.
String nextLine = peekAheadLine();
if( nextLine.length() == 0 ||
(nextLine.length() > 0 &&
!nextLine.startsWith("{{{") &&
!nextLine.startsWith("
!nextLine.startsWith("%%") &&
"*#!;".indexOf( nextLine.charAt(0) ) == -1) )
{
pushElement( new Element("p") );
m_isOpenParagraph = true;
}
}
else
{
m_plainTextBuf.append("\n");
newLine = true;
}
continue;
case '\\':
el = handleBackslash();
break;
case '_':
el = handleUnderscore();
break;
case '\'':
el = handleApostrophe();
break;
case '{':
el = handleOpenbrace( newLine );
break;
case '}':
el = handleClosebrace();
break;
case '-':
if( newLine )
el = handleDash();
break;
case '!':
if( newLine )
{
el = handleHeading();
}
else
{
s = "!";
}
break;
case ';':
if( newLine )
{
el = handleDefinitionList();
}
break;
case ':':
if( m_isdefinition )
{
popElement("dt");
el = pushElement( new Element("dd") );
m_isdefinition = false;
}
break;
case '[':
el = handleOpenbracket();
break;
case '*':
if( newLine )
{
pushBack('*');
el = handleGeneralList();
}
break;
case '
if( newLine )
{
pushBack('
el = handleGeneralList();
}
break;
case '|':
el = handleBar( newLine );
break;
/*
case '<':
s = m_allowHTML ? "<" : "<";
break;
case '>':
s = m_allowHTML ? ">" : ">";
break;
case '\"':
s = m_allowHTML ? "\"" : """;
break;
*/
/*
case '&':
s = "&";
break;
*/
case '~':
el = handleTilde();
break;
case '%':
el = handleDiv( newLine );
break;
case -1:
quitReading = true;
continue;
/*
default:
m_plainTextBuf.append( (char)ch );
newLine = false;
break;
*/
}
// The idea is as follows: If the handler method returns
// an element (el != null), it is assumed that it has been
// added in the stack. Otherwise the character is added
// as is to the plaintext buffer.
// For the transition phase, if s != null, it also gets
// added in the plaintext buffer.
if( el != null )
{
newLine = false;
}
else
{
m_plainTextBuf.append( (char) ch );
newLine = false;
}
if( s != null )
{
m_plainTextBuf.append( s );
newLine = false;
}
}
popElement("domroot");
}
public WikiDocument parse()
throws IOException
{
WikiDocument d = new WikiDocument( m_context.getPage() );
Element rootElement = new Element("domroot");
d.setRootElement( rootElement );
try
{
fillBuffer( rootElement );
}
catch( IllegalDataException e )
{
log.error("Page "+m_context.getPage().getName()+" contained something that cannot be added in the DOM tree",e);
throw new IOException("Illegal page data: "+e.getMessage());
}
return d;
}
/**
* Compares two Strings, and if one starts with the other, then
* returns null. Otherwise just like the normal Comparator
* for strings.
*
* @author jalkanen
*
* @since
*/
private static class StartingComparator implements Comparator
{
public int compare( Object arg0, Object arg1 )
{
String s1 = (String)arg0;
String s2 = (String)arg1;
if( s1.length() > s2.length() )
{
if( s1.startsWith(s2) && s2.length() > 1 ) return 0;
}
else
{
if( s2.startsWith(s1) && s1.length() > 1 ) return 0;
}
return s1.compareTo( s2 );
}
}
}
|
package com.jensen.game.othello.view;
import com.jensen.game.view.DefualtGameView;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
* An Extension of the defualt game view to display a othello game.
* Overrides updateCell to display othello pieces instead of text.
*
* @see DefualtGameView
*/
public class OthelloGameView extends DefualtGameView {
/**
* Creates a othello game view with Othello written in the header.
*/
public OthelloGameView() {
super("Othello");
}
@Override
public void updateCell(int x, int y, String status) {
throw new NotImplementedException();
}
}
|
package com.redhat.ceylon.common.tool;
import java.io.File;
import java.util.List;
import com.redhat.ceylon.common.FileUtil;
import com.redhat.ceylon.common.tools.CeylonTool;
public abstract class CeylonBaseTool implements Tool {
protected File cwd;
public String verbose;
protected List<String> defines;
public File getCwd() {
return cwd;
}
@OptionArgument(longName="cwd", argumentName="dir")
@Description("Specifies the current working directory for this tool. " +
"(default: the directory where the tool is run from)")
public void setCwd(File cwd) {
this.cwd = cwd;
}
public String getVerbose() {
return verbose;
}
@Option(shortName='d')
@OptionArgument(argumentName = "flags")
@Description("Produce verbose output. " +
"If no `flags` are given then be verbose about everything, " +
"otherwise just be verbose about the flags which are present. " +
"Allowed flags include: `all`, `loader`.")
public void setVerbose(String verbose) {
this.verbose = verbose;
}
@OptionArgument(shortName='D', argumentName = "key>=<value")
@Description("Set a system property")
public void setDefine(List<String> defines) {
this.defines = defines;
}
protected void setSystemProperties() {
if (defines != null) {
for (String prop : defines) {
int p = prop.indexOf('=');
if (p > 0) {
String key = prop.substring(0, p);
String val = prop.substring(p + 1);
System.setProperty(key, val);
}
}
}
}
protected File validCwd() {
return (cwd != null) ? cwd : new File(".");
}
protected List<File> applyCwd(List<File> files) {
return FileUtil.applyCwd(getCwd(), files);
}
protected File applyCwd(File file) {
return FileUtil.applyCwd(getCwd(), file);
}
@Override
public void initialize(CeylonTool mainTool) throws Exception {
// Empty default implementation for simple tools that don't need initialization
}
}
|
package com.tw.go.plugin;
import com.google.gson.GsonBuilder;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.GoPlugin;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.api.annotation.Extension;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import java.util.*;
import static java.util.Arrays.asList;
@Extension
public class EmailNotificationPluginImpl implements GoPlugin {
private static Logger LOGGER = Logger.getLoggerFor(EmailNotificationPluginImpl.class);
public static final String EXTENSION_NAME = "notification";
private static final List<String> goSupportedVersions = asList("1.0");
public static final String REQUEST_NOTIFICATIONS_INTERESTED_IN = "notifications-interested-in";
public static final String REQUEST_STAGE_STATUS = "stage-status";
public static final int SUCCESS_RESPONSE_CODE = 200;
public static final int INTERNAL_ERROR_RESPONSE_CODE = 500;
@Override
public void initializeGoApplicationAccessor(GoApplicationAccessor goApplicationAccessor) {
// ignore
}
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) {
if (goPluginApiRequest.requestName().equals(REQUEST_NOTIFICATIONS_INTERESTED_IN)) {
return handleNotificationsInterestedIn();
} else if (goPluginApiRequest.requestName().equals(REQUEST_STAGE_STATUS)) {
return handleStageNotification(goPluginApiRequest);
}
return null;
}
@Override
public GoPluginIdentifier pluginIdentifier() {
return new GoPluginIdentifier(EXTENSION_NAME, goSupportedVersions);
}
private GoPluginApiResponse handleNotificationsInterestedIn() {
Map<String, Object> response = new HashMap<String, Object>();
response.put("notifications", Arrays.asList(REQUEST_STAGE_STATUS));
return renderJSON(SUCCESS_RESPONSE_CODE, response);
}
private GoPluginApiResponse handleStageNotification(GoPluginApiRequest goPluginApiRequest) {
Map<String, Object> dataMap = getMapFor(goPluginApiRequest);
int responseCode = SUCCESS_RESPONSE_CODE;
Map<String, Object> response = new HashMap<String, Object>();
List<String> messages = new ArrayList<String>();
try {
Map<String, Object> pipelineMap = (Map<String, Object>) dataMap.get("pipeline");
Map<String, Object> stageMap = (Map<String, Object>) pipelineMap.get("stage");
String subject = String.format("Stage: %s/%s/%s/%s", pipelineMap.get("name"), pipelineMap.get("counter"), stageMap.get("name"), stageMap.get("counter"));
String body = String.format("State: %s\nResult: %s\nCreate Time: %s\nLast Transition Time: %s", stageMap.get("state"), stageMap.get("result"), stageMap.get("create-time"), stageMap.get("last-transition-time"));
LOGGER.warn("Sending Email for " + subject);
SMTPSettings settings = new SMTPSettings("smtp.gmail.com", 587, true, "", "");
new SMTPMailSender(settings).send(subject, body, "");
LOGGER.warn("Done");
response.put("status", "success");
} catch (Exception e) {
LOGGER.warn("Error occurred while trying to deliver an email.", e);
responseCode = INTERNAL_ERROR_RESPONSE_CODE;
response.put("status", "failure");
if (!isEmpty(e.getMessage())) {
messages.add(e.getMessage());
}
}
response.put("messages", messages);
return renderJSON(responseCode, response);
}
private boolean isEmpty(String str) {
return str == null || str.trim().isEmpty();
}
private Map<String, Object> getMapFor(GoPluginApiRequest goPluginApiRequest) {
return (Map<String, Object>) new GsonBuilder().create().fromJson(goPluginApiRequest.requestBody(), Object.class);
}
private GoPluginApiResponse renderJSON(final int responseCode, Object response) {
final String json = response == null ? null : new GsonBuilder().create().toJson(response);
return new GoPluginApiResponse() {
@Override
public int responseCode() {
return responseCode;
}
@Override
public Map<String, String> responseHeaders() {
return null;
}
@Override
public String responseBody() {
return json;
}
};
}
}
|
package com.stripe.android.model;
import com.stripe.android.util.DateUtils;
import com.stripe.android.util.TextUtils;
public class Card extends com.stripe.model.StripeObject {
String number;
String cvc;
Integer expMonth;
Integer expYear;
String name;
String addressLine1;
String addressLine2;
String addressCity;
String addressState;
String addressZip;
String addressCountry;
String last4;
String type;
String fingerprint;
String country;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getCVC() {
return cvc;
}
public void setCVC(String cvc) {
this.cvc = cvc;
}
public Integer getExpMonth() {
return expMonth;
}
public void setExpMonth(Integer expMonth) {
this.expMonth = expMonth;
}
public Integer getExpYear() {
return expYear;
}
public void setExpYear(Integer expYear) {
this.expYear = expYear;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getAddressCity() {
return addressCity;
}
public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
public String getAddressZip() {
return addressZip;
}
public void setAddressZip(String addressZip) {
this.addressZip = addressZip;
}
public String getAddressState() {
return addressState;
}
public void setAddressState(String addressState) {
this.addressState = addressState;
}
public String getAddressCountry() {
return addressCountry;
}
public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}
public String getLast4() {
if (!TextUtils.isBlank(last4)) {
return last4;
}
if (number != null && number.length() > 4) {
return number.substring(number.length() - 4, number.length());
}
return null;
}
public String getType() {
if (TextUtils.isBlank(type) && !TextUtils.isBlank(number)) {
if (TextUtils.hasAnyPrefix(number, "34", "37")) {
return "American Express";
} else if (TextUtils.hasAnyPrefix(number, "60", "62", "64", "65")) {
return "Discover";
} else if (TextUtils.hasAnyPrefix(number, "35")) {
return "JCB";
} else if (TextUtils.hasAnyPrefix(number, "30", "36", "38", "39")) {
return "Diners Club";
} else if (TextUtils.hasAnyPrefix(number, "4")) {
return "Visa";
} else if (TextUtils.hasAnyPrefix(number, "5")) {
return "MasterCard";
} else {
return "Unknown";
}
}
return type;
}
public String getFingerprint() {
return fingerprint;
}
public String getCountry() {
return country;
}
public Card(String number, Integer expMonth, Integer expYear, String cvc, String name, String addressLine1, String addressLine2, String addressCity, String addressState, String addressZip, String addressCountry, String last4, String type, String fingerprint, String country) {
this.number = TextUtils.nullIfBlank(normalizeCardNumber(number));
this.expMonth = expMonth;
this.expYear = expYear;
this.cvc = TextUtils.nullIfBlank(cvc);
this.name = TextUtils.nullIfBlank(name);
this.addressLine1 = TextUtils.nullIfBlank(addressLine1);
this.addressLine2 = TextUtils.nullIfBlank(addressLine2);
this.addressCity = TextUtils.nullIfBlank(addressCity);
this.addressState = TextUtils.nullIfBlank(addressState);
this.addressZip = TextUtils.nullIfBlank(addressZip);
this.addressCountry = TextUtils.nullIfBlank(addressCountry);
this.last4 = TextUtils.nullIfBlank(last4);
this.type = TextUtils.nullIfBlank(type);
this.fingerprint = TextUtils.nullIfBlank(fingerprint);
this.country = TextUtils.nullIfBlank(country);
this.type = getType();
}
public Card(String number, Integer expMonth, Integer expYear, String cvc, String name, String addressLine1, String addressLine2, String addressCity, String addressState, String addressZip, String addressCountry) {
this(number, expMonth, expYear, cvc, name, addressLine1, addressLine2, addressCity, addressState, addressZip, addressCountry, null, null, null, null);
}
public Card(String number, Integer expMonth, Integer expYear, String cvc) {
this(number, expMonth, expYear, cvc, null, null, null, null, null, null, null, null, null, null, null);
}
public boolean validateCard() {
if (cvc == null) {
return validateNumber() && validateExpiryDate();
} else {
return validateNumber() && validateExpiryDate() && validateCVC();
}
}
public boolean validateNumber() {
if (TextUtils.isBlank(number)) {
return false;
}
String rawNumber = number.trim().replaceAll("\\s+|-", "");
if (TextUtils.isBlank(rawNumber)
|| !TextUtils.isWholePositiveNumber(rawNumber)
|| !isValidLuhnNumber(rawNumber)) {
return false;
}
if (!"American Express".equals(type) && rawNumber.length() != 16) {
return false;
}
if ("American Express".equals(type) && rawNumber.length() != 15) {
return false;
}
return true;
}
public boolean validateExpiryDate() {
if (!validateExpMonth()) {
return false;
}
if (!validateExpYear()) {
return false;
}
return !DateUtils.hasMonthPassed(expYear, expMonth);
}
public boolean validateExpMonth() {
if (expMonth == null) {
return false;
}
return (expMonth >= 1 && expMonth <= 12);
}
public boolean validateExpYear() {
if (expYear == null) {
return false;
}
return !DateUtils.hasYearPassed(expYear);
}
public boolean validateCVC() {
if (TextUtils.isBlank(cvc)) {
return false;
}
String cvcValue = cvc.trim();
boolean validLength = ((type == null && cvcValue.length() >= 3 && cvcValue.length() <= 4) ||
("American Express".equals(type) && cvcValue.length() == 4) ||
(!"American Express".equals(type) && cvcValue.length() == 3));
if (!TextUtils.isWholePositiveNumber(cvcValue) || !validLength) {
return false;
}
return true;
}
private boolean isValidLuhnNumber(String number) {
boolean isOdd = true;
int sum = 0;
for (int index = number.length() - 1; index >= 0; index
char c = number.charAt(index);
if (!Character.isDigit(c)) {
return false;
}
int digitInteger = Integer.parseInt("" + c);
isOdd = !isOdd;
if (isOdd) {
digitInteger *= 2;
}
if (digitInteger > 9) {
digitInteger -= 9;
}
sum += digitInteger;
}
return sum % 10 == 0;
}
private String normalizeCardNumber(String number) {
if (number == null) {
return null;
}
return number.trim().replaceAll("\\s+|-", "");
}
}
|
package net.fortuna.ical4j.model.component;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Iterator;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentTest;
import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.ParameterList;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.Recur;
import net.fortuna.ical4j.model.TimeZone;
import net.fortuna.ical4j.model.TimeZoneRegistry;
import net.fortuna.ical4j.model.TimeZoneRegistryFactory;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.WeekDay;
import net.fortuna.ical4j.model.parameter.TzId;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.ExDate;
import net.fortuna.ical4j.model.property.RRule;
import net.fortuna.ical4j.model.property.Summary;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.util.Calendars;
import net.fortuna.ical4j.util.UidGenerator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A test case for VEvents.
* @author Ben Fortuna
*/
public class VEventTest extends ComponentTest {
private static Log log = LogFactory.getLog(VEventTest.class);
private TimeZoneRegistry registry;
private VTimeZone tz;
private TzId tzParam;
private VEvent weekdayNineToFiveEvents = null;
private VEvent dailyWeekdayEvents = null;
private VEvent monthlyWeekdayEvents = null;
public void setUp() throws Exception {
super.setUp();
registry = TimeZoneRegistryFactory.getInstance().createRegistry();
// create timezone property..
tz = registry.getTimeZone("Australia/Melbourne").getVTimeZone();
// create tzid parameter..
tzParam = new TzId(tz.getProperty(Property.TZID).getValue());
Calendar weekday9AM = getCalendarInstance();
weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0);
weekday9AM.set(Calendar.MILLISECOND, 0);
Calendar weekday5PM = getCalendarInstance();
weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0);
weekday5PM.set(Calendar.MILLISECOND, 0);
// Do the recurrence until December 31st.
Calendar untilCal = getCalendarInstance();
untilCal.set(2005, Calendar.DECEMBER, 31);
untilCal.set(Calendar.MILLISECOND, 0);
Date until = new Date(untilCal.getTime().getTime());
// 9:00AM to 5:00PM Rule using weekly
Recur recurWeekly = new Recur(Recur.WEEKLY, until);
recurWeekly.getDayList().add(WeekDay.MO);
recurWeekly.getDayList().add(WeekDay.TU);
recurWeekly.getDayList().add(WeekDay.WE);
recurWeekly.getDayList().add(WeekDay.TH);
recurWeekly.getDayList().add(WeekDay.FR);
recurWeekly.setInterval(1);
recurWeekly.setWeekStartDay(WeekDay.MO.getDay());
RRule rruleWeekly = new RRule(recurWeekly);
// 9:00AM to 5:00PM Rule using daily frequency
Recur recurDaily = new Recur(Recur.DAILY, until);
recurDaily.getDayList().add(WeekDay.MO);
recurDaily.getDayList().add(WeekDay.TU);
recurDaily.getDayList().add(WeekDay.WE);
recurDaily.getDayList().add(WeekDay.TH);
recurDaily.getDayList().add(WeekDay.FR);
recurDaily.setInterval(1);
recurDaily.setWeekStartDay(WeekDay.MO.getDay());
RRule rruleDaily = new RRule(recurDaily);
// 9:00AM to 5:00PM Rule using monthly frequency
Recur recurMonthly = new Recur(Recur.MONTHLY, until);
recurMonthly.getDayList().add(WeekDay.MO);
recurMonthly.getDayList().add(WeekDay.TU);
recurMonthly.getDayList().add(WeekDay.WE);
recurMonthly.getDayList().add(WeekDay.TH);
recurMonthly.getDayList().add(WeekDay.FR);
recurMonthly.setInterval(1);
recurMonthly.setWeekStartDay(WeekDay.MO.getDay());
RRule rruleMonthly = new RRule(recurMonthly);
Summary summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED WEEKLY");
weekdayNineToFiveEvents = new VEvent();
weekdayNineToFiveEvents.getProperties().add(rruleWeekly);
weekdayNineToFiveEvents.getProperties().add(summary);
DtStart dtStart = new DtStart(new DateTime(weekday9AM.getTime().getTime()));
// dtStart.getParameters().add(Value.DATE);
weekdayNineToFiveEvents.getProperties().add(dtStart);
DtEnd dtEnd = new DtEnd(new DateTime(weekday5PM.getTime().getTime()));
// dtEnd.getParameters().add(Value.DATE);
weekdayNineToFiveEvents.getProperties().add(dtEnd);
weekdayNineToFiveEvents.getProperties().add(new Uid("000001@modularity.net.au"));
// ensure event is valid..
weekdayNineToFiveEvents.validate();
summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED DAILY");
dailyWeekdayEvents = new VEvent();
dailyWeekdayEvents.getProperties().add(rruleDaily);
dailyWeekdayEvents.getProperties().add(summary);
DtStart dtStart2 = new DtStart(new DateTime(weekday9AM.getTime().getTime()));
// dtStart2.getParameters().add(Value.DATE);
dailyWeekdayEvents.getProperties().add(dtStart2);
DtEnd dtEnd2 = new DtEnd(new DateTime(weekday5PM.getTime().getTime()));
// dtEnd2.getParameters().add(Value.DATE);
dailyWeekdayEvents.getProperties().add(dtEnd2);
dailyWeekdayEvents.getProperties().add(new Uid("000002@modularity.net.au"));
// ensure event is valid..
dailyWeekdayEvents.validate();
summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED MONTHLY");
monthlyWeekdayEvents = new VEvent();
monthlyWeekdayEvents.getProperties().add(rruleMonthly);
monthlyWeekdayEvents.getProperties().add(summary);
DtStart dtStart3 = new DtStart(new DateTime(weekday9AM.getTime().getTime()));
// dtStart3.getParameters().add(Value.DATE);
monthlyWeekdayEvents.getProperties().add(dtStart3);
DtEnd dtEnd3 = new DtEnd(new DateTime(weekday5PM.getTime().getTime()));
// dtEnd3.getParameters().add(Value.DATE);
monthlyWeekdayEvents.getProperties().add(dtEnd3);
monthlyWeekdayEvents.getProperties().add(new Uid("000003@modularity.net.au"));
// ensure event is valid..
monthlyWeekdayEvents.validate();
}
/**
* @return
*/
private Calendar getCalendarInstance() {
return Calendar.getInstance(); //java.util.TimeZone.getTimeZone(TimeZones.GMT_ID));
}
/**
* @param filename
* @return
*/
private net.fortuna.ical4j.model.Calendar loadCalendar(String filename)
throws IOException, ParserException, ValidationException {
net.fortuna.ical4j.model.Calendar calendar = Calendars.load(
filename);
calendar.validate();
log.info("File: " + filename);
if (log.isDebugEnabled()) {
log.debug("Calendar:\n=========\n" + calendar.toString());
}
return calendar;
}
public final void testChristmas() {
// create event start date..
java.util.Calendar calendar = getCalendarInstance();
calendar.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER);
calendar.set(java.util.Calendar.DAY_OF_MONTH, 25);
DtStart start = new DtStart(new Date(calendar.getTime()));
start.getParameters().add(tzParam);
start.getParameters().add(Value.DATE);
Summary summary = new Summary("Christmas Day; \n this is a, test\\");
VEvent christmas = new VEvent();
christmas.getProperties().add(start);
christmas.getProperties().add(summary);
log.info(christmas);
}
/**
* Test creating an event with an associated timezone.
*/
public final void testMelbourneCup() {
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TimeZone timezone = registry.getTimeZone("Australia/Melbourne");
java.util.Calendar cal = java.util.Calendar.getInstance(timezone);
cal.set(java.util.Calendar.YEAR, 2005);
cal.set(java.util.Calendar.MONTH, java.util.Calendar.NOVEMBER);
cal.set(java.util.Calendar.DAY_OF_MONTH, 1);
cal.set(java.util.Calendar.HOUR_OF_DAY, 15);
cal.clear(java.util.Calendar.MINUTE);
cal.clear(java.util.Calendar.SECOND);
DateTime dt = new DateTime(cal.getTime());
dt.setTimeZone(timezone);
VEvent melbourneCup = new VEvent(dt, "Melbourne Cup");
log.info(melbourneCup);
}
public final void test2() {
java.util.Calendar cal = getCalendarInstance();
cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER);
cal.set(java.util.Calendar.DAY_OF_MONTH, 25);
VEvent christmas = new VEvent(new Date(cal.getTime()), "Christmas Day");
// initialise as an all-day event..
christmas.getProperty(Property.DTSTART).getParameters().add(Value.DATE);
// add timezone information..
christmas.getProperty(Property.DTSTART).getParameters().add(tzParam);
log.info(christmas);
}
public final void test3() {
java.util.Calendar cal = getCalendarInstance();
// tomorrow..
cal.add(java.util.Calendar.DAY_OF_MONTH, 1);
cal.set(java.util.Calendar.HOUR_OF_DAY, 9);
cal.set(java.util.Calendar.MINUTE, 30);
VEvent meeting = new VEvent(new DateTime(cal.getTime().getTime()), new Dur(0, 1, 0, 0), "Progress Meeting");
// add timezone information..
meeting.getProperty(Property.DTSTART).getParameters().add(tzParam);
log.info(meeting);
}
/**
* Test Null Dates
* Test Start today, End One month from now.
*
* @throws Exception
*/
public final void testGetConsumedTime() throws Exception {
// Test Null Dates
try {
weekdayNineToFiveEvents.getConsumedTime(null, null);
fail("Should've thrown an exception.");
} catch (RuntimeException re) {
log.info("Expecting an exception here.");
}
// Test Start 04/01/2005, End One month later.
// Query Calendar Start and End Dates.
Calendar queryStartDate = getCalendarInstance();
queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0);
queryStartDate.set(Calendar.MILLISECOND, 0);
DateTime queryStart = new DateTime(queryStartDate.getTime().getTime());
Calendar queryEndDate = getCalendarInstance();
queryEndDate.set(2005, Calendar.MAY, 1, 07, 15, 0);
queryEndDate.set(Calendar.MILLISECOND, 0);
DateTime queryEnd = new DateTime(queryEndDate.getTime().getTime());
Calendar week1EndDate = getCalendarInstance();
week1EndDate.set(2005, Calendar.APRIL, 8, 11, 15, 0);
week1EndDate.set(Calendar.MILLISECOND, 0);
Calendar week4StartDate = getCalendarInstance();
week4StartDate.set(2005, Calendar.APRIL, 24, 14, 47, 0);
week4StartDate.set(Calendar.MILLISECOND, 0);
DateTime week4Start = new DateTime(week4StartDate.getTime().getTime());
// This range is monday to friday every three weeks, starting from
// March 7th 2005, which means for our query dates we need
// April 18th through to the 22nd.
PeriodList weeklyPeriods = weekdayNineToFiveEvents.getConsumedTime(queryStart, queryEnd);
PeriodList dailyPeriods = dailyWeekdayEvents.getConsumedTime(queryStart, queryEnd);
// week1EndDate.getTime());
dailyPeriods.addAll(dailyWeekdayEvents.getConsumedTime(week4Start, queryEnd));
Calendar expectedCal = Calendar.getInstance(); //TimeZone.getTimeZone(TimeZones.GMT_ID));
expectedCal.set(2005, Calendar.APRIL, 1, 9, 0, 0);
expectedCal.set(Calendar.MILLISECOND, 0);
Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime().getTime());
expectedCal.set(2005, Calendar.APRIL, 1, 17, 0, 0);
expectedCal.set(Calendar.MILLISECOND, 0);
Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime().getTime());
assertNotNull(weeklyPeriods);
assertTrue(weeklyPeriods.size() > 0);
Period firstPeriod = (Period) weeklyPeriods.toArray()[0];
assertEquals(expectedStartOfFirstRange, firstPeriod.getStart());
assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd());
assertEquals(dailyPeriods, weeklyPeriods);
}
public final void testGetConsumedTimeDaily() throws Exception {
// Test Starts 04/03/2005, Ends One week later.
// Query Calendar Start and End Dates.
Calendar queryStartDate = getCalendarInstance();
queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0);
queryStartDate.set(Calendar.MILLISECOND, 0);
Calendar queryEndDate = getCalendarInstance();
queryEndDate.set(2005, Calendar.APRIL, 10, 21, 55, 0);
queryEndDate.set(Calendar.MILLISECOND, 0);
// This range is Monday to Friday every day (which has a filtering
// effect), starting from March 7th 2005. Our query dates are
// April 3rd through to the 10th.
PeriodList weeklyPeriods =
weekdayNineToFiveEvents.getConsumedTime(new DateTime(queryStartDate.getTime()),
new DateTime(queryEndDate.getTime()));
PeriodList dailyPeriods =
dailyWeekdayEvents.getConsumedTime(new DateTime(queryStartDate.getTime()),
new DateTime(queryEndDate.getTime()));
Calendar expectedCal = getCalendarInstance();
expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0);
expectedCal.set(Calendar.MILLISECOND, 0);
Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime());
expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0);
expectedCal.set(Calendar.MILLISECOND, 0);
Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime());
assertNotNull(dailyPeriods);
assertTrue(dailyPeriods.size() > 0);
Period firstPeriod = (Period) dailyPeriods.toArray()[0];
assertEquals(expectedStartOfFirstRange, firstPeriod.getStart());
assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd());
assertEquals(weeklyPeriods, dailyPeriods);
}
/**
* Test whether you can select weekdays using a monthly frequency.
* <p>
* This test really belongs in RecurTest, but the weekly range test
* in this VEventTest matches so perfectly with the daily range test
* that should produce the same results for some weeks that it was
* felt leveraging the existing test code was more important.
* <p>
* Section 4.3.10 of the iCalendar specification RFC 2445 reads:
* <pre>
* If an integer modifier is not present, it means all days of
* this type within the specified frequency.
* </pre>
* This test ensures compliance.
*/
public final void testGetConsumedTimeMonthly() throws Exception {
// Test Starts 04/03/2005, Ends two weeks later.
// Query Calendar Start and End Dates.
Calendar queryStartDate = getCalendarInstance();
queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0);
queryStartDate.set(Calendar.MILLISECOND, 0);
Calendar queryEndDate = getCalendarInstance();
queryEndDate.set(2005, Calendar.APRIL, 17, 21, 55, 0);
queryEndDate.set(Calendar.MILLISECOND, 0);
// This range is Monday to Friday every month (which has a multiplying
// effect), starting from March 7th 2005. Our query dates are
// April 3rd through to the 17th.
PeriodList monthlyPeriods =
monthlyWeekdayEvents.getConsumedTime(new DateTime(queryStartDate.getTime()),
new DateTime(queryEndDate.getTime()));
PeriodList dailyPeriods =
dailyWeekdayEvents.getConsumedTime(new DateTime(queryStartDate.getTime()),
new DateTime(queryEndDate.getTime()));
Calendar expectedCal = getCalendarInstance();
expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0);
expectedCal.set(Calendar.MILLISECOND, 0);
Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime());
expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0);
expectedCal.set(Calendar.MILLISECOND, 0);
Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime());
assertNotNull(monthlyPeriods);
assertTrue(monthlyPeriods.size() > 0);
Period firstPeriod = (Period) monthlyPeriods.toArray()[0];
assertEquals(expectedStartOfFirstRange, firstPeriod.getStart());
assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd());
assertEquals(dailyPeriods, monthlyPeriods);
}
public final void testGetConsumedTime2() throws Exception {
String filename = "etc/samples/valid/derryn.ics";
net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename);
Date start = new Date();
Calendar endCal = getCalendarInstance();
endCal.setTime(start);
endCal.add(Calendar.WEEK_OF_YEAR, 4);
// Date end = new Date(start.getTime() + (1000 * 60 * 60 * 24 * 7 * 4));
for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
Component c = (Component) i.next();
if (c instanceof VEvent) {
PeriodList consumed = ((VEvent) c).getConsumedTime(start, new Date(endCal.getTime().getTime()));
log.debug("Event [" + c + "]");
log.debug("Consumed time [" + consumed + "]");
}
}
}
public final void testGetConsumedTime3() throws Exception {
String filename = "etc/samples/valid/calconnect10.ics";
net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename);
VEvent vev = (VEvent) calendar.getComponent(Component.VEVENT);
Date start = vev.getStartDate().getDate();
Calendar cal = getCalendarInstance();
cal.add(Calendar.YEAR, 1);
Date latest = new Date(cal.getTime());
PeriodList pl = vev.getConsumedTime(start, latest);
Iterator it = pl.iterator();
assertTrue(it.hasNext());
}
/**
* Test COUNT rules.
*/
public void testGetConsumeTimeByCount() {
Recur recur = new Recur(Recur.WEEKLY, 3);
recur.setInterval(1);
recur.getDayList().add(WeekDay.SU);
log.info(recur);
Calendar cal = getCalendarInstance();
cal.set(Calendar.DAY_OF_MONTH, 8);
Date start = new DateTime(cal.getTime());
// cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 10);
cal.add(Calendar.HOUR_OF_DAY, 1);
Date end = new DateTime(cal.getTime());
// log.info(recur.getDates(start, end, Value.DATE_TIME));
RRule rrule = new RRule(recur);
VEvent event = new VEvent(start, end, "Test recurrence COUNT");
event.getProperties().add(rrule);
log.info(event);
Calendar rangeCal = getCalendarInstance();
Date rangeStart = new DateTime(rangeCal.getTime());
rangeCal.add(Calendar.WEEK_OF_YEAR, 4);
Date rangeEnd = new DateTime(rangeCal.getTime());
log.info(event.getConsumedTime(rangeStart, rangeEnd));
}
/**
* A test to confirm that the end date is calculated correctly
* from a given start date and duration.
*/
public final void testEventEndDate() {
Calendar cal = getCalendarInstance();
Date startDate = new Date(cal.getTime());
log.info("Start date: " + startDate);
VEvent event = new VEvent(startDate, new Dur(3, 0, 0, 0), "3 day event");
Date endDate = event.getEndDate().getDate();
log.info("End date: " + endDate);
cal.add(Calendar.DAY_OF_YEAR, 3);
assertEquals(new Date(cal.getTime()), endDate);
}
/**
* Test to ensure that EXDATE properties are correctly applied.
* @throws ParseException
*/
public void testGetConsumedTimeWithExDate() throws ParseException {
VEvent event1 = new VEvent(new DateTime("20050103T080000"),
new Dur(0, 0, 15, 0),
"Event 1");
Recur rRuleRecur = new Recur("FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR");
RRule rRule = new RRule(rRuleRecur);
event1.getProperties().add(rRule);
ParameterList parameterList = new ParameterList();
parameterList.add(Value.DATE);
ExDate exDate = new ExDate(parameterList, "20050106");
event1.getProperties().add(exDate);
Date start = new Date("20050106");
Date end = new Date("20050107");
PeriodList list = event1.getConsumedTime(start, end);
assertTrue(list.isEmpty());
}
/**
* Test to ensure that EXDATE properties are correctly applied.
* @throws ParseException
*/
public void testGetConsumedTimeWithExDate2() throws IOException, ParserException {
FileInputStream fin = new FileInputStream("etc/samples/valid/friday13.ics");
net.fortuna.ical4j.model.Calendar calendar = new CalendarBuilder().build(fin);
VEvent event = (VEvent) calendar.getComponent(Component.VEVENT);
Calendar cal = Calendar.getInstance();
cal.set(1997, 8, 2);
Date start = new Date(cal.getTime());
cal.set(1997, 8, 4);
Date end = new Date(cal.getTime());
PeriodList periods = event.getConsumedTime(start, end);
assertTrue(periods.isEmpty());
}
/* (non-Javadoc)
* @see net.fortuna.ical4j.model.ComponentTest#testIsCalendarComponent()
*/
public void testIsCalendarComponent() {
assertIsCalendarComponent(new VEvent());
}
/**
* Test equality of events with different alarm sub-components.
*/
public void testEquals() {
Date date = new Date();
String summary = "test event";
PropertyList props = new PropertyList();
props.add(new DtStart(date));
props.add(new Summary(summary));
VEvent e1 = new VEvent(props);
VEvent e2 = new VEvent(props);
assertTrue(e1.equals(e2));
e2.getAlarms().add(new VAlarm());
assertFalse(e1.equals(e2));
}
/**
* Test VEvent validation.
*/
public void testValidation() throws SocketException, ValidationException {
UidGenerator ug = new UidGenerator("1");
Uid uid = ug.generateUid();
DtStart start = new DtStart();
DtEnd end = new DtEnd();
VEvent event = new VEvent();
event.getProperties().add(uid);
event.getProperties().add(start);
event.getProperties().add(end);
event.validate();
start.getParameters().replace(Value.DATE_TIME);
event.validate();
start.getParameters().remove(Value.DATE_TIME);
end.getParameters().replace(Value.DATE_TIME);
event.validate();
// test 1..
start.getParameters().replace(Value.DATE);
try {
event.validate();
}
catch (ValidationException ve) {
log.info("Caught exception: [" + ve.getMessage() + "]");
}
// test 2..
start.getParameters().replace(Value.DATE_TIME);
end.getParameters().replace(Value.DATE);
try {
event.validate();
}
catch (ValidationException ve) {
log.info("Caught exception: [" + ve.getMessage() + "]");
}
// test 3..
start.getParameters().replace(Value.DATE);
end.getParameters().replace(Value.DATE_TIME);
try {
event.validate();
}
catch (ValidationException ve) {
log.info("Caught exception: [" + ve.getMessage() + "]");
}
// test 3..
start.getParameters().remove(Value.DATE);
end.getParameters().replace(Value.DATE);
try {
event.validate();
}
catch (ValidationException ve) {
log.info("Caught exception: [" + ve.getMessage() + "]");
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.sam;
import org.broad.igv.AbstractHeadlessTest;
import org.broad.igv.PreferenceManager;
import org.broad.igv.sam.reader.AlignmentReader;
import org.broad.igv.sam.reader.AlignmentReaderFactory;
import org.broad.igv.util.ResourceLocator;
import org.junit.Ignore;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
/**
* @author jrobinso
*/
public class AlignmentTileLoaderTest extends AbstractHeadlessTest {
/**
* Test that sampling keeps pairs together. Note that this test requires a lot of memory (2Gb on this devs machine)
* Pairs are only definitely kept together if they end up on the same tile, so we need 1 big tile.
*
* @throws Exception
*/
@Ignore
@Test
public void testKeepPairs() throws Exception {
String path = "http:
String sequence = "1";
int start = 1;
int end = 2000;
int maxDepth = 2;
String max_vis = PreferenceManager.getInstance().get(PreferenceManager.SAM_MAX_VISIBLE_RANGE);
PreferenceManager.getInstance().put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, "" + (end - start));
try {
ResourceLocator loc = new ResourceLocator(path);
AlignmentReader reader = AlignmentReaderFactory.getReader(loc);
AlignmentTileLoader loader = new AlignmentTileLoader(reader);
AlignmentDataManager.DownsampleOptions downsampleOptions = new AlignmentDataManager.DownsampleOptions();
AlignmentTileLoader.AlignmentTile tile = loader.loadTile(sequence, start, end, null, downsampleOptions, null, null, null);
List<Alignment> alignments = tile.getAlignments();
int count = 0;
Map<String, Integer> pairedReads = new HashMap<String, Integer>();
for(Alignment al: alignments) {
assertNotNull(al);
count++;
if (al.isPaired() && al.getMate().isMapped()) {
//Mate may not be part of the query.
//Make sure it's within bounds
int mateStart = al.getMate().getStart();
//All we require is some overlap
boolean overlap = mateStart >= start && mateStart < end;
if (overlap) {
Integer rdCnt = pairedReads.get(al.getReadName());
rdCnt = rdCnt != null ? rdCnt + 1 : 1;
pairedReads.put(al.getReadName(), rdCnt);
}
}
}
assertTrue(count > 0);
//Note: CachingQueryReader will not line alignments up properly if they land in different tiles
int countmissing = 0;
for (String readName : pairedReads.keySet()) {
int val = pairedReads.get(readName);
countmissing += 2 == val ? 0 : 1;
if (val != 2) {
System.out.println("Read " + readName + " has val " + val);
}
}
//System.out.println("Number of paired reads: " + pairedReads.size());
assertTrue("No pairs in test data set", pairedReads.size() > 0);
assertEquals("Missing " + countmissing + " out of " + pairedReads.size() + " pairs", 0, countmissing);
} catch (Exception e) {
PreferenceManager.getInstance().put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, max_vis);
throw e;
}
}
public static void main(String[] args) {
//Represents total number of alignments
long totalLength = (long) 1e6;
//Memory used per alignment
int longseach = 100;
int maxKeep = 1000;
float fmaxKeep = (float) maxKeep;
int maxBucketDepth = (int) 1e5;
long seed = 5310431327l;
long t1 = System.currentTimeMillis();
liveSample(totalLength, longseach, seed, maxKeep, maxBucketDepth * 10);
long t2 = System.currentTimeMillis();
System.out.println("Time for live sampling: " + (t2 - t1) + " mSec");
long t3 = System.currentTimeMillis();
downSample(totalLength, longseach, seed, maxKeep, maxBucketDepth);
long t4 = System.currentTimeMillis();
System.out.println("Time for down sampling: " + (t4 - t3) + " mSec");
}
// NOTE: The active tests in this class have been moved to AlignmentDataManagerTest.
@Test
public void nullTest() {
assert(true == true);
}
/**
* Test that our live sample gives a uniform distribution
*/
@Ignore
public void testLiveSample() throws Exception {
int totalLength = (int) 1e4;
//Store the number of times each index is sampled
int[] counts = new int[totalLength];
List<long[]> samples;
int longseach = 1;
long seed = 212338399;
Random rand = new Random(seed);
int maxKeep = 1000;
int maxBucketDepth = Integer.MAX_VALUE;
int trials = 10000;
for (int _ = 0; _ < trials; _++) {
seed = rand.nextLong();
samples = liveSample(totalLength, longseach, seed, maxKeep, maxBucketDepth);
for (long[] dat : samples) {
counts[(int) dat[0]] += 1;
}
}
float avgFreq = ((float) maxKeep) / totalLength;
int avgCount = (int) (avgFreq * trials);
double stdDev = Math.sqrt(trials / 12);
int numStds = 4;
int ind = 0;
//System.out.println("Expected number of times sampled: " + avgCount + ". Stdev " + stdDev);
for (int cnt : counts) {
//System.out.println("ind: " + ind + " cnt: " + cnt);
assertTrue("Index " + ind + " outside of expected sampling range at " + cnt, Math.abs(cnt - avgCount) < numStds * stdDev);
ind++;
}
}
private static List<long[]> liveSample(long totalLength, int longseach, long seed, int maxKeep, int maxBucketDepth) {
List<long[]> liveSampled = new ArrayList<long[]>(maxKeep);
float fmaxKeep = (float) maxKeep;
RandDataIterator iter1 = new RandDataIterator(totalLength, longseach);
float prob = 0;
Random rand = new Random(seed);
int numAfterMax = 1;
for (long[] data : iter1) {
if (liveSampled.size() < maxKeep) {
liveSampled.add(data);
} else if (liveSampled.size() > maxBucketDepth) {
break;
} else {
//Calculate whether to accept this element
prob = fmaxKeep / (maxKeep + numAfterMax);
numAfterMax += 1;
boolean keep = rand.nextFloat() < prob;
if (keep) {
//Choose one to replace
int torep = rand.nextInt(maxKeep);
liveSampled.remove(torep);
liveSampled.add(data);
}
}
}
return liveSampled;
}
private static List<long[]> downSample(long totalLength, int longseach, long seed, int maxKeep, int maxBucketDepth) {
List<long[]> downSampled = new ArrayList<long[]>(maxKeep);
RandDataIterator iter2 = new RandDataIterator(totalLength, longseach);
Random rand = new Random(seed);
for (long[] data : iter2) {
if (downSampled.size() < maxBucketDepth) {
downSampled.add(data);
} else {
break;
}
}
//Actual downsampling
while (downSampled.size() > maxKeep) {
downSampled.remove(rand.nextInt(downSampled.size()));
}
return downSampled;
}
/**
* Iterator over garbage data.
*/
private static class RandDataIterator implements Iterable<long[]>, Iterator<long[]> {
private long counter;
private long length;
private int longseach;
/**
* @param length Number of elements that this iterator will have
* @param longseach how large each element will be (byte array)
*/
public RandDataIterator(long length, int longseach) {
this.length = length;
this.longseach = longseach;
}
public boolean hasNext() {
return counter < length;
}
public long[] next() {
if (!hasNext()) {
return null;
}
long[] arr = new long[longseach];
Arrays.fill(arr, counter);
counter++;
return arr;
}
public void remove() {
throw new UnsupportedOperationException("Can't remove");
}
public Iterator<long[]> iterator() {
return this;
}
}
}
|
package org.voltdb.planner;
import org.voltdb.plannodes.AbstractPlanNode;
import org.voltdb.types.PlanNodeType;
public class TestPlansOrderBy extends PlannerTestCase {
@Override
protected void setUp() throws Exception {
setupSchema(TestPlansGroupBy.class.getResource("testplans-orderby-ddl.sql"),
"testplansorderby", false);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
private void validatePlan(String sql, boolean expectIndexScan,
boolean expectSeqScan, boolean expectOrderBy)
{
validatePlan(sql, expectIndexScan, expectSeqScan, expectOrderBy, false, false);
}
private void validatePlan(String sql, boolean expectIndexScan,
boolean expectSeqScan, boolean expectOrderBy, boolean expectHashAggregate,
boolean expectedAggregate)
{
AbstractPlanNode pn = compile(sql);
//* to debug */ System.out.println(pn.getChild(0).toJSONString());
//* to debug */ System.out.println(pn.getChild(0).toExplainPlanString());
assertEquals(expectIndexScan, pn.hasAnyNodeOfType(PlanNodeType.INDEXSCAN));
assertEquals(expectSeqScan, pn.hasAnyNodeOfType(PlanNodeType.SEQSCAN));
assertEquals(expectOrderBy, pn.hasAnyNodeOfType(PlanNodeType.ORDERBY));
assertEquals(expectHashAggregate, pn.hasAnyNodeOfType(PlanNodeType.HASHAGGREGATE));
assertEquals(expectedAggregate, pn.hasAnyNodeOfType(PlanNodeType.AGGREGATE));
}
/// Validate that a plan uses the full bag of tricks
/// -- that it uses an index scan but no seq scan, order by, or hash aggregate.
private void validateOptimalPlan(String sql)
{
validatePlan(sql, true, false, false);
}
/// Validate that a plan does not unintentionally use
/// a completely inapplicable index scan for order.
private void validateBruteForcePlan(String sql)
{
validatePlan(sql, false, true, true);
}
/// Validate that a plan does not unintentionally use
/// a completely inapplicable index scan for order,
/// when it still uses an index scan for non-determinism.
/// This arguably should not happen for plans where the final
/// sort already confers determinism (yet it currently does)?.
private void validateIndexedBruteForcePlan(String sql)
{
validatePlan(sql, true, false, true);
}
public void testOrderByOneOfTwoIndexKeys()
{
validateOptimalPlan("SELECT * from T ORDER BY T_D0");
validateOptimalPlan("SELECT * from T WHERE T_D0 = 1 ORDER BY T_D1");
}
public void testOrderByIndexedColumns() {
validateOptimalPlan("SELECT * from T ORDER BY T_D0, T_D1");
validateOptimalPlan("SELECT * from Tmanykeys ORDER BY T_D0, T_D1, T_D2");
}
public void testOrderByTwoDesc() {
validateOptimalPlan("SELECT * from T ORDER BY T_D0 DESC, T_D1 DESC");
}
public void testOrderByTwoAscDesc() {
validateBruteForcePlan("SELECT * from T ORDER BY T_D0, T_D1 DESC");
validateBruteForcePlan("SELECT * from Tnokey ORDER BY T_D0, T_D1 DESC");
}
public void testOrderByTwoOfThreeIndexKeys()
{
validateOptimalPlan("SELECT * from Tmanykeys WHERE T_D0 = ? ORDER BY T_D1, T_D2");
validateOptimalPlan("SELECT * from Tmanykeys WHERE T_D1 = ? ORDER BY T_D0, T_D2");
validateOptimalPlan("SELECT * from Tmanykeys WHERE T_D2 = ? ORDER BY T_D0, T_D1");
validateOptimalPlan("SELECT * from Tmanykeys ORDER BY T_D0, T_D1");
validateIndexedBruteForcePlan("SELECT * FROM Tmanykeys WHERE T_D0 <= ? ORDER BY T_D1, T_D2");
validateIndexedBruteForcePlan("SELECT * FROM Tmanykeys WHERE T_D0 <= ? ORDER BY T_D1 DESC, T_D2 DESC");
}
public void testOrderByOneOfThreeIndexKeys()
{
validateOptimalPlan("SELECT * from Tmanykeys WHERE T_D0 = ? AND T_D1 = ? ORDER BY T_D2");
validateOptimalPlan("SELECT * from Tmanykeys WHERE T_D1 = ? AND T_D2 = ? ORDER BY T_D0");
validateOptimalPlan("SELECT * from Tmanykeys WHERE T_D2 = ? AND T_D0 = ? ORDER BY T_D1");
validateOptimalPlan("SELECT * from Tmanykeys WHERE T_D0 = ? ORDER BY T_D1");
validateOptimalPlan("SELECT * from Tmanykeys WHERE T_D1 = ? ORDER BY T_D0");
validateOptimalPlan("SELECT * from Tmanykeys WHERE T_D2 = ? ORDER BY T_D0");
validateOptimalPlan("SELECT * from Tmanykeys ORDER BY T_D0");
validateIndexedBruteForcePlan("SELECT * FROM Tmanykeys WHERE T_D0 = ? AND T_D1 < ? ORDER BY T_D2");
validateIndexedBruteForcePlan("SELECT * FROM Tmanykeys WHERE T_D0 = ? AND T_D1 < ? ORDER BY T_D2 DESC");
validateIndexedBruteForcePlan("SELECT * FROM Tmanykeys WHERE T_D0 = ? ORDER BY T_D2");
validateIndexedBruteForcePlan("SELECT * FROM Tmanykeys WHERE T_D0 = ? ORDER BY T_D2 DESC");
}
public void testOrderByWrongPermutation()
{
// Order determinism, so do not make it worse by using index scan.
validateBruteForcePlan("SELECT * from Tmanykeys ORDER BY T_D2, T_D1, T_D0");
validateBruteForcePlan("SELECT * from Tmanykeys ORDER BY T_D2, T_D0, T_D1");
validateBruteForcePlan("SELECT * from Tmanykeys ORDER BY T_D1, T_D0, T_D2");
validateBruteForcePlan("SELECT * from Tmanykeys ORDER BY T_D1, T_D2, T_D0");
validateBruteForcePlan("SELECT * from Tmanykeys ORDER BY T_D0, T_D2, T_D1");
// Use index for filter.
validateIndexedBruteForcePlan("SELECT * from Tmanykeys WHERE T_D0 = ? ORDER BY T_D2, T_D1");
validateIndexedBruteForcePlan("SELECT * from Tmanykeys WHERE T_D1 = ? ORDER BY T_D2, T_D0");
}
public void testOrderByTooManyToIndex()
{
validateBruteForcePlan("SELECT * from T ORDER BY T_D0, T_D1, T_D2");
validateBruteForcePlan("SELECT * from Tnokey ORDER BY T_D0, T_D1, T_D2");
}
public void testOrderByTooMany()
{
validateBruteForcePlan("SELECT * from Tnokey ORDER BY T_D0, T_D1, T_D2");
validateBruteForcePlan("SELECT * from T ORDER BY T_D0, T_D1, T_D2");
}
public void testNoIndexToOrderBy() {
validateIndexedBruteForcePlan("SELECT * FROM T ORDER BY T_D2");
validateBruteForcePlan("SELECT * FROM Tnokey ORDER BY T_D2");
validateIndexedBruteForcePlan("SELECT * FROM Tmanykeys ORDER BY T_D2");
}
public void testOrderByNLIJ()
{
validatePlan("SELECT Tnokey.T_D1, T.T_D0, T.T_D1 from Tnokey, T " +
"where Tnokey.T_D2 = 2 AND T.T_D0 = Tnokey.T_D0 " +
"ORDER BY T.T_D0, T.T_D1", true, true, true);
}
public void testTableAgg() {
validatePlan("SELECT SUM(T_D0) from T", false, true, false, false, true);
validatePlan("SELECT SUM(T_D0), COUNT(*), AVG(T_D1) from T", false, true, false, false, true);
validatePlan("SELECT SUM(T_D0) from T ORDER BY T_D0, T_D1",
false, true, false, false, true);
validatePlan("SELECT SUM(T_D0), COUNT(*), AVG(T_D1) from T ORDER BY T_D0, T_D1",
false, true, false, false, true);
}
public void testOrderByCountStar() {
validatePlan("SELECT T_D0, COUNT(*) AS FOO FROM T GROUP BY T_D0 ORDER BY FOO", true, false, true, false, true);
validatePlan("SELECT T_D0, COUNT(*) AS FOO FROM Tnokey GROUP BY T_D0 ORDER BY FOO", false, true, true, true, false);
}
public void testOrderByAggWithoutAlias() {
validatePlan("SELECT T_D0, SUM(T_D1) FROM T GROUP BY T_D0 ORDER BY SUM(T_D1)",
true, false, true, false, true);
validatePlan("SELECT T_D0, COUNT(*) FROM T GROUP BY T_D0 ORDER BY COUNT(*)",
true, false, true, false, true);
validatePlan("SELECT T_D0, AVG(T_D1) FROM T GROUP BY T_D0 ORDER BY AVG(T_D1)",
true, false, true, false, true);
validatePlan("SELECT T_D0, COUNT(T_D1) FROM T GROUP BY T_D0 ORDER BY COUNT(T_D1)",
true, false, true, false, true);
validatePlan("SELECT T_D0, MIN(T_D1) FROM T GROUP BY T_D0 ORDER BY MIN(T_D1)",
true, false, true, false, true);
validatePlan("SELECT T_D0, MAX(T_D1) FROM T GROUP BY T_D0 ORDER BY MAX(T_D1)",
true, false, true, false, true);
// Complex aggregation
validatePlan("SELECT T_D0, COUNT(*)+1 FROM T GROUP BY T_D0 ORDER BY COUNT(*)+1",
true, false, true, false, true);
validatePlan("SELECT T_D0, abs(MAX(T_D1)) FROM T GROUP BY T_D0 ORDER BY abs(MAX(T_D1))",
true, false, true, false, true);
}
public void testEng450()
{
// This used to not compile. It does now. That's all we care about.
compile("select T.T_D0, " +
"sum(T.T_D1) " +
"from T " +
"group by T.T_D0 " +
"order by T.T_D0;");
}
public void testOrderDescWithEquality() {
validateOptimalPlan("SELECT * FROM T WHERE T_D0 = 2 ORDER BY T_D1");
// See ENG-5084 to optimize this query to use inverse scan in future.
validateIndexedBruteForcePlan("SELECT * FROM T WHERE T_D0 = 2 ORDER BY T_D1 DESC");
//validateOptimalPlan("SELECT * FROM T WHERE T_D0 = 2 ORDER BY T_D1 DESC");
}
// Indexes on T (T_D0, T_D1), T2 (T_D0, T_D1), and Tmanykeys (T_D0, T_D1, T_D2)
// no index on Tnokey and Tnokey2
public void testENG4676() {
// single column ORDER BY
// ORDER BY on indexed key ascending, JOIN on indexed key from one table and
// unindexed key from the other table -> no ORDER BY node
validateOptimalPlan("SELECT * FROM T, Tmanykeys WHERE Tmanykeys.T_D0 = T.T_D2 " +
"ORDER BY T.T_D0 LIMIT ?");
// ORDER BY on indexed key descending, JOIN on indexed key from one table
// and unindexed key from the other table -> no ORDER BY node
validateOptimalPlan("SELECT * FROM T, Tmanykeys WHERE Tmanykeys.T_D0 = T.T_D2 " +
"ORDER BY T.T_D0 DESC LIMIT ?");
// multiple columns ORDER BY
// ORDER BY on indexed key ascending, JOIN on indexed key from one table and
// unindexed key from the other table -> no ORDER BY node
validateOptimalPlan("SELECT * FROM T, Tmanykeys WHERE Tmanykeys.T_D0 = T.T_D2 " +
"ORDER BY T.T_D0, T.T_D1 LIMIT ?");
// ORDER BY on indexed key descending, JOIN on indexed key from one table and
// unindexed key from the other table -> no ORDER BY node
validateOptimalPlan("SELECT * FROM T, Tmanykeys WHERE Tmanykeys.T_D0 = T.T_D2 " +
"ORDER BY T.T_D0 DESC, T.T_D1 DESC LIMIT ?");
// filter on indexed column on one table, prefix join constraint,
// ORDER BY looking for 1 recovered spoiler -> no ORDER BY node
validateOptimalPlan("SELECT * FROM T, Tmanykeys WHERE Tmanykeys.T_D0 = T.T_D2 AND Tmanykeys.T_D0 = ? " +
"ORDER BY Tmanykeys.T_D1 LIMIT ?");
// This query requires additional recognition of transitive equality to eliminate the ORDER BY.
// See ENG-4728.
//*See ENG-4728.*/ validateOptimalPlan("SELECT * FROM T, Tmanykeys WHERE Tmanykeys.T_D0 = T.T_D2 AND T.T_D2 = ? " +
//*See ENG-4728.*/ "ORDER BY Tmanykeys.T_D1 LIMIT ?");
// ORDER BY is not recovered, but index is chosen for sorting purpose --> no ORDER BY node
validateOptimalPlan("SELECT * FROM T, Tmanykeys WHERE Tmanykeys.T_D1 = T.T_D2 AND T.T_D0 = ? " +
"ORDER BY Tmanykeys.T_D0 LIMIT ?");
// test NLJ --> need ORDER BY node
validateBruteForcePlan("SELECT * FROM Tnokey, Tnokey2 WHERE Tnokey.T_D0 = Tnokey2.T_D0 " +
"ORDER BY Tnokey.T_D1 LIMIT ?");
// test nested NLIJ
validateIndexedBruteForcePlan("SELECT * FROM T, T2, Tmanykeys " +
"WHERE T.T_D0 = T2.T_D0 AND T2.T_D1 = Tmanykeys.T_D0 ORDER BY Tmanykeys.T_D1 LIMIT ?");
validateIndexedBruteForcePlan("SELECT * FROM T, T2, Tmanykeys " +
"WHERE T.T_D0 = T2.T_D0 AND T2.T_D1 = Tmanykeys.T_D0 ORDER BY T.T_D1 LIMIT ?");
validateIndexedBruteForcePlan("SELECT * FROM T, T2, Tmanykeys " +
"WHERE T.T_D0 = T2.T_D0 AND T2.T_D1 = Tmanykeys.T_D0 ORDER BY T2.T_D1 LIMIT ?");
validateOptimalPlan("SELECT * FROM T, T2, Tmanykeys " +
"WHERE T.T_D0 = T2.T_D0 AND T2.T_D1 = Tmanykeys.T_D0 ORDER BY T.T_D0, T.T_D1 LIMIT ?");
}
}
|
package cx2x;
import cx2x.decompiler.XcmlBackend;
import cx2x.translator.ClawTranslatorDriver;
import cx2x.translator.config.Configuration;
import cx2x.translator.language.helper.accelerator.AcceleratorDirective;
import cx2x.translator.language.helper.target.Target;
import cx2x.translator.report.ClawTransformationReport;
import exc.xcodeml.XcodeMLtools_Fmod;
import org.apache.commons.cli.*;
import xcodeml.util.XmOption;
import java.io.File;
/**
* Cx2x is the entry point of any CLAW XcodeML/F translation.
*
* @author clementval
*/
public class Cx2x {
/**
* Print an error message an abort.
*
* @param filename Filename in which error occurred.
* @param lineNumber Line number of the error, if known.
* @param charPos Character position of the error, if known.
* @param msg Error message.
*/
private static void error(String filename, int lineNumber,
int charPos, String msg)
{
System.err.println(String.format("%s:%d:%d error: %s",
filename, lineNumber, charPos, msg));
System.exit(1);
}
/**
* Print program usage.
*/
private static void usage() {
Options options = prepareOptions();
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("clawfc", options);
System.exit(1);
}
/**
* List all accelerator target available for code generation.
*/
private static void listTarget() {
System.out.println("- CLAW available targets -");
for(String t : Target.availableTargets()) {
System.out.println(" - " + t);
}
}
/**
* List all accelerator directive language available for code generation.
*/
private static void listDirectiveLanguage() {
System.out.println("- CLAW accelerator directive language -");
for(String d : AcceleratorDirective.availableDirectiveLanguage()) {
System.out.println(" - " + d);
}
}
/**
* Prepare the set of available options.
*
* @return Options object.
*/
private static Options prepareOptions() {
Options options = new Options();
options.addOption("h", "help", false, "display program usage.");
options.addOption("l", false, "suppress line directive in decompiled code.");
options.addOption("cp", "config-path", true, "specify the configuration directory");
options.addOption("c", "config", true, "specify the configuration for the translator.");
options.addOption("s", "schema", true, "specify the XSD schema location to validate the configuration.");
options.addOption("t", "target", true, "specify the target for the code transformation.");
options.addOption("dir", "directive", true, "list all accelerator directive language available for code generation.");
options.addOption("d", "debug", false, "enable output debug message.");
options.addOption("f", true, "specify FORTRAN decompiled output file.");
options.addOption("w", true, "number of character per line in decompiled code.");
options.addOption("o", true, "specify XcodeML/F output file.");
options.addOption("M", true, "specify where to search for .xmod files");
options.addOption("tl", "target-list", false, "list all target available for code transformation.");
options.addOption("dl", "directive-list", false, "list all available directive language to be generated.");
options.addOption("sc", "show-config", false, "display the current configuration.");
options.addOption("fp", "force-pure", false, "exit the translator if a PURE subroutine/function has to be transformed.");
options.addOption("r", "report", true, "generate the transformation report.");
return options;
}
/**
* Parse the arguments passed to the program.
*
* @param args Arguments passed to the program.
* @return Parsed command line object.
* @throws ParseException If one or several arguments are not found.
*/
private static CommandLine processCommandArgs(String[] args)
throws ParseException
{
Options options = prepareOptions();
CommandLineParser parser = new DefaultParser();
return parser.parse(options, args);
}
/**
* Main point of entry of the program.
*
* @param args Arguments of the program.
* @throws Exception if translation failed.
*/
public static void main(String[] args) throws Exception {
String input;
String xcmlOuput = null;
String targetLangOutput = null;
String target_option = null;
String directive_option = null;
String configuration_file = null;
String configuration_path = null;
int maxColumns = 0;
boolean forcePure = false;
CommandLine cmd;
try {
cmd = processCommandArgs(args);
} catch(ParseException pex) {
error("internal", 0, 0, pex.getMessage());
return;
}
// Help option
if(cmd.hasOption("h")) {
usage();
return;
}
// Display target list option
if(cmd.hasOption("tl")) {
listTarget();
return;
}
// Display directive list option
if(cmd.hasOption("dl")) {
listDirectiveLanguage();
return;
}
// Target option
if(cmd.hasOption("t")) {
target_option = cmd.getOptionValue("t");
}
// Directive option
if(cmd.hasOption("dir")) {
directive_option = cmd.getOptionValue("dir");
}
// Suppressing line directive option
if(cmd.hasOption("l")) {
XmOption.setIsSuppressLineDirective(true);
}
// Debug option
if(cmd.hasOption("d")) {
XmOption.setDebugOutput(true);
}
// XcodeML/F output file option
if(cmd.hasOption("o")) {
xcmlOuput = cmd.getOptionValue("o");
}
// FORTRAN output file option
if(cmd.hasOption("f")) {
targetLangOutput = cmd.getOptionValue("f");
}
if(cmd.hasOption("w")) {
maxColumns = Integer.parseInt(cmd.getOptionValue("w"));
}
if(cmd.hasOption("c")) {
configuration_file = cmd.getOptionValue("c");
}
if(cmd.hasOption("cp")) {
configuration_path = cmd.getOptionValue("cp");
}
// Check that configuration path exists
if(configuration_path == null) {
error("internal", 0, 0, "Configuration path missing.");
return;
}
// Check that configuration file exists
if(configuration_file != null) {
File configFile = new File(configuration_file);
if(!configFile.exists()) {
error("internal", 0, 0, "Configuration file not found. "
+ configuration_path);
}
}
// --show-config option
if(cmd.hasOption("sc")) {
Configuration config =
new Configuration(configuration_path, configuration_file);
config.displayConfig();
return;
}
if(cmd.getArgs().length == 0) {
error("internal", 0, 0, "no input file");
return;
} else {
input = cmd.getArgs()[0];
}
// Module search path options
if(cmd.hasOption("M")) {
for(String value : cmd.getOptionValues("M")) {
XcodeMLtools_Fmod.addSearchPath(value);
}
}
// Read the configuration file
Configuration config;
try {
config = new Configuration(configuration_path, configuration_file);
config.setUserDefinedTarget(target_option);
config.setUserDefineDirective(directive_option);
config.setMaxColumns(maxColumns);
} catch(Exception ex) {
error("internal", 0, 0, ex.getMessage());
return;
}
// Force pure option
if(cmd.hasOption("fp")) {
config.setForcePure();
}
// Call the translator driver to apply transformation on XcodeML/F
ClawTranslatorDriver translatorDriver =
new ClawTranslatorDriver(input, xcmlOuput, config);
translatorDriver.analyze();
translatorDriver.transform();
translatorDriver.flush(config);
// Produce report
if(cmd.hasOption("r")) {
ClawTransformationReport report =
new ClawTransformationReport(cmd.getOptionValue("r"));
report.generate(config, args, translatorDriver);
}
// Decompile XcodeML/F to Fortran
XcmlBackend decompiler = new XcmlBackend(XcmlBackend.Lang.FORTRAN);
if(!decompiler.decompile(targetLangOutput, xcmlOuput, maxColumns,
XmOption.isSuppressLineDirective()))
{
error(xcmlOuput, 0, 0, "Unable to decompile XcodeML to target language");
System.exit(1);
}
}
}
|
package com.db.upnp.client;
import com.db.net.http.HttpWebClient;
import com.db.net.http.HttpWebConnection;
import com.db.net.http.HttpWebRequest;
import com.db.net.http.HttpWebResponse;
import com.db.net.soap.RpcSoapEnvelope;
import com.db.net.soap.SoapOperation;
import com.db.upnp.device.UPnPRootDevice;
import com.db.upnp.service.UPnPService;
/**
* A UPnPServiceClient is a client that communicates with a UPnPDevice by
* using its UPnPServices.
*
* @author Dave Longley
*/
public class UPnPServiceClient
{
/**
* The UPnPRootDevice this client is for.
*/
protected UPnPRootDevice mRootDevice;
/**
* Creates a new UPnPServiceClient for the specified UPnPService.
*
* @param rootDevice the UPnPRootDevice this client is for.
*/
public UPnPServiceClient(UPnPRootDevice rootDevice)
{
// set the root device
mRootDevice = rootDevice;
}
/**
* Sends the passed SoapEnvelope to the passed UPnPService and returns the
* HTTP response code. The passed envelope will be updated if the server
* responds with its own envelope.
*
* @param envelope the SoapEnvelope to send.
* @param service the UPnPService to send the envelope to.
*
* @return true if a connection was made to the service, false if not.
*/
public boolean sendSoapEnvelope(
RpcSoapEnvelope envelope, UPnPService service)
{
boolean rval = false;
// get the url for the service --
// use the base URL for the root device
String url = mRootDevice.getDescription().getBaseUrl();
if(url.equals(""))
{
// use the control URL for the service
url = service.getControlUrl();
}
// get an http web connection
HttpWebClient client = new HttpWebClient();
HttpWebConnection connection = (HttpWebConnection)client.connect(url);
if(connection != null)
{
rval = true;
// get the xml for the envelope
String xml = envelope.convertToXml(true, 0, 0);
// get the operation from the envelope
SoapOperation operation = envelope.getSoapOperation();
// set the soap action
String soapAction =
"\"" + service.getServiceType() + "#" + operation.getName() + "\"";
// create an HTTP request
HttpWebRequest request = new HttpWebRequest(connection);
request.getHeader().setVersion("HTTP/1.1");
request.getHeader().setMethod("POST");
request.getHeader().setPath(service.getControlUrl());
request.getHeader().setHost(connection.getRemoteHost());
request.getHeader().setContentLength(xml.length());
request.getHeader().setContentType("text/xml; charset=\"utf-8\"");
request.getHeader().addHeader("SOAPACTION", soapAction);
request.getHeader().setConnection("close");
// send the request header
if(request.sendHeader())
{
// send the request body
request.sendBody(xml);
// create a response
HttpWebResponse response = request.createHttpWebResponse();
// receive the response header
if(response.receiveHeader())
{
// receive the body, if any
if(response.getHeader().getContentLength() > 0)
{
xml = response.receiveBodyString();
if(xml != null)
{
// convert the rpc soap envelope from the received xml
envelope.convertFromXml(xml);
}
}
}
}
// disconnect the connection
connection.disconnect();
}
return rval;
}
}
|
package org.nick.wwwjdic;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import android.util.Log;
public class SentenceBreakdownTask extends SearchTask<SentenceBreakdownEntry> {
private static final Pattern SENTENCE_PART_PATTERN = Pattern.compile(
"^.*<font color=\"\\S+\">\\S+</font>.*<br>$",
Pattern.CASE_INSENSITIVE);
private static final Pattern INFLECTED_FORM_PATTERN = Pattern.compile(
"<font color=\"\\S+\">(\\S+)</font>", Pattern.CASE_INSENSITIVE);
private static final Pattern ENTRY_WITH_EXPLANATION_PATTERN = Pattern
.compile("^.*<li>\\s*(.+)<br>\\s*(.+)\\s(.+)\\s+(.+)</li>.*$");
private static final Pattern ENTRY_PATTERN = Pattern
.compile("^.*<li>\\s*(.+)\\s(.+)\\s+(.+)\\s+(<font.*>(.+)</font>)?</li>.*$");
private static final Pattern NO_READING_ENTRY_PATTERN = Pattern
.compile("^.*<li>\\s*(\\S+)\\s+(.+)\\s+(<font.*>(.+)</font>)?</li>.*$");
private static final Pattern BR_PATTERN = Pattern.compile("^<br>$");
public SentenceBreakdownTask(String url, int timeoutSeconds,
ResultListViewBase<SentenceBreakdownEntry> resultListView,
WwwjdicQuery query) {
super(url, timeoutSeconds, resultListView, query);
}
@Override
protected List<SentenceBreakdownEntry> parseResult(String html) {
List<SentenceBreakdownEntry> result = new ArrayList<SentenceBreakdownEntry>();
List<String> inflectedForms = new ArrayList<String>();
String[] lines = html.split("\n");
boolean exampleFollows = false;
int wordIdx = 0;
for (String line : lines) {
Matcher m = BR_PATTERN.matcher(line);
if (m.matches()) {
exampleFollows = true;
continue;
}
if (exampleFollows) {
m = INFLECTED_FORM_PATTERN.matcher(line);
while (m.find()) {
inflectedForms.add(m.group(1));
}
exampleFollows = false;
continue;
}
m = SENTENCE_PART_PATTERN.matcher(line);
if (m.matches()) {
m = INFLECTED_FORM_PATTERN.matcher(line);
while (m.find()) {
inflectedForms.add(m.group(1));
}
continue;
}
m = ENTRY_WITH_EXPLANATION_PATTERN.matcher(line);
if (m.matches()) {
String explanation = m.group(1).trim();
String word = m.group(2).trim();
String reading = m.group(3).trim();
String translation = m.group(4).trim();
SentenceBreakdownEntry entry = SentenceBreakdownEntry
.createWithExplanation(inflectedForms.get(wordIdx),
word, reading, translation, explanation);
result.add(entry);
wordIdx++;
continue;
}
m = ENTRY_PATTERN.matcher(line);
if (m.matches()) {
String word = m.group(1).trim();
String reading = m.group(2).trim();
String translation = m.group(3).trim();
SentenceBreakdownEntry entry = null;
if (m.groupCount() > 4 && m.group(5) != null) {
String explanation = m.group(5).trim();
entry = SentenceBreakdownEntry.createWithExplanation(
inflectedForms.get(wordIdx), word, reading,
translation, explanation);
} else {
entry = SentenceBreakdownEntry.create(
inflectedForms.get(wordIdx), word, reading,
translation);
}
result.add(entry);
wordIdx++;
continue;
}
m = NO_READING_ENTRY_PATTERN.matcher(line);
if (m.matches()) {
String word = m.group(1).trim();
String translation = m.group(2).trim();
SentenceBreakdownEntry entry = null;
if (m.groupCount() > 3 && m.group(4) != null) {
String explanation = m.group(4).trim();
entry = SentenceBreakdownEntry.createWithExplanation(
inflectedForms.get(wordIdx), word, null,
translation, explanation);
} else {
entry = SentenceBreakdownEntry.createNoReading(
inflectedForms.get(wordIdx), word, translation);
}
result.add(entry);
wordIdx++;
continue;
}
}
return result;
}
@Override
protected String query(WwwjdicQuery query) {
try {
String lookupUrl = String.format("%s?%s", url,
generateBackdoorCode(query));
HttpGet get = new HttpGet(lookupUrl);
String responseStr = httpclient.execute(get, responseHandler,
localContext);
return responseStr;
} catch (ClientProtocolException cpe) {
Log.e("WWWJDIC", "ClientProtocolException", cpe);
throw new RuntimeException(cpe);
} catch (IOException e) {
Log.e("WWWJDIC", "IOException", e);
throw new RuntimeException(e);
}
}
private String generateBackdoorCode(WwwjdicQuery query) {
StringBuffer buff = new StringBuffer();
// raw
buff.append("9ZIG");
try {
buff.append(URLEncoder.encode(query.getQueryString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return buff.toString();
}
}
|
package com.box.boxjavalibv2;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.NotImplementedException;
import com.box.boxjavalibv2.BoxConnectionManagerBuilder.BoxConnectionManager;
import com.box.boxjavalibv2.authorization.IAuthDataController;
import com.box.boxjavalibv2.authorization.IAuthEvent;
import com.box.boxjavalibv2.authorization.IAuthFlowListener;
import com.box.boxjavalibv2.authorization.IAuthFlowMessage;
import com.box.boxjavalibv2.authorization.IAuthFlowUI;
import com.box.boxjavalibv2.authorization.IAuthSecureStorage;
import com.box.boxjavalibv2.authorization.OAuthAuthorization;
import com.box.boxjavalibv2.authorization.OAuthDataController;
import com.box.boxjavalibv2.authorization.OAuthDataController.OAuthTokenState;
import com.box.boxjavalibv2.authorization.OAuthRefreshListener;
import com.box.boxjavalibv2.authorization.SharedLinkAuthorization;
import com.box.boxjavalibv2.dao.BoxBase;
import com.box.boxjavalibv2.dao.BoxOAuthToken;
import com.box.boxjavalibv2.dao.BoxResourceType;
import com.box.boxjavalibv2.dao.IAuthData;
import com.box.boxjavalibv2.events.OAuthEvent;
import com.box.boxjavalibv2.exceptions.AuthFatalFailureException;
import com.box.boxjavalibv2.jsonparsing.BoxJSONParser;
import com.box.boxjavalibv2.jsonparsing.BoxResourceHub;
import com.box.boxjavalibv2.jsonparsing.IBoxJSONParser;
import com.box.boxjavalibv2.jsonparsing.IBoxResourceHub;
import com.box.boxjavalibv2.resourcemanagers.BoxCollaborationsManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxCommentsManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxEventsManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxFilesManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxFoldersManageImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxGroupsManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxItemsManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxOAuthManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxSearchManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxSharedItemsManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxTrashManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.BoxUsersManagerImpl;
import com.box.boxjavalibv2.resourcemanagers.IBoxCollaborationsManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxCommentsManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxEventsManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxFilesManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxFoldersManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxGroupsManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxItemsManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxOAuthManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxResourceManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxSearchManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxSharedItemsManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxTrashManager;
import com.box.boxjavalibv2.resourcemanagers.IBoxUsersManager;
import com.box.boxjavalibv2.resourcemanagers.IPluginResourceManagerBuilder;
import com.box.restclientv2.IBoxRESTClient;
import com.box.restclientv2.authorization.IBoxRequestAuth;
public class BoxClient extends BoxBase implements IAuthFlowListener {
private final static boolean DEFAULT_AUTO_REFRESH = true;
private final IAuthDataController authController;
private final IBoxRequestAuth auth;
private final IBoxResourceHub resourceHub;
private final IBoxJSONParser jsonParser;
private final IBoxRESTClient restClient;
private final IBoxConfig config;
private final IBoxFilesManager filesManager;
private final IBoxFoldersManager foldersManager;
private final IBoxItemsManager boxItemsManager;
private final IBoxSearchManager searchManager;
private final IBoxEventsManager eventsManager;
private final IBoxCollaborationsManager collaborationsManager;
private final IBoxCommentsManager commentsManager;
private final IBoxUsersManager usersManager;
private final IBoxOAuthManager oauthManager;
private final IBoxGroupsManager groupsManager;
private final IBoxTrashManager trashManager;
private IAuthFlowListener mAuthListener;
private final Map<String, IBoxResourceManager> pluginResourceManagers = new HashMap<String, IBoxResourceManager>();
/**
* This constructor has some connection parameters. They are used to periodically close idle connections that HttpClient opens.
*
* @param clientId
* client id, you can get it from dev console.
* @param clientSecret
* client secret, you can get it from dev console.
* @param hub
* resource hub. use null if you want to use default one.
* @param parser
* json parser, use null if you want to use default one(Jackson).
* @param config
* BoxConfig. User BoxConfigBuilder to build. Normally you only need default config: (new BoxConfigBuilder()).build()
* @param connectionManager
* BoxConnectionManager. Normally you only need default connection manager: (new BoxConnectionManagerBuilder()).build()
*/
public BoxClient(final String clientId, final String clientSecret, final IBoxResourceHub hub, final IBoxJSONParser parser, final IBoxConfig config,
final BoxConnectionManager connectionManager) {
this(clientId, clientSecret, hub, parser, createMonitoredRestClient(connectionManager), config);
}
/**
* @param clientId
* client id
* @param clientSecret
* client secret
* @param hub
* resource hub, use null for default resource hub.
* @param parser
* json parser, use null for default parser.
* @param config
* BoxConfig. User BoxConfigBuilder to build. Normally you only need default config: (new BoxConfigBuilder()).build()
*/
public BoxClient(final String clientId, final String clientSecret, final IBoxResourceHub hub, final IBoxJSONParser parser, final IBoxConfig config) {
this(clientId, clientSecret, hub, parser, createRestClient(), config);
}
/**
* @param clientId
* client id
* @param clientSecret
* client secret
* @param hub
* resource hub, use null for default resource hub.
* @param parser
* json parser, use null for default parser.
* @param restClient
* rest client
* @param config
* BoxConfig. User BoxConfigBuilder to build. Normally you only need default config: (new BoxConfigBuilder()).build()
*/
public BoxClient(final String clientId, final String clientSecret, final IBoxResourceHub hub, final IBoxJSONParser parser, final IBoxRESTClient restClient,
final IBoxConfig config) {
this.resourceHub = hub == null ? createResourceHub() : hub;
this.jsonParser = parser == null ? createJSONParser(resourceHub) : parser;
this.restClient = restClient;
this.config = config == null ? (new BoxConfigBuilder()).build() : config;
authController = createAuthDataController(clientId, clientSecret);
auth = createAuthorization(authController);
boxItemsManager = new BoxItemsManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
filesManager = new BoxFilesManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
foldersManager = new BoxFoldersManageImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
searchManager = new BoxSearchManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
eventsManager = new BoxEventsManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
collaborationsManager = new BoxCollaborationsManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
commentsManager = new BoxCommentsManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
usersManager = new BoxUsersManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
oauthManager = new BoxOAuthManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getRestClient());
groupsManager = new BoxGroupsManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
trashManager = new BoxTrashManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
}
@Deprecated
public BoxClient(final String clientId, final String clientSecret, final IBoxConfig config) {
this(clientId, clientSecret, null, null, config);
}
/**
* Plug in a resource manager into sdk client. The plugged in resource manager can be retrieved by getPluginManager(key).
*
* @param key
* key of the resource manager. The key is used to retrieve the plugged in resource manager.
* @param builder
* builder of the resource manager, the builder interface confines the base building blocks of the plugged in resource manager.
* @return The plugged in resource manager.
*/
public IBoxResourceManager pluginResourceManager(String key, IPluginResourceManagerBuilder builder) {
IBoxResourceManager manager = builder.build(getConfig(), getResourceHub(), getJSONParser(), getAuth(), getRestClient());
pluginResourceManagers.put(key, manager);
return manager;
}
/**
* Whether this client is authenticated.
*
* @return
*/
public boolean isAuthenticated() {
try {
return getOAuthDataController().getTokenState() != OAuthTokenState.FAIL && getAuthData() != null;
}
catch (AuthFatalFailureException e) {
return false;
}
}
/**
* Makes OAuth auto refresh itself when token expires. By default, this is set to true. Note if autorefresh fails, it's not going to try refresh again.
*
* @param autoRefresh
*/
public void setAutoRefreshOAuth(boolean autoRefresh) {
getOAuthDataController().setAutoRefreshOAuth(autoRefresh);
}
/**
* Set whether we want the connection to keep open (and reused) after an api call.
*
* @param connectionOpen
* true if we want the connection to remain open and reused for another api call.
*/
public void setConnectionOpen(final boolean connectionOpen) {
((BoxRESTClient) getRestClient()).setConnectionOpen(connectionOpen);
}
/**
* Set connection time out.
*
* @param timeOut
*/
public void setConnectionTimeOut(final int timeOut) {
((BoxRESTClient) getRestClient()).setConnectionTimeOut(timeOut);
}
/**
* Get the OAuthDataController that controls OAuth data.
*/
public OAuthDataController getOAuthDataController() {
return (OAuthDataController) authController;
}
/**
* Add a listener to listen to OAuth refresh events. This is important because every time OAuth token refreshes, a new refresh/access token pair will be
* generated. If your app is storing the token pairs, it needs to get rid of the stale pair store the updated pair.
*
* @param listener
*/
public void addOAuthRefreshListener(OAuthRefreshListener listener) {
getOAuthDataController().addOAuthRefreshListener(listener);
}
/**
* Get the OAuth data.
*
* @return
* @throws AuthFatalFailureException
*/
public BoxOAuthToken getAuthData() throws AuthFatalFailureException {
return getOAuthDataController().getAuthData();
}
/**
* Save auth in a customized secure storage.
*
* @param storage
* @throws AuthFatalFailureException
*/
public void saveAuth(IAuthSecureStorage storage) throws AuthFatalFailureException {
storage.saveAuth(getAuthData());
}
/**
* Authenticate from the auth object stored in the secure storage.
*
* @param storage
*/
public void authenticateFromSecureStorage(IAuthSecureStorage storage) {
authenticate(storage.getAuth());
}
/**
* Get the BoxFilesManager, which can be used to make API calls on files endpoints. Note this files manager only work on the folders you own. if you are
* trying to make api calls on a shared file (file shared to you via shared link), please use getSharedFilesManager().
*
* @return the filesManager
*/
public IBoxFilesManager getFilesManager() {
return filesManager;
}
/**
* Get the BoxItemsManager, which can be used to make API calls on files/folders endpoints. Note this files manager only work on the files/folders you own.
* if you are trying to make api calls on a shared file (file shared to you via shared link), please use getSharedBoxItemsManager(). In general this is a
* convenient resource manager when you make api calls for a BoxItem without knowing whether it's a BoxFile or BoxFolder.
*
* @return the boxItemsManager
*/
public IBoxItemsManager getBoxItemsManager() {
return boxItemsManager;
}
/**
* Get the BoxItemsManager for items(files/folders) shared to you, this can be used to make API calls on files/folders endpoints. Note this is different
* from getSharedItemsManager(), getSharedItemsManager is used for api calls on sharedItems endpoints.
*
* @param sharedLink
* shared link
* @param password
* use null if no password required.
* @return
*/
public IBoxItemsManager getSharedBoxItemsManager(String sharedLink, String password) {
return new BoxItemsManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getSharedItemAuth(sharedLink, password), getRestClient());
}
/**
* Get the BoxItemsManager, which can be used to make API calls on files/folders endpoints for trashed files/folders.
*
* @return the boxItemsManager
*/
public IBoxTrashManager getTrashManager() {
return trashManager;
}
/**
* Get the OAuthManager, which can be used to make OAuth related api calls.
*
* @return
*/
public IBoxOAuthManager getOAuthManager() {
return oauthManager;
}
/**
* Get the BoxGroupsManager, which can be used to make API calls on groups endpoints.
*/
public IBoxGroupsManager getGroupsManager() {
return groupsManager;
}
/**
* Get Shared Items manager, which can be used to make API calls on shared item endpoints.
*
* @param sharedLink
* shared link
* @param password
* password
* @return BoxSharedItemsManager
*/
public IBoxSharedItemsManager getSharedItemsManager(String sharedLink, String password) {
return new BoxSharedItemsManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getSharedItemAuth(sharedLink, password), getRestClient());
}
/**
* Get the BoxFilesManager for shared items, which can be used to make API calls on files endpoints for a shared item.
*
* @param sharedLink
* shared link.
* @param password
* password of the shared link, use null if there is no password
* @return BoxFilesManager
*/
public IBoxFilesManager getSharedFilesManager(String sharedLink, String password) {
return new BoxFilesManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getSharedItemAuth(sharedLink, password), getRestClient());
}
/**
* Get the BoxFoldersManager for shared items, which can be used to make API calls on folders endpoints for a shared item.
*
* @param sharedLink
* shared link.
* @param password
* password of the shared link, use null if there is no password
* @return BoxFoldersManager
*/
public IBoxFoldersManager getSharedFoldersManager(String sharedLink, String password) {
return new BoxFoldersManageImpl(getConfig(), getResourceHub(), getJSONParser(), getSharedItemAuth(sharedLink, password), getRestClient());
}
/**
* Get the BoxCommentsManager for shared items, which can be used to make API calls on comments endpoints for a shared item.
*
* @param sharedLink
* shared link.
* @param password
* password of the shared link, use null if there is no password
* @return BoxFoldersManager
*/
public IBoxCommentsManager getSharedCommentsManager(String sharedLink, String password) {
return new BoxCommentsManagerImpl(getConfig(), getResourceHub(), getJSONParser(), getSharedItemAuth(sharedLink, password), getRestClient());
}
/**
* A generic way to get a resourceManager with shared link auth. Currently only supports file, folder and comment endpoints.
*
* @param type
* @param sharedLink
* @param password
* @return
*/
public IBoxResourceManager getResourceManagerWithSharedLinkAuth(BoxResourceType type, String sharedLink, String password) {
switch (type) {
case FILE:
return getSharedFilesManager(sharedLink, password);
case FOLDER:
return getSharedFoldersManager(sharedLink, password);
case COMMENT:
return getSharedCommentsManager(sharedLink, password);
default:
throw new NotImplementedException();
}
}
/**
* Get a resource manager plugged in based on the key.
*/
public IBoxResourceManager getPluginManager(String pluginManagerKey) {
return this.pluginResourceManagers.get(pluginManagerKey);
}
/**
* @return the BoxFoldersManager, which can be used to make API calls on folders endpoints. Note this folders manager only work on the folders you own. if
* you are trying to make api calls on a shared folder (folder shared to you via shared link), please use getSharedFoldersManager().
*/
public IBoxFoldersManager getFoldersManager() {
return foldersManager;
}
/**
* @return BoxSearchManager through which searches can be performed.
*/
public IBoxSearchManager getSearchManager() {
return searchManager;
}
/**
*
* @return BoxEventsManager through which the Box Events API can be queried.
*/
public IBoxEventsManager getEventsManager() {
return eventsManager;
}
/**
* @return the collaborationsManager
*/
public IBoxCollaborationsManager getCollaborationsManager() {
return collaborationsManager;
}
/**
* @return the commentsManager
*/
public IBoxCommentsManager getCommentsManager() {
return commentsManager;
}
/**
* @return the usersManager
*/
public IBoxUsersManager getUsersManager() {
return usersManager;
}
/**
* Get authenticated using a Auth object, this could be a previously stored data.
*
* @param authData
*/
public synchronized void authenticate(IAuthData authData) {
OAuthDataController oauthController = getOAuthDataController();
oauthController.setOAuthData((BoxOAuthToken) authData);
if (authData != null) {
oauthController.setTokenState(OAuthTokenState.AVAILABLE);
}
else {
oauthController.setTokenState(OAuthTokenState.PRE_CREATION);
}
}
/**
* Get authenticated. Note authentication is done asynchronously and may not finish right after this method. The authentication result should be notified to
* the IAuthFlowListener parameter.
*
* @param authFlowUI
* UI for the auth(OAuth) flow.
* @param autoRefreshOAuth
* whether the OAuth token should be auto refreshed when it expires.
* @param listener
* listener listening to the auth flow events.
*/
public void authenticate(IAuthFlowUI authFlowUI, boolean autoRefreshOAuth, IAuthFlowListener listener) {
this.mAuthListener = listener;
authFlowUI.authenticate(this);
}
@Override
public void onAuthFlowEvent(IAuthEvent event, IAuthFlowMessage message) {
OAuthEvent oe = (OAuthEvent) event;
if (oe == OAuthEvent.OAUTH_CREATED) {
((OAuthAuthorization) getAuth()).setOAuthData(getOAuthTokenFromMessage(message));
}
if (mAuthListener != null) {
mAuthListener.onAuthFlowEvent(event, message);
}
}
/**
* Check authentication state.
*
* @return authentication state
*/
public OAuthTokenState getAuthState() {
return getOAuthDataController().getTokenState();
}
/**
* Get config.
*
* @return config
*/
public IBoxConfig getConfig() {
return config;
}
/**
* Create a resource hub
*
* @return IBoxResourceHub
*/
protected IBoxResourceHub createResourceHub() {
return new BoxResourceHub();
}
/**
* Create a json parser.
*
* @param resourceHub
* @return
*/
protected IBoxJSONParser createJSONParser(IBoxResourceHub resourceHub) {
return new BoxJSONParser(resourceHub);
}
/**
* Get resource hub.
*
* @return Resource hub
*/
public IBoxResourceHub getResourceHub() {
return this.resourceHub;
}
public IBoxJSONParser getJSONParser() {
return this.jsonParser;
}
/**
* Get rest client.
*
* @return
*/
protected IBoxRESTClient getRestClient() {
return this.restClient;
}
/**
* Create a REST client to make api calls.
*
* @return IBoxRESTClient
*/
protected static IBoxRESTClient createRestClient() {
return new BoxRESTClient();
}
protected static IBoxRESTClient createMonitoredRestClient(final BoxConnectionManager connectionManager) {
return new BoxRESTClient(connectionManager);
}
/**
* Get the authorization needed for shared items.
*
* @param sharedLink
* shared link
* @param password
* password(use null if no password at all)
* @return IBoxRequestAuth
*/
public IBoxRequestAuth getSharedItemAuth(String sharedLink, String password) {
return new SharedLinkAuthorization((OAuthAuthorization) getAuth(), sharedLink, password);
}
/**
* Create auth data controller, which maintains auth data and handles auth refresh.
*/
protected IAuthDataController createAuthDataController(final String clientId, final String clientSecret) {
return new OAuthDataController(this, clientId, clientSecret, DEFAULT_AUTO_REFRESH);
}
/**
* From auth data controller, generate IBoxRequestAuth, which can be applied to api requests.
*/
protected IBoxRequestAuth createAuthorization(IAuthDataController controller) {
return new OAuthAuthorization((OAuthDataController) authController);
}
/**
* Get the auth object used to make api calls.
*
* @return
*/
public IBoxRequestAuth getAuth() {
return auth;
}
@Override
public void onAuthFlowMessage(IAuthFlowMessage message) {
if (mAuthListener != null) {
mAuthListener.onAuthFlowMessage(message);
}
}
@Override
public void onAuthFlowException(Exception e) {
if (mAuthListener != null) {
mAuthListener.onAuthFlowException(e);
}
}
protected BoxOAuthToken getOAuthTokenFromMessage(IAuthFlowMessage message) {
return (BoxOAuthToken) message.getData();
}
}
|
package crSemantics;
import java.util.ArrayList;
import java.util.List;
import graph.ConresActivity;
import graph.ConresGraph;
import graph.ConresRelation;
import graph.Type;
import interfaces.Graph;
import interfaces.Semantics;
import utils.SemanticsFactory;
//TODO MAKE A DEEP COPY OF THE CRGRAPH WHEN RECIEVED
public class CRSemantics implements Semantics {
public SemanticsFactory semanticsFactory = null;
public CRSemantics(){
this.semanticsFactory = new SemanticsFactory();
}
public boolean isExecutable(ConresGraph graph, int id) {
for(int i = 0; i < graph.activities.size(); i++) {
if(graph.activities.get(i).id == id)
// what if multiple ConresActivities have the same id?
// not our problem
return isExecutable(graph, graph.activities.get(i));
}
return true;
}
public boolean isExecutable(ConresGraph graph, ConresActivity activity) {
for(int i = 0; i < graph.relations.size(); i++) {
if(graph.relations.get(i).type == Type.CONDITION)
// this definitely needs to be tested. object equivalence
if (graph.relations.get(i).child == activity)
if(graph.relations.get(i).parent.isPending || !graph.relations.get(i).parent.isExecuted)
return false;
}
return true;
}
@Override
public List<Integer> getPossibleActions(Graph graph) throws Exception {
ConresGraph crGraph = null;
try{
crGraph = (ConresGraph)graph;
}catch(Exception e){
throw new Exception("This is not a CRGraph");
}
List<Integer> actions = new ArrayList<Integer>();
for(int i = 0; i < crGraph.activities.size(); i++) {
if(!crGraph.activities.get(i).isExecuted && isExecutable(crGraph, crGraph.activities.get(i).id))
actions.add(crGraph.activities.get(i).id);
}
return actions;
}
/**
* Doing it this way, it's possible that no events are executed
* Maybe there should be a check if all events are in our graph
*/
@Override
public ConresGraph executeAction(Graph graph, List<Integer> ids) throws Exception {
ConresGraph crGraph = null;
try{
crGraph = (ConresGraph)graph;
}catch(Exception e){
throw new Exception("This is not a CRGraph");
}
// Its nested graph activities that needs execution
if(ids.size() > 1){
for(int i = 0; i < crGraph.activities.size(); i++){
if(crGraph.activities.get(i).id == ids.get(0)){
//TODO check all condition relations
//Check that is has a nested Graph
ConresActivity activity = crGraph.activities.get(i);
if(activity.nestedGraph == null){
throw new Exception("There is no nested graph for given id");
}
Semantics semantics = semanticsFactory.getSemantics(activity.nestedGraph);
ids.remove(0);
activity.nestedGraph = semantics.executeAction(activity.nestedGraph, ids);
}
}
}
// Its activity in this graph that needs execution
if (ids.size() == 1){
for (int i = 0; i < crGraph.activities.size(); i++){
if(crGraph.activities.get(i).id == ids.get(0)){
ConresActivity activity = crGraph.activities.get(i);
activity.isExecuted = true;
activity.isPending = false;
//Check all condition relations
if(!noBlockingConditions(activity, crGraph)){
throw new Exception("Condition relationship blocking for execution");
}
//TODO Check if it makes anything pending.
makeActivitiesPending(activity, crGraph);
}
}
}
return crGraph;
}
// Function used to Response relations
private void makeActivitiesPending(ConresActivity activity, ConresGraph crGraph) {
for (int i = 0; i < crGraph.relations.size(); i++){
ConresRelation relation = crGraph.relations.get(i);
if(relation.parent.id == activity.id && relation.type == Type.RESPONSE){
relation.child.isPending = true;
}
}
}
// Function to check for any not done conditions
private boolean noBlockingConditions(ConresActivity activity, ConresGraph crGraph) {
for(int i = 0; i < crGraph.relations.size(); i++){
ConresRelation relation = crGraph.relations.get(i);
if(relation.child.id == activity.id && relation.type == Type.CONDITION && !relation.parent.isExecuted){
return false;
}
else if(relation.child.id == activity.id && relation.type == Type.CONDITION && relation.parent.isExecuted){
if(!noBlockingConditions(relation.parent, crGraph)){
return false;
}
}
}
return true;
}
@Override
public boolean isFinished(Graph graph) throws Exception {
ConresGraph crGraph = null;
try{
crGraph = (ConresGraph)graph;
}catch(Exception e){
throw new Exception("This is not a CRGraph");
}
for(int i = 0; i < crGraph.activities.size(); i++){
ConresActivity activity = crGraph.activities.get(i);
if(activity.isPending == true){
return false;
}
if (activity.nestedGraph != null){
//Check if nested graph is done
Graph nestedGraph = activity.nestedGraph;
Semantics semantics = semanticsFactory.getSemantics(nestedGraph);
if(semantics.isFinished(nestedGraph) == false){
return false;
}
}
}
return true;
}
}
|
package edu.ucsb.cs56.projects.games.poker;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
final class PokerSinglePlayer extends PokerGame {
Timer timer;
int timer_value = 1500; // milliseconds
boolean yourTurnToBet = true;
/**
* Default no-arg constructor;
*/
public PokerSinglePlayer() {
}
/**
* Constructor to set the player and opponent's initial chips.
* @param dChips
* @param pChips
*/
public PokerSinglePlayer(int oChips, int pChips){
opponent.setChips(oChips);
player.setChips(pChips);
}
/**
* Starts the game.
*/
public void go() {
pot = 0;
playerSetUp();
layoutSubViews();
if(!gameOver){
step = Step.BLIND;
turn = Turn.OPPONENT;
timer = new Timer(timer_value, new ActionListener() {
public void actionPerformed(ActionEvent e){
opponentAI();
}
});
timer.setRepeats(false);
message = "opponent is thinking...";
prompt = "opponent goes first!";
timer.restart();
}
}
/**
* Method to activate the opponent AI on turn change.
*/
public void changeTurn() {
if (turn == Turn.PLAYER) {
if (responding == true) {
turn = Turn.OPPONENT;
controlButtons();
updateFrame();
message = "opponent is thinking...";
timer.restart();
} else {
updateFrame();
nextStep();
if (step != Step.SHOWDOWN) {
turn = Turn.OPPONENT;
controlButtons();
prompt = "opponent Turn.";
message = "opponent is thinking...";
updateFrame();
timer.restart();
}
}
} else if (turn == Turn.OPPONENT) {
if (responding == true) {
turn = Turn.PLAYER;
controlButtons();
responding = false;
prompt = "What will you do?";
updateFrame();
} else {
prompt = "What will you do?";
turn = Turn.PLAYER;
controlButtons();
updateFrame();
}
}
}
/**
* Simple AI for the opponent in single player.
*/
public void opponentAI() {
Hand opponentHand = new Hand();
if (step == Step.BLIND) {
if (opponentHand.size() != 2) {
for (int i = 0; i < 2; i++) {
opponentHand.add(opponent.getHand().get(i));
}
}
} else if (step == Step.FLOP) {
if (opponentHand.size() < 5) {
for (Card c : flop) {
opponentHand.add(c);
}
}
} else if (step == Step.TURN) {
if (opponentHand.size() < 6) {
opponentHand.add(turnCard);
}
} else if (step == Step.RIVER) {
if (opponentHand.size() < 7) {
opponentHand.add(riverCard);
}
} else {
}
boolean shouldBet = false;
boolean shouldCall = true;
int dValue = opponentHand.calculateValue();
int betAmount = 5 * dValue;
if (step == Step.BLIND) {
if (dValue >= 1) {
shouldBet = true;
}
} else if (step == Step.FLOP) {
if (dValue >= 3) {
shouldBet = true;
}
if ((dValue == 0 && bet >= 20)) {
shouldCall = false;
}
} else if (step == Step.TURN) {
if (dValue >= 4) {
shouldBet = true;
}
if ((dValue < 2 && bet > 20)) {
shouldCall = false;
}
} else if (step == Step.RIVER) {
if (dValue >= 4) {
shouldBet = true;
}
if ((dValue < 2 && bet > 20))
shouldCall = false;
}
if (responding == true) {
if (shouldCall) {
message = "opponent calls.";
pot += bet;
opponent.setChips(opponent.getChips() - opponent.bet(bet));
bet = 0;
responding = false;
nextStep();
updateFrame();
timer.restart();
} else {
message = "opponent folds.";
opponent.foldHand();
}
} else if (shouldBet && step != Step.SHOWDOWN) {
if ((opponent.getChips() - betAmount >= 0) && (player.getChips() - betAmount >= 0)) {
bet = betAmount;
pot += bet;
opponent.setChips(opponent.getChips() - opponent.bet(bet));
responding = true;
message = "opponent bets " + bet + " chips.";
updateFrame();
changeTurn();
} else {
message = "opponent checks.";
updateFrame();
changeTurn();
}
} else if (step != Step.SHOWDOWN) {
message = "opponent checks.";
updateFrame();
changeTurn();
}
}
/**
* Method overridden to allow for a new single player game to start.
*/
public void showWinnerAlert() {
if(!gameOver){
String message = "";
oSubPane2.remove(backCardLabel1);
oSubPane2.remove(backCardLabel2);
for(int i=0;i<2;i++){
oSubPane2.add(new JLabel(getCardImage(opponent.getCardFromHand(i))));
}
updateFrame();
if (winnerType == Winner.PLAYER) {
System.out.println("player");
message = "You won! \n\n Next round?";
} else if (winnerType == Winner.OPPONENT) {
System.out.println("opponent");
message = "opponent won. \n\n Next round?";
} else if (winnerType == Winner.TIE){
System.out.println("tie");
message = "Tie \n\n Next round?";
}
int option = JOptionPane.showConfirmDialog(null, message, "Winner",
JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
// Restart
mainFrame.dispose();
// First check if players have enough chips
if(opponent.getChips() < 5) {
gameOver("GAME OVER!\n\n opponent has run out of chips!");
}
else if (player.getChips() < 5) {
gameOver("GAME OVER!\n\n you have run out of chips!");
}
// Create new game
PokerSinglePlayer singlePlayerReplay = new PokerSinglePlayer();
singlePlayerReplay.go();
}
else if (option == JOptionPane.NO_OPTION) {
gameOver("");
mainFrame.dispose();
}
else {
// Quit
System.exit(1);
}
}
}
/**
* Function that puts up a Game Over Frame that can take us back to the Main Screen
*/
private void gameOver(String label) {
gameOverFrame = new JFrame();
gameOverFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameOverFrame.setBackground(Color.red);
gameOverMessage = new JPanel();
gameOverMessage.setBackground(Color.red);
gameOverButtonPanel = new JPanel();
gameOverButtonPanel.setBackground(Color.red);
gameOverLabel = new JLabel(label);
gameOverButton = new JButton("Back to Main Menu");
gameOverButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
gameOverFrame.setVisible(false);
PokerMain restart = new PokerMain();
restart.go();
}
});
gameOverMessage.add(gameOverLabel);
gameOverButtonPanel.add(gameOverButton);
gameOverFrame.setSize(300, 200);
gameOverFrame.setResizable(false);
gameOverFrame.setLocation(250, 250);
gameOverFrame.getContentPane().add(BorderLayout.NORTH, gameOverMessage);
gameOverFrame.getContentPane().add(BorderLayout.SOUTH, gameOverButtonPanel);
gameOverFrame.pack();
gameOverFrame.setVisible(true);
}
}
|
package edu.washington.escience.myria.parallel;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.collect.ImmutableMap;
import edu.washington.escience.myria.MyriaConstants;
import edu.washington.escience.myria.MyriaConstants.PROFILING_MODE;
import edu.washington.escience.myria.operator.IDBController;
import edu.washington.escience.myria.operator.Operator;
import edu.washington.escience.myria.operator.RootOperator;
import edu.washington.escience.myria.operator.network.Consumer;
import edu.washington.escience.myria.operator.network.Producer;
import edu.washington.escience.myria.parallel.ipc.IPCConnectionPool;
import edu.washington.escience.myria.parallel.ipc.StreamIOChannelID;
import edu.washington.escience.myria.profiling.ProfilingLogger;
import edu.washington.escience.myria.util.AtomicUtils;
import edu.washington.escience.myria.util.concurrent.ReentrantSpinLock;
/**
* Non-blocking driving code for one of the fragments in a {@link LocalSubQuery}.
*
* {@link LocalFragment} state could be:<br>
* 1) In execution.<br>
* 2) In dormant.<br>
* 3) Already finished.<br>
* 4) Has not started.
*/
public final class LocalFragment {
/** The logger for this class. */
private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(LocalFragment.class);
/**
* The root operator.
*/
private final RootOperator root;
/**
* The executor who is responsible for executing this fragment.
*/
private final ExecutorService myExecutor;
/**
* Each bit for each output channel. Currently, if a single output channel is not writable, the whole
* {@link LocalFragment} stops.
*/
private final BitSet outputChannelAvailable;
/**
* the subquery of which this {@link LocalFragment} is a part.
*/
private final LocalSubQuery localSubQuery;
/**
* The actual physical plan to be executed when this {@link LocalFragment} is run.
*/
private final Callable<Void> executionPlan;
/**
* Task for executing initialization code .
*/
private final Callable<Void> initTask;
/**
* The output channels belonging to this {@link LocalFragment}.
*/
private final StreamIOChannelID[] outputChannels;
/**
* The IDBController operators, if any, in this {@link LocalFragment}.
*/
private final Set<IDBController> idbControllerSet;
/**
* IPC ID of the owner {@link Worker} or {@link Server}.
*/
private final int ipcEntityID;
/**
* The handle for managing the execution of the {@link LocalFragment}.
*/
private volatile Future<Void> executionHandle;
/**
* Protect the output channel status.
*/
private final ReentrantSpinLock outputLock = new ReentrantSpinLock();
/**
* Future for the {@link LocalFragment} execution.
*/
private final LocalFragmentFuture fragmentExecutionFuture;
/**
* The lock mainly to make operator memory consistency.
*/
private final Object executionLock = new Object();
/**
* resource manager.
*/
private final LocalFragmentResourceManager resourceManager;
/**
* Record nanoseconds so that we can normalize the time in {@link ProfilingLogger}.
*/
private volatile long beginNanoseconds;
/**
* Record the milliseconds so that we can calculate the difference to the worker initialization in
* {@link ProfilingLogger}.
*/
private volatile long beginMilliseconds = 0;
/**
* @return the fragment execution future.
*/
LocalFragmentFuture getExecutionFuture() {
return fragmentExecutionFuture;
}
/** total used CPU time of this task so far. */
private volatile long cpuTotal = 0;
/** total used CPU time of this task before starting the current execution. */
private volatile long cpuBefore = 0;
/** the thread id of this task. */
private volatile long threadId = -1;
/**
* @param connectionPool the IPC connection pool.
* @param localSubQuery the {@link LocalSubQuery} of which this {@link LocalFragment} is a part.
* @param root the root operator this fragment will run.
* @param executor the executor who provides the execution service for the fragment to run on
*/
LocalFragment(final IPCConnectionPool connectionPool, final LocalSubQuery localSubQuery, final RootOperator root,
final ExecutorService executor) {
ipcEntityID = connectionPool.getMyIPCID();
resourceManager = new LocalFragmentResourceManager(connectionPool, this);
executionCondition = new AtomicInteger(STATE_OUTPUT_AVAILABLE | STATE_INPUT_AVAILABLE);
this.root = root;
myExecutor = executor;
this.localSubQuery = localSubQuery;
fragmentExecutionFuture = new LocalFragmentFuture(this, true);
idbControllerSet = new HashSet<IDBController>();
HashSet<StreamIOChannelID> outputChannelSet = new HashSet<StreamIOChannelID>();
collectDownChannels(root, outputChannelSet);
outputChannels = outputChannelSet.toArray(new StreamIOChannelID[] {});
HashMap<StreamIOChannelID, Consumer> inputChannelMap = new HashMap<StreamIOChannelID, Consumer>();
collectUpChannels(root, inputChannelMap);
for (final Consumer operator : inputChannelMap.values()) {
resourceManager.allocateInputBuffer(operator);
}
Arrays.sort(outputChannels);
outputChannelAvailable = new BitSet(outputChannels.length);
for (int i = 0; i < outputChannels.length; i++) {
outputChannelAvailable.set(i);
}
executionPlan = new Callable<Void>() {
@Override
public Void call() throws Exception {
// synchronized to keep memory consistency
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Start fragment execution: " + LocalFragment.this);
}
if (threadId == -1) {
threadId = Thread.currentThread().getId();
}
// otherwise threadId should always equal to Thread.currentThread().getId() based on the current design
PROFILING_MODE mode = localSubQuery.getProfilingMode();
if (mode.equals(PROFILING_MODE.RESOURCE) || mode.equals(PROFILING_MODE.ALL)) {
synchronized (LocalFragment.this) {
cpuBefore = ManagementFactory.getThreadMXBean().getThreadCpuTime(threadId);
}
}
try {
synchronized (executionLock) {
LocalFragment.this.executeActually();
}
} catch (RuntimeException ee) {
LOGGER.error("Unexpected Error: ", ee);
throw ee;
} finally {
executionHandle = null;
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("End execution: " + LocalFragment.this);
}
if (mode.equals(PROFILING_MODE.RESOURCE) || mode.equals(PROFILING_MODE.ALL)) {
synchronized (LocalFragment.this) {
cpuTotal += ManagementFactory.getThreadMXBean().getThreadCpuTime(threadId) - cpuBefore;
cpuBefore = 0;
}
}
return null;
}
};
initTask = new Callable<Void>() {
@Override
public Void call() throws Exception {
// synchronized to keep memory consistency
LOGGER.trace("Start fragment initialization: ", LocalFragment.this);
try {
synchronized (executionLock) {
LocalFragment.this.initActually();
}
} catch (Throwable e) {
LOGGER.error("Fragment failed to open because of exception:", e);
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
AtomicUtils.setBitByValue(executionCondition, STATE_FAIL);
if (fragmentExecutionFuture.setFailure(e)) {
cleanup(true);
}
}
LOGGER.trace("End fragment initialization: {}", LocalFragment.this);
return null;
}
};
}
/**
* @return all output channels belonging to this {@link LocalFragment}.
*/
StreamIOChannelID[] getOutputChannels() {
return outputChannels;
}
/**
* @return all the IDBController operators in this {@link LocalFragment}.
*/
Set<IDBController> getIDBControllers() {
return idbControllerSet;
}
/**
* gather all output (Producer or IDBController's EOI report) channel IDs.
*
* @param currentOperator current operator to check.
* @param outputExchangeChannels the current collected output channel IDs.
*/
private void collectDownChannels(final Operator currentOperator,
final HashSet<StreamIOChannelID> outputExchangeChannels) {
if (currentOperator instanceof Producer) {
Producer p = (Producer) currentOperator;
StreamIOChannelID[] exCID = p.getOutputChannelIDs(ipcEntityID);
for (StreamIOChannelID element : exCID) {
outputExchangeChannels.add(element);
}
} else if (currentOperator instanceof IDBController) {
IDBController p = (IDBController) currentOperator;
ExchangePairID oID = p.getControllerOperatorID();
int wID = p.getControllerWorkerID();
outputExchangeChannels.add(new StreamIOChannelID(oID.getLong(), wID));
idbControllerSet.add(p);
}
final Operator[] children = currentOperator.getChildren();
if (children != null) {
for (final Operator child : children) {
if (child != null) {
collectDownChannels(child, outputExchangeChannels);
}
}
}
}
/**
* @return if the {@link LocalFragment} is finished
*/
public boolean isFinished() {
return fragmentExecutionFuture.isDone();
}
/**
* gather all input (consumer) channel IDs.
*
* @param currentOperator current operator to check.
* @param inputExchangeChannels the current collected input channels.
*/
private void collectUpChannels(final Operator currentOperator,
final Map<StreamIOChannelID, Consumer> inputExchangeChannels) {
if (currentOperator instanceof Consumer) {
Consumer c = (Consumer) currentOperator;
int[] sourceWorkers = c.getSourceWorkers(ipcEntityID);
ExchangePairID oID = c.getOperatorID();
for (int sourceWorker : sourceWorkers) {
inputExchangeChannels.put(new StreamIOChannelID(oID.getLong(), sourceWorker), c);
}
}
final Operator[] children = currentOperator.getChildren();
if (children != null) {
for (final Operator child : children) {
if (child != null) {
collectUpChannels(child, inputExchangeChannels);
}
}
}
}
/**
* call this method if a new TupleBatch arrived at a Consumer operator belonging to this {@link LocalFragment}. This
* method is always called by Netty Upstream IO worker threads.
*/
public void notifyNewInput() {
AtomicUtils.setBitByValue(executionCondition, STATE_INPUT_AVAILABLE);
execute();
}
/**
* Called by Netty downstream IO worker threads.
*
* @param outputChannelID the logical output channel ID.
*/
public void notifyOutputDisabled(final StreamIOChannelID outputChannelID) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Output disabled: " + outputChannelID);
}
int idx = Arrays.binarySearch(outputChannels, outputChannelID);
outputLock.lock();
try {
outputChannelAvailable.clear(idx);
} finally {
outputLock.unlock();
}
// disable output
AtomicUtils.unsetBitByValue(executionCondition, STATE_OUTPUT_AVAILABLE);
}
/**
* Called by Netty downstream IO worker threads.
*
* @param outputChannelID the down channel ID.
*/
public void notifyOutputEnabled(final StreamIOChannelID outputChannelID) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Output enabled: " + outputChannelID);
}
if (!isOutputAvailable()) {
int idx = Arrays.binarySearch(outputChannels, outputChannelID);
outputLock.lock();
try {
if (!outputChannelAvailable.get(idx)) {
outputChannelAvailable.set(idx);
if (outputChannelAvailable.nextClearBit(0) >= outputChannels.length) {
// enable output
AtomicUtils.setBitByValue(executionCondition, STATE_OUTPUT_AVAILABLE);
execute();
}
}
} finally {
outputLock.unlock();
}
}
}
@Override
public String toString() {
SubQueryId queryID = localSubQuery.getSubQueryId();
Operator rootOp = root;
StringBuilder stateS = new StringBuilder();
int state = executionCondition.get();
String splitter = "";
if ((state & LocalFragment.STATE_INITIALIZED) == STATE_INITIALIZED) {
stateS.append(splitter + "Initialized");
splitter = " | ";
}
if ((state & LocalFragment.STATE_STARTED) == STATE_STARTED) {
stateS.append(splitter + "Started");
splitter = " | ";
}
if ((state & LocalFragment.STATE_INPUT_AVAILABLE) == STATE_INPUT_AVAILABLE) {
stateS.append(splitter + "Input_Available");
splitter = " | ";
}
if ((state & LocalFragment.STATE_EOS) == STATE_EOS) {
stateS.append(splitter + "EOS");
splitter = " | ";
}
if ((state & LocalFragment.STATE_EXECUTION_REQUESTED) == STATE_EXECUTION_REQUESTED) {
stateS.append(splitter + "Execution_Requested");
splitter = " | ";
}
if ((state & LocalFragment.STATE_IN_EXECUTION) == STATE_IN_EXECUTION) {
stateS.append(splitter + "In_Execution");
splitter = " | ";
}
if ((state & LocalFragment.STATE_KILLED) == STATE_KILLED) {
stateS.append(splitter + "Killed");
splitter = " | ";
}
if ((state & LocalFragment.STATE_OUTPUT_AVAILABLE) == STATE_OUTPUT_AVAILABLE) {
stateS.append(splitter + "Output_Available");
splitter = " | ";
}
return String.format("%s: { Owner QID: %s, Root Op: %s, State: %s }", LocalFragment.class.getSimpleName(), queryID,
rootOp, stateS.toString());
}
/**
* Actually execute this fragment.
*
* @return always null. The return value is unused.
*/
private Object executeActually() {
beginNanoseconds = System.nanoTime();
beginMilliseconds = System.currentTimeMillis();
Throwable failureCause = null;
if (executionCondition.compareAndSet(EXECUTION_READY | STATE_EXECUTION_REQUESTED, EXECUTION_READY
| STATE_EXECUTION_REQUESTED | STATE_IN_EXECUTION)) {
EXECUTE : while (true) {
if (Thread.interrupted()) {
Thread.currentThread().interrupt();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("LocalFragment execution interrupted. Root operator: " + root + ". Close directly.");
}
// set interrupted
AtomicUtils.setBitByValue(executionCondition, STATE_INTERRUPTED);
// TODO clean up fragment state
} else {
// do the execution
// clearInput(); // clear input at beginning.
AtomicUtils.unsetBitByValue(executionCondition, STATE_INPUT_AVAILABLE);
boolean breakByOutputUnavailable = false;
try {
boolean hasData = true;
while (hasData && !breakByOutputUnavailable) {
hasData = false;
if (root.nextReady() != null) {
hasData = true;
breakByOutputUnavailable = !isOutputAvailable();
} else {
// check output
if (root.eoi()) {
root.setEOI(false);
hasData = true;
}
}
if (Thread.interrupted()) {
Thread.currentThread().interrupt();
break;
}
}
} catch (final Throwable e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Unexpected exception occur at operator excution. Operator: " + root, e);
}
failureCause = e;
AtomicUtils.setBitByValue(executionCondition, STATE_FAIL);
}
if (breakByOutputUnavailable) {
// we do not know whether all the inputs have been consumed, recover the input available bit
AtomicUtils.setBitByValue(executionCondition, STATE_INPUT_AVAILABLE);
}
}
// Check if another round of execution is needed.
int oldV = executionCondition.get();
while (oldV != EXECUTION_CONTINUE) {
// try clear the STATE_EXECUTION_REQUESTED and STATE_IN_EXECUTION bit
if (executionCondition.compareAndSet(oldV, oldV & ~(STATE_EXECUTION_REQUESTED | STATE_IN_EXECUTION))) {
// exit execution.
break EXECUTE;
}
oldV = executionCondition.get();
}
}
// clear interrupted
AtomicUtils.unsetBitByValue(executionCondition, STATE_INTERRUPTED);
Thread.interrupted();
}
if ((executionCondition.get() & STATE_FAIL) == STATE_FAIL) {
// failed
if (fragmentExecutionFuture.setFailure(failureCause)) {
cleanup(true);
}
} else if (root.eos()) {
if (AtomicUtils.setBitIfUnsetByValue(executionCondition, STATE_EOS)) {
cleanup(false);
fragmentExecutionFuture.setSuccess();
}
} else if ((executionCondition.get() & STATE_KILLED) == STATE_KILLED) {
// killed
if (fragmentExecutionFuture.setFailure(new QueryKilledException("LocalFragment was killed"))) {
cleanup(true);
}
}
return null;
}
/**
* Current execution condition.
*/
private final AtomicInteger executionCondition;
/**
* The {@link LocalFragment} is initialized.
*/
private static final int STATE_INITIALIZED = (1 << 0);
/**
* The {@link LocalFragment} has actually been started.
*/
private static final int STATE_STARTED = (1 << 1);
/**
* All outputs of the {@link LocalFragment} are available.
*/
private static final int STATE_OUTPUT_AVAILABLE = (1 << 2);
/**
* @return if the output channels are available for writing.
*/
private boolean isOutputAvailable() {
return (executionCondition.get() & STATE_OUTPUT_AVAILABLE) == STATE_OUTPUT_AVAILABLE;
}
/**
* Any input of the {@link LocalFragment} is available.
*/
private static final int STATE_INPUT_AVAILABLE = (1 << 3);
/**
* The {@link LocalFragment} is killed.
*/
private static final int STATE_KILLED = (1 << 4);
/**
* The {@link LocalFragment} is EOS.
*/
private static final int STATE_EOS = (1 << 5);
/**
* The {@link LocalFragment} has been requested to execute.
*/
private static final int STATE_EXECUTION_REQUESTED = (1 << 6);
/**
* The {@link LocalFragment} fails because of uncaught exception.
*/
private static final int STATE_FAIL = (1 << 7);
/**
* The {@link LocalFragment} execution thread is interrupted.
*/
private static final int STATE_INTERRUPTED = (1 << 8);
/**
* The {@link LocalFragment} is in execution.
*/
private static final int STATE_IN_EXECUTION = (1 << 9);
/**
* Non-blocking ready condition.
*/
public static final int EXECUTION_PRE_START = STATE_INITIALIZED | STATE_OUTPUT_AVAILABLE | STATE_INPUT_AVAILABLE;
/**
* Non-blocking ready condition.
*/
public static final int EXECUTION_READY = EXECUTION_PRE_START | STATE_STARTED;
/**
* Non-blocking continue execution condition.
*/
public static final int EXECUTION_CONTINUE = EXECUTION_READY | STATE_EXECUTION_REQUESTED | STATE_IN_EXECUTION;
/**
* @return if the {@link LocalFragment} has been killed.
*/
public boolean isKilled() {
return (executionCondition.get() & STATE_KILLED) == STATE_KILLED;
}
/**
* clean up the {@link LocalFragment}, release resources, etc.
*
* @param failed if the {@link LocalFragment} execution has already failed.
*/
private void cleanup(final boolean failed) {
if (AtomicUtils.unsetBitIfSetByValue(executionCondition, STATE_INITIALIZED)) {
// Only cleanup if initialized.
try {
root.close();
} catch (Throwable ee) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Unknown exception at operator close. Root operator: " + root + ".", ee);
}
if (!failed) {
fragmentExecutionFuture.setFailure(ee);
}
} finally {
if (resourceManager != null) {
resourceManager.cleanup();
}
}
}
}
/**
* Kill this {@link LocalFragment}.
*
*/
void kill() {
if (!AtomicUtils.setBitIfUnsetByValue(executionCondition, STATE_KILLED)) {
return;
}
final Future<Void> executionHandleLocal = executionHandle;
if (executionHandleLocal != null) {
// Abruptly cancel the execution
executionHandleLocal.cancel(true);
}
myExecutor.submit(executionPlan);
}
/**
* Start this {@link LocalFragment}.
*/
public void start() {
AtomicUtils.setBitByValue(executionCondition, STATE_STARTED);
execute();
}
/**
* Execute this {@link LocalFragment}.
*/
private void execute() {
if (executionCondition.compareAndSet(EXECUTION_READY, EXECUTION_READY | STATE_EXECUTION_REQUESTED)) {
// set in execution.
executionHandle = myExecutor.submit(executionPlan);
}
}
/**
* Execution environment variable.
*/
private volatile ImmutableMap<String, Object> execEnvVars;
/**
* Initialize the {@link LocalFragment}.
*
* @param execEnvVars execution environment variable.
*/
public void init(final ImmutableMap<String, Object> execEnvVars) {
this.execEnvVars = execEnvVars;
try {
myExecutor.submit(initTask).get();
} catch (InterruptedException e) {
Thread.interrupted();
return;
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
}
/**
* The actual initialization method.
*
* @throws Exception if any exception occurs.
*/
private void initActually() throws Exception {
ImmutableMap.Builder<String, Object> b = ImmutableMap.builder();
b.put(MyriaConstants.EXEC_ENV_VAR_FRAGMENT_RESOURCE_MANAGER, resourceManager);
b.putAll(execEnvVars);
root.open(b.build());
AtomicUtils.setBitByValue(executionCondition, STATE_INITIALIZED);
}
/**
* Return the {@link LocalSubQuery} of which this {@link LocalFragment} is a part.
*
* @return the {@link LocalSubQuery} of which this {@link LocalFragment} is a part
*/
public LocalSubQuery getLocalSubQuery() {
return localSubQuery;
}
/**
* enable/disable output channels of the root(producer) of this {@link LocalFragment}.
*
* @param workerId the worker that changed its status.
* @param enable enable/disable all the channels that belong to the worker.
*/
public void updateProducerChannels(final int workerId, final boolean enable) {
if (root instanceof Producer) {
((Producer) root).updateChannelAvailability(workerId, enable);
}
}
/**
* return the root operator of this {@link LocalFragment}.
*
* @return the root operator
*/
public RootOperator getRootOp() {
return root;
}
/**
* return the resource manager of this {@link LocalFragment}.
*
* @return the resource manager.
*/
public LocalFragmentResourceManager getResourceManager() {
return resourceManager;
}
/**
* @return the nanosecond counter when this {@link LocalFragment} began executing.
*/
public long getBeginNanoseconds() {
return beginNanoseconds;
}
/**
* @return the time when this {@link LocalFragment} began executing.
*/
public long getBeginMilliseconds() {
return beginMilliseconds;
}
}
|
package org.voovan.network;
import org.voovan.network.handler.SynchronousHandler;
import org.voovan.network.messagesplitter.TransferSplitter;
import org.voovan.tools.TPerformance;
import org.voovan.tools.TUnsafe;
import org.voovan.tools.collection.Chain;
import org.voovan.tools.buffer.TByteBuffer;
import org.voovan.tools.TEnv;
import org.voovan.tools.event.EventRunner;
import org.voovan.tools.event.EventRunnerGroup;
import org.voovan.tools.log.Logger;
import org.voovan.tools.pool.PooledObject;
import org.voovan.tools.reflect.TReflect;
import org.voovan.tools.threadpool.ThreadPool;
import javax.net.ssl.SSLException;
import java.io.FileDescriptor;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.SocketOption;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
public abstract class SocketContext<C extends SelectableChannel, S extends IoSession> extends PooledObject {
public static int ACCEPT_THREAD_SIZE = TEnv.getSystemProperty("AcceptThreadSize", 1);
public static int IO_THREAD_SIZE = TEnv.getSystemProperty("IoThreadSize", TPerformance.getProcessorCount()+1);
public final static Long SELECT_INTERVAL = TEnv.getSystemProperty("SelectInterval", 1000L);
public final static Boolean CHECK_TIMEOUT = TEnv.getSystemProperty("CheckTimeout", true);
public final static boolean ASYNC_SEND = TEnv.getSystemProperty("AsyncSend", true);
public final static boolean ASYNC_RECIVE = TEnv.getSystemProperty("AsyncRecive", true);
public final static boolean DIRECT_IO = TEnv.getSystemProperty("DirectIO", false);
public final static boolean FORCE_FLUSH = TEnv.getSystemProperty("ForecFlush", false);
static {
IO_THREAD_SIZE = IO_THREAD_SIZE < 8 ? 8 : IO_THREAD_SIZE;
System.out.println("[SOCKET] AcceptThreadSize:\t" + ACCEPT_THREAD_SIZE);
System.out.println("[SOCKET] IoThreadSize:\t\t" + IO_THREAD_SIZE);
System.out.println("[SOCKET] SelectInterval:\t" + SELECT_INTERVAL);
System.out.println("[SOCKET] CheckTimeout:\t\t" + CHECK_TIMEOUT);
System.out.println("[SOCKET] AsyncSend:\t\t" + ASYNC_SEND);
System.out.println("[SOCKET] AsyncRecive:\t\t" + ASYNC_RECIVE);
System.out.println("[SOCKET] DirectIO:\t\t" + DIRECT_IO);
System.out.println("[SOCKET] ForecFlush:\t\t" + FORCE_FLUSH);
}
public static EventRunnerGroup COMMON_ACCEPT_EVENT_RUNNER_GROUP;
public static EventRunnerGroup COMMON_IO_EVENT_RUNNER_GROUP;
/**
*
* @param name
* @param size
* @param isAccept Accept
* @return
*/
public static EventRunnerGroup createEventRunnerGroup(String name, int size, boolean isAccept) {
name = name + "-" + (isAccept ? "Accept" : "IO");
int threadPriority = isAccept ? 10 : 9;
EventRunnerGroup eventRunnerGroup = EventRunnerGroup.newInstance(name, size, false, threadPriority, (obj)->{
try {
boolean isCheckTimeout = true;
if(isAccept) {
isCheckTimeout = false;
} else {
isCheckTimeout = CHECK_TIMEOUT;
}
return new SocketSelector(obj, isCheckTimeout);
} catch (IOException e) {
Logger.error(e);
}
return null;
});
return eventRunnerGroup.process();
}
/**
* Accept
* @return Accept
*/
public static synchronized EventRunnerGroup getCommonAcceptEventRunnerGroup(){
if(COMMON_ACCEPT_EVENT_RUNNER_GROUP == null) {
Logger.simple("[HTTP] Create common accept EventRunnerGroup");
COMMON_ACCEPT_EVENT_RUNNER_GROUP = createEventRunnerGroup("Common", ACCEPT_THREAD_SIZE, true);
}
return COMMON_ACCEPT_EVENT_RUNNER_GROUP;
}
/**
* IO
* @return IO
*/
public static synchronized EventRunnerGroup getCommonIoEventRunnerGroup(){
if(COMMON_IO_EVENT_RUNNER_GROUP == null) {
Logger.simple("[HTTP] Create common IO EventRunnerGroup");
COMMON_IO_EVENT_RUNNER_GROUP = createEventRunnerGroup("Common", IO_THREAD_SIZE, false);
}
return COMMON_IO_EVENT_RUNNER_GROUP;
}
protected String host;
protected int port;
protected int readTimeout;
protected int sendTimeout = 1000;
protected IoHandler handler;
protected Chain<IoFilter> filterChain;
protected Chain<IoFilter> reciveFilterChain;
protected Chain<IoFilter> sendFilterChain;
protected MessageSplitter messageSplitter;
protected SSLManager sslManager;
protected ConnectModel connectModel;
protected ConnectType connectType;
protected int readBufferSize = TByteBuffer.DEFAULT_BYTE_BUFFER_SIZE;
protected int sendBufferSize = TByteBuffer.DEFAULT_BYTE_BUFFER_SIZE;
protected int idleInterval = 0;
protected long lastReadTime = System.currentTimeMillis();
private boolean isRegister = false;
protected boolean isSynchronous = true;
private EventRunnerGroup acceptEventRunnerGroup;
private EventRunnerGroup ioEventRunnerGroup;
private FileDescriptor fileDescriptor;
private Object wait = new Object();
/**
*
* , : 1s
* @param host
* @param port
* @param readTimeout
*/
public SocketContext(String host,int port,int readTimeout) {
init(host, port, readTimeout, sendTimeout, this.idleInterval);
}
/**
*
* : 1s
* @param host
* @param port
* @param readTimeout , :
* @param idleInterval
*/
public SocketContext(String host,int port, int readTimeout, int idleInterval) {
init(host, port, readTimeout, sendTimeout, idleInterval);
}
/**
*
* @param host
* @param port
* @param readTimeout , :
* @param sendTimeout , :
* @param idleInterval
*/
public SocketContext(String host,int port,int readTimeout, int sendTimeout, int idleInterval) {
init(host, port, readTimeout, sendTimeout, idleInterval);
}
private void init(String host,int port,int readTimeout, int sendTimeout, int idleInterval){
this.host = host;
this.port = port;
this.readTimeout = readTimeout;
this.sendTimeout = sendTimeout;
this.idleInterval = idleInterval;
connectModel = null;
filterChain = new Chain<IoFilter>();
this.reciveFilterChain = (Chain<IoFilter>) filterChain.clone();
this.sendFilterChain = (Chain<IoFilter>) filterChain.clone();
this.messageSplitter = new TransferSplitter();
this.handler = new SynchronousHandler();
}
public FileDescriptor getFileDescriptor() {
return fileDescriptor;
}
protected void setFileDescriptor(FileDescriptor fileDescriptor) {
this.fileDescriptor = fileDescriptor;
}
public EventRunnerGroup getAcceptEventRunnerGroup() {
return acceptEventRunnerGroup;
}
public void setAcceptEventRunnerGroup(EventRunnerGroup acceptEventRunnerGroup) {
this.acceptEventRunnerGroup = acceptEventRunnerGroup;
}
public EventRunnerGroup getIoEventRunnerGroup() {
return ioEventRunnerGroup;
}
public void setIoEventRunnerGroup(EventRunnerGroup ioEventRunnerGroup) {
this.ioEventRunnerGroup = ioEventRunnerGroup;
}
protected void initSSL(IoSession session) throws SSLException {
if (sslManager != null && connectModel == ConnectModel.SERVER) {
sslManager.createServerSSLParser(session);
} else if (sslManager != null && connectModel == ConnectModel.CLIENT) {
sslManager.createClientSSLParser(session);
}
}
/**
*
* @param parentSocketContext socket
*/
protected void copyFrom(SocketContext parentSocketContext){
this.readTimeout = parentSocketContext.readTimeout;
this.sendTimeout = parentSocketContext.sendTimeout;
this.handler = parentSocketContext.handler;
this.filterChain = (Chain<IoFilter>) parentSocketContext.filterChain;
this.reciveFilterChain = (Chain<IoFilter>) filterChain.clone();
this.sendFilterChain = (Chain<IoFilter>) filterChain.clone();
this.messageSplitter = parentSocketContext.messageSplitter;
this.sslManager = parentSocketContext.sslManager;
this.readBufferSize = parentSocketContext.readBufferSize;
this.sendBufferSize = parentSocketContext.sendBufferSize;
this.idleInterval = parentSocketContext.idleInterval;
this.acceptEventRunnerGroup = parentSocketContext.acceptEventRunnerGroup;
this.ioEventRunnerGroup = parentSocketContext.ioEventRunnerGroup;
}
/**
*
* @return , :
*/
public int getIdleInterval() {
return idleInterval;
}
/**
*
* @param idleInterval , :
*/
public abstract void setIdleInterval(int idleInterval);
/**
* Socket Option
*
* @param name SocketOption, :AsynchronousSocketChannel.setOption
* @param value SocketOption
* @param <T>
* @throws IOException IO
*/
public abstract <T> void setOption(SocketOption<T> name, T value) throws IOException;
/**
* SocketChannel
* @return SocketChannel
*/
public abstract C socketChannel();
public long getLastReadTime() {
return lastReadTime;
}
public void updateLastTime() {
if(CHECK_TIMEOUT == null || CHECK_TIMEOUT) {
this.lastReadTime = System.currentTimeMillis();
}
}
public boolean isTimeOut(){
if(readTimeout > 0 && CHECK_TIMEOUT) {
return (System.currentTimeMillis() - lastReadTime) >= readTimeout;
} else {
return false;
}
}
Object getWait() {
return wait;
}
/**
*
* @return
*/
public int getReadBufferSize() {
return readBufferSize;
}
/**
*
* @param readBufferSize
*/
public void setReadBufferSize(int readBufferSize) {
this.readBufferSize = readBufferSize;
}
/**
*
* @return
*/
public int getSendBufferSize() {
return sendBufferSize;
}
/**
*
* @param sendBufferSize
*/
public void setSendBufferSize(int sendBufferSize) {
this.sendBufferSize = sendBufferSize;
}
public boolean isRegister() {
return isRegister;
}
protected void setRegister(boolean register) {
isRegister = register;
}
protected SocketContext() {
}
/**
* SSL
* @return SSL
*/
public SSLManager getSSLManager() {
return sslManager;
}
/**
* SSL
* @param sslManager SSL
*/
public void setSSLManager(SSLManager sslManager) {
if(this.sslManager==null){
this.sslManager = sslManager;
}
}
/**
*
* @return
*/
public String getHost() {
return host;
}
/**
*
* @return
*/
public int getPort() {
return port;
}
/**
*
* @return , 0: , 0
*/
public int getReadTimeout() {
return readTimeout;
}
/**
*
* @param readTimeout ,0: , 0
*/
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
/**
*
* @return ,0: , 0
*/
public int getSendTimeout(){
return sendTimeout;
}
/**
*
* @param sendTimeout , 0: , 0
*/
public void setSendTimeout(int sendTimeout) {
this.sendTimeout = sendTimeout;
}
/**
*
* @return ConnectModel.CLIENT,ConnectModel.LISTENER, ConnectModel.SERVER
*/
public ConnectModel getConnectModel() {
return connectModel;
}
/**
*
* @return ConnectType.TCP / ConnectType.UDP
*/
public ConnectType getConnectType() {
return connectType;
}
/**
*
* @return
*/
public IoHandler handler(){
return this.handler;
}
/**
*
* @param handler
*/
public void handler(IoHandler handler){
this.handler = handler;
isSynchronous = handler instanceof SynchronousHandler;
}
/**
*
* @return
*/
public Chain<IoFilter> filterChain(){
return this.filterChain;
}
protected Chain<IoFilter> getReciveFilterChain() {
return reciveFilterChain;
}
protected Chain<IoFilter> getSendFilterChain() {
return sendFilterChain;
}
/**
*
* @return
*/
public MessageSplitter messageSplitter() {
return this.messageSplitter;
}
/**
*
* @param messageSplitter
*/
public void messageSplitter(MessageSplitter messageSplitter) {
this.messageSplitter = messageSplitter;
}
public abstract S getSession();
/**
*
*
* @throws IOException IO
*/
public abstract void start() throws IOException;
/**
*
*
*
* @exception IOException IO
*/
public abstract void syncStart() throws IOException;
/**
* Accept Socket
* @throws IOException IO
*/
protected abstract void acceptStart() throws IOException;
/**
*
* @return true:,false:
*/
public abstract boolean isOpen();
/**
*
* @return true:,false:
*/
public abstract boolean isConnected();
/**
*
* @return
*/
public abstract boolean close();
/**
* , SSL ,
*/
protected void hold() {
synchronized (wait) {
try {
wait.wait();
}catch(Exception e){
Logger.error(e);
close();
}
}
}
protected void unhold() {
synchronized (wait) {
EventTrigger.fireConnect(getSession());
wait.notifyAll();
}
}
/**
* SocketSelector
* @param ops
*/
public void bindToSocketSelector(int ops) {
EventRunner eventRunner = null;
if(connectModel == ConnectModel.LISTENER) {
if(acceptEventRunnerGroup == null) {
acceptEventRunnerGroup = getCommonAcceptEventRunnerGroup();
}
eventRunner = acceptEventRunnerGroup.choseEventRunner();
} else {
if(ioEventRunnerGroup == null) {
ioEventRunnerGroup = getCommonIoEventRunnerGroup();
}
eventRunner = ioEventRunnerGroup.choseEventRunner();
}
SocketSelector socketSelector = (SocketSelector)eventRunner.attachment();
socketSelector.register(this, ops);
// FileDescriptor
NioUtil.bindFileDescriptor(this);
}
/**
* Socket
*/
public static void gracefulShutdown() {
if(COMMON_ACCEPT_EVENT_RUNNER_GROUP!=null) {
ThreadPool.gracefulShutdown(COMMON_ACCEPT_EVENT_RUNNER_GROUP.getThreadPool());
}
if(COMMON_IO_EVENT_RUNNER_GROUP!=null) {
ThreadPool.gracefulShutdown(COMMON_IO_EVENT_RUNNER_GROUP.getThreadPool());
}
Logger.info("All IO thread is shutdown");
}
}
|
package org.voovan.network;
import org.voovan.network.handler.SynchronousHandler;
import org.voovan.network.messagesplitter.TransferSplitter;
import org.voovan.tools.TPerformance;
import org.voovan.tools.collection.Chain;
import org.voovan.tools.buffer.TByteBuffer;
import org.voovan.tools.TEnv;
import org.voovan.tools.event.EventRunner;
import org.voovan.tools.event.EventRunnerGroup;
import org.voovan.tools.log.Logger;
import org.voovan.tools.pool.PooledObject;
import org.voovan.tools.threadpool.ThreadPool;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.SocketOption;
import java.nio.channels.SelectableChannel;
public abstract class SocketContext<C extends SelectableChannel, S extends IoSession> extends PooledObject {
public static int ACCEPT_THREAD_SIZE = TEnv.getSystemProperty("AcceptThreadSize", 1);
public static int IO_THREAD_SIZE = TEnv.getSystemProperty("IoThreadSize", TPerformance.getProcessorCount()+1);
public final static int SELECT_INTERVAL = TEnv.getSystemProperty("SelectInterval", 1000);
public final static Boolean CHECK_TIMEOUT = TEnv.getSystemProperty("CheckTimeout", Boolean.class);
public final static boolean ASYNC_SEND = TEnv.getSystemProperty("AsyncSend", true);
public final static boolean ASYNC_RECIVE = TEnv.getSystemProperty("AsyncRecive", true);
static {
IO_THREAD_SIZE = IO_THREAD_SIZE < 8 ? 8 : IO_THREAD_SIZE;
System.out.println("[SOCKET] AcceptThreadSize:\t" + ACCEPT_THREAD_SIZE);
System.out.println("[SOCKET] IoThreadSize:\t\t" + IO_THREAD_SIZE);
System.out.println("[SOCKET] SelectInterval:\t" + SELECT_INTERVAL);
System.out.println("[SOCKET] CheckTimeout:\t\t" + CHECK_TIMEOUT);
System.out.println("[SOCKET] AsyncSend:\t\t" + ASYNC_SEND);
System.out.println("[SOCKET] AsyncRecive:\t\t" + ASYNC_RECIVE);
}
public static EventRunnerGroup COMMON_ACCEPT_EVENT_RUNNER_GROUP;
public static EventRunnerGroup COMMON_IO_EVENT_RUNNER_GROUP;
/**
*
* @param name
* @param size
* @param isAccept Accept
* @return
*/
public static EventRunnerGroup createEventRunnerGroup(String name, int size, boolean isAccept) {
name = name + "-" + (isAccept ? "Accept" : "IO");
int threadPriority = isAccept ? 10 : 9;
return EventRunnerGroup.newInstance(name, size, threadPriority, (obj)->{
try {
boolean isCheckTimeout = true;
if(isAccept) {
isCheckTimeout = false;
} else {
isCheckTimeout = CHECK_TIMEOUT != null ? CHECK_TIMEOUT : true;
}
return new SocketSelector(obj, isCheckTimeout);
} catch (IOException e) {
Logger.error(e);
}
return null;
});
}
/**
* Accept
* @return Accept
*/
public static synchronized EventRunnerGroup getCommonAcceptEventRunnerGroup(){
if(COMMON_ACCEPT_EVENT_RUNNER_GROUP == null) {
Logger.simple("[HTTP] Create common accept EventRunnerGroup");
COMMON_ACCEPT_EVENT_RUNNER_GROUP = createEventRunnerGroup("Common", ACCEPT_THREAD_SIZE, true);
}
return COMMON_ACCEPT_EVENT_RUNNER_GROUP;
}
/**
* IO
* @return IO
*/
public static synchronized EventRunnerGroup getCommonIoEventRunnerGroup(){
if(COMMON_IO_EVENT_RUNNER_GROUP == null) {
Logger.simple("[HTTP] Create common IO EventRunnerGroup");
COMMON_IO_EVENT_RUNNER_GROUP = createEventRunnerGroup("Common", IO_THREAD_SIZE, false);
}
return COMMON_IO_EVENT_RUNNER_GROUP;
}
protected String host;
protected int port;
protected int readTimeout;
protected int sendTimeout = 1000;
protected IoHandler handler;
protected Chain<IoFilter> filterChain;
protected Chain<IoFilter> reciveFilterChain;
protected Chain<IoFilter> sendFilterChain;
protected MessageSplitter messageSplitter;
protected SSLManager sslManager;
protected ConnectModel connectModel;
protected ConnectType connectType;
protected int readBufferSize = TByteBuffer.DEFAULT_BYTE_BUFFER_SIZE;
protected int sendBufferSize = TByteBuffer.DEFAULT_BYTE_BUFFER_SIZE;
protected int idleInterval = 0;
protected long lastReadTime = System.currentTimeMillis();
private boolean isRegister = false;
protected boolean isSynchronous = true;
private EventRunnerGroup acceptEventRunnerGroup;
private EventRunnerGroup ioEventRunnerGroup;
/**
*
* , : 1s
* @param host
* @param port
* @param readTimeout
*/
public SocketContext(String host,int port,int readTimeout) {
init(host, port, readTimeout, sendTimeout, this.idleInterval);
}
/**
*
* : 1s
* @param host
* @param port
* @param readTimeout , :
* @param idleInterval
*/
public SocketContext(String host,int port, int readTimeout, int idleInterval) {
init(host, port, readTimeout, sendTimeout, idleInterval);
}
/**
*
* @param host
* @param port
* @param readTimeout , :
* @param sendTimeout , :
* @param idleInterval
*/
public SocketContext(String host,int port,int readTimeout, int sendTimeout, int idleInterval) {
init(host, port, readTimeout, sendTimeout, idleInterval);
}
private void init(String host,int port,int readTimeout, int sendTimeout, int idleInterval){
this.host = host;
this.port = port;
this.readTimeout = readTimeout;
this.sendTimeout = sendTimeout;
this.idleInterval = idleInterval;
connectModel = null;
filterChain = new Chain<IoFilter>();
this.reciveFilterChain = (Chain<IoFilter>) filterChain.clone();
this.sendFilterChain = (Chain<IoFilter>) filterChain.clone();
this.messageSplitter = new TransferSplitter();
this.handler = new SynchronousHandler();
}
public EventRunnerGroup getAcceptEventRunnerGroup() {
return acceptEventRunnerGroup;
}
public void setAcceptEventRunnerGroup(EventRunnerGroup acceptEventRunnerGroup) {
this.acceptEventRunnerGroup = acceptEventRunnerGroup;
}
public EventRunnerGroup getIoEventRunnerGroup() {
return ioEventRunnerGroup;
}
public void setIoEventRunnerGroup(EventRunnerGroup ioEventRunnerGroup) {
this.ioEventRunnerGroup = ioEventRunnerGroup;
}
protected void initSSL(IoSession session) throws SSLException {
if (sslManager != null && connectModel == ConnectModel.SERVER) {
sslManager.createServerSSLParser(session);
} else if (sslManager != null && connectModel == ConnectModel.CLIENT) {
sslManager.createClientSSLParser(session);
}
}
/**
*
* @param parentSocketContext socket
*/
protected void copyFrom(SocketContext parentSocketContext){
this.readTimeout = parentSocketContext.readTimeout;
this.sendTimeout = parentSocketContext.sendTimeout;
this.handler = parentSocketContext.handler;
this.filterChain = (Chain<IoFilter>) parentSocketContext.filterChain;
this.reciveFilterChain = (Chain<IoFilter>) filterChain.clone();
this.sendFilterChain = (Chain<IoFilter>) filterChain.clone();
this.messageSplitter = parentSocketContext.messageSplitter;
this.sslManager = parentSocketContext.sslManager;
this.readBufferSize = parentSocketContext.readBufferSize;
this.sendBufferSize = parentSocketContext.sendBufferSize;
this.idleInterval = parentSocketContext.idleInterval;
this.acceptEventRunnerGroup = parentSocketContext.acceptEventRunnerGroup;
this.ioEventRunnerGroup = parentSocketContext.ioEventRunnerGroup;
}
/**
*
* @return , :
*/
public int getIdleInterval() {
return idleInterval;
}
/**
*
* @param idleInterval , :
*/
public abstract void setIdleInterval(int idleInterval);
/**
* Socket Option
*
* @param name SocketOption, :AsynchronousSocketChannel.setOption
* @param value SocketOption
* @param <T>
* @throws IOException IO
*/
public abstract <T> void setOption(SocketOption<T> name, T value) throws IOException;
/**
* SocketChannel
* @return SocketChannel
*/
public abstract C socketChannel();
public long getLastReadTime() {
return lastReadTime;
}
public void updateLastTime() {
if(SocketContext.CHECK_TIMEOUT) {
this.lastReadTime = System.currentTimeMillis();
}
}
public boolean isTimeOut(){
if(CHECK_TIMEOUT) {
return false;
} else {
return (System.currentTimeMillis() - lastReadTime) >= readTimeout;
}
}
/**
*
* @return
*/
public int getReadBufferSize() {
return readBufferSize;
}
/**
*
* @param readBufferSize
*/
public void setReadBufferSize(int readBufferSize) {
this.readBufferSize = readBufferSize;
}
/**
*
* @return
*/
public int getSendBufferSize() {
return sendBufferSize;
}
/**
*
* @param sendBufferSize
*/
public void setSendBufferSize(int sendBufferSize) {
this.sendBufferSize = sendBufferSize;
}
public boolean isRegister() {
return isRegister;
}
protected void setRegister(boolean register) {
isRegister = register;
}
protected SocketContext() {
}
/**
* SSL
* @return SSL
*/
public SSLManager getSSLManager() {
return sslManager;
}
/**
* SSL
* @param sslManager SSL
*/
public void setSSLManager(SSLManager sslManager) {
if(this.sslManager==null){
this.sslManager = sslManager;
}
}
/**
*
* @return
*/
public String getHost() {
return host;
}
/**
*
* @return
*/
public int getPort() {
return port;
}
/**
*
* @return
*/
public int getReadTimeout() {
return readTimeout;
}
public int getSendTimeout(){
return sendTimeout;
}
/**
*
* @return ConnectModel.CLIENT,ConnectModel.LISTENER, ConnectModel.SERVER
*/
public ConnectModel getConnectModel() {
return connectModel;
}
/**
*
* @return ConnectType.TCP / ConnectType.UDP
*/
public ConnectType getConnectType() {
return connectType;
}
/**
*
* @return
*/
public IoHandler handler(){
return this.handler;
}
/**
*
* @param handler
*/
public void handler(IoHandler handler){
this.handler = handler;
isSynchronous = handler instanceof SynchronousHandler;
}
/**
*
* @return
*/
public Chain<IoFilter> filterChain(){
return this.filterChain;
}
protected Chain<IoFilter> getReciveFilterChain() {
return reciveFilterChain;
}
protected Chain<IoFilter> getSendFilterChain() {
return sendFilterChain;
}
/**
*
* @return
*/
public MessageSplitter messageSplitter() {
return this.messageSplitter;
}
/**
*
* @param messageSplitter
*/
public void messageSplitter(MessageSplitter messageSplitter) {
this.messageSplitter = messageSplitter;
}
public abstract S getSession();
/**
*
*
* @throws IOException IO
*/
public abstract void start() throws IOException;
/**
*
*
*
* @exception IOException IO
*/
public abstract void syncStart() throws IOException;
/**
* Accept Socket
* @throws IOException IO
*/
protected abstract void acceptStart() throws IOException;
/**
*
* @return true:,false:
*/
public abstract boolean isOpen();
/**
*
* @return true:,false:
*/
public abstract boolean isConnected();
/**
*
* @return
*/
public abstract boolean close();
/**
* , SSL ,
*/
public void waitConnect() {
try {
TEnv.wait(readTimeout, ()->!isRegister);
// SSL
if(getSession().isSSLMode()) {
getSession().getSSLParser().waitHandShakeDone();
}
}catch(Exception e){
Logger.error(e);
close();
}
}
/**
* SocketSelector
* @param ops
*/
public void bindToSocketSelector(int ops) {
EventRunner eventRunner = null;
if(connectModel == ConnectModel.LISTENER) {
if(acceptEventRunnerGroup == null) {
acceptEventRunnerGroup = getCommonAcceptEventRunnerGroup();
}
eventRunner = acceptEventRunnerGroup.choseEventRunner();
} else {
if(ioEventRunnerGroup == null) {
ioEventRunnerGroup = getCommonIoEventRunnerGroup();
}
eventRunner = ioEventRunnerGroup.choseEventRunner();
}
SocketSelector socketSelector = (SocketSelector)eventRunner.attachment();
socketSelector.register(this, ops);
}
/**
* Socket
*/
public static void gracefulShutdown() {
if(COMMON_ACCEPT_EVENT_RUNNER_GROUP!=null) {
ThreadPool.gracefulShutdown(COMMON_ACCEPT_EVENT_RUNNER_GROUP.getThreadPool());
}
if(COMMON_IO_EVENT_RUNNER_GROUP!=null) {
ThreadPool.gracefulShutdown(COMMON_IO_EVENT_RUNNER_GROUP.getThreadPool());
}
Logger.info("All IO thread is shutdown");
}
}
|
package org.voovan.network;
import org.voovan.network.handler.SynchronousHandler;
import org.voovan.network.messagesplitter.TransferSplitter;
import org.voovan.tools.TObject;
import org.voovan.tools.TPerformance;
import org.voovan.tools.collection.Chain;
import org.voovan.tools.buffer.TByteBuffer;
import org.voovan.tools.TEnv;
import org.voovan.tools.event.EventRunner;
import org.voovan.tools.event.EventRunnerGroup;
import org.voovan.tools.log.Logger;
import org.voovan.tools.threadpool.ThreadPool;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.SocketOption;
import java.nio.channels.SelectableChannel;
import java.util.concurrent.ThreadPoolExecutor;
public abstract class SocketContext<C extends SelectableChannel, S extends IoSession> {
public static int ACCEPT_THREAD_SIZE = Integer.valueOf(TObject.nullDefault(System.getProperty("AcceptThreadSize"),"1"));
public static ThreadPoolExecutor ACCEPT_THREAD_POOL = ThreadPool.createThreadPool("ACCEPT", ACCEPT_THREAD_SIZE, ACCEPT_THREAD_SIZE, 60*1000, true, 10);
public static EventRunnerGroup ACCEPT_EVENT_RUNNER_GROUP= new EventRunnerGroup(ACCEPT_THREAD_POOL, ACCEPT_THREAD_SIZE, (obj)->{
try {
//Accept
return new SocketSelector(obj, false);
} catch (IOException e) {
e.printStackTrace();
}
return null;
});
public static int IO_THREAD_SIZE = Integer.valueOf(TObject.nullDefault(System.getProperty("IoThreadSize"), TPerformance.getProcessorCount()+""));
public static ThreadPoolExecutor IO_THREAD_POOL = ThreadPool.createThreadPool("IO", IO_THREAD_SIZE, IO_THREAD_SIZE, 60*1000, true, 9);
public static EventRunnerGroup IO_EVENT_RUNNER_GROUP= new EventRunnerGroup(IO_THREAD_POOL, IO_THREAD_SIZE, (obj)->{
try {
return new SocketSelector(obj, true);
} catch (IOException e) {
e.printStackTrace();
}
return null;
});
static {
System.out.println("[SOCKET] IO_THREAD_SIZE: " + IO_THREAD_SIZE);
}
protected String host;
protected int port;
protected int readTimeout;
protected int sendTimeout = 1000;
protected IoHandler handler;
protected Chain<IoFilter> filterChain;
protected MessageSplitter messageSplitter;
protected SSLManager sslManager;
protected ConnectModel connectModel;
protected int readBufferSize = TByteBuffer.DEFAULT_BYTE_BUFFER_SIZE;
protected int sendBufferSize = TByteBuffer.DEFAULT_BYTE_BUFFER_SIZE;
protected int idleInterval = 0;
protected long lastReadTime = System.currentTimeMillis();
protected int readRecursionDepth = 1;
private boolean isRegister = false;
protected boolean isSynchronous = true;
/**
*
* , : 1s
* @param host
* @param port
* @param readTimeout
*/
public SocketContext(String host,int port,int readTimeout) {
init(host, port, readTimeout, sendTimeout, this.idleInterval);
}
/**
*
* : 1s
* @param host
* @param port
* @param readTimeout , :
* @param idleInterval
*/
public SocketContext(String host,int port, int readTimeout, int idleInterval) {
init(host, port, readTimeout, sendTimeout, idleInterval);
}
/**
*
* @param host
* @param port
* @param readTimeout , :
* @param sendTimeout , :
* @param idleInterval
*/
public SocketContext(String host,int port,int readTimeout, int sendTimeout, int idleInterval) {
init(host, port, readTimeout, sendTimeout, idleInterval);
}
private void init(String host,int port,int readTimeout, int sendTimeout, int idleInterval){
this.host = host;
this.port = port;
this.readTimeout = readTimeout;
this.sendTimeout = sendTimeout;
this.idleInterval = idleInterval;
connectModel = null;
filterChain = new Chain<IoFilter>();
this.messageSplitter = new TransferSplitter();
this.handler = new SynchronousHandler();
}
protected void initSSL(IoSession session) throws SSLException {
if (sslManager != null && connectModel == ConnectModel.SERVER) {
sslManager.createServerSSLParser(session);
} else if (sslManager != null && connectModel == ConnectModel.CLIENT) {
sslManager.createClientSSLParser(session);
}
}
/**
*
* @param parentSocketContext socket
*/
protected void copyFrom(SocketContext parentSocketContext){
this.readTimeout = parentSocketContext.readTimeout;
this.sendTimeout = parentSocketContext.sendTimeout;
this.handler = parentSocketContext.handler;
this.filterChain = parentSocketContext.filterChain;
this.messageSplitter = parentSocketContext.messageSplitter;
this.sslManager = parentSocketContext.sslManager;
this.readBufferSize = parentSocketContext.readBufferSize;
this.sendBufferSize = parentSocketContext.sendBufferSize;
this.idleInterval = parentSocketContext.idleInterval;
this.readRecursionDepth = parentSocketContext.readRecursionDepth;
}
/**
*
* @return , :
*/
public int getIdleInterval() {
return idleInterval;
}
/**
*
* @param idleInterval , :
*/
public abstract void setIdleInterval(int idleInterval);
/**
* Socket Option
*
* @param name SocketOption, :AsynchronousSocketChannel.setOption
* @param value SocketOption
* @param <T>
* @throws IOException IO
*/
public abstract <T> void setOption(SocketOption<T> name, T value) throws IOException;
/**
* SocketChannel
* @return SocketChannel
*/
public abstract C socketChannel();
public long getLastReadTime() {
return lastReadTime;
}
public void updateLastReadTime() {
this.lastReadTime = System.currentTimeMillis();
}
public boolean isReadTimeOut(){
return (System.currentTimeMillis() - lastReadTime) >= readTimeout;
}
/**
*
* @return
*/
public int getReadBufferSize() {
return readBufferSize;
}
/**
*
* @param readBufferSize
*/
public void setReadBufferSize(int readBufferSize) {
this.readBufferSize = readBufferSize;
}
/**
*
* @return
*/
public int getSendBufferSize() {
return sendBufferSize;
}
/**
*
* @param sendBufferSize
*/
public void setSendBufferSize(int sendBufferSize) {
this.sendBufferSize = sendBufferSize;
}
/**
*
* @return
*/
public int getReadRecursionDepth() {
return readRecursionDepth;
}
/**
*
* @param readRecursionDepth
*/
public void setReadRecursionDepth(int readRecursionDepth) {
this.readRecursionDepth = readRecursionDepth;
}
public boolean isRegister() {
return isRegister;
}
protected void setRegister(boolean register) {
isRegister = register;
}
protected SocketContext() {
filterChain = new Chain<IoFilter>();
}
/**
* SSL
* @return SSL
*/
public SSLManager getSSLManager() {
return sslManager;
}
/**
* SSL
* @param sslManager SSL
*/
public void setSSLManager(SSLManager sslManager) {
if(this.sslManager==null){
this.sslManager = sslManager;
}
}
/**
*
* @return
*/
public String getHost() {
return host;
}
/**
*
* @return
*/
public int getPort() {
return port;
}
/**
*
* @return
*/
public int getReadTimeout() {
return readTimeout;
}
public int getSendTimeout(){
return sendTimeout;
}
/**
*
* @return
*/
public ConnectModel getConnectModel() {
return connectModel;
}
/**
*
* @return
*/
public IoHandler handler(){
return this.handler;
}
/**
*
* @param handler
*/
public void handler(IoHandler handler){
this.handler = handler;
isSynchronous = handler instanceof SynchronousHandler;
}
/**
*
* @return
*/
public Chain<IoFilter> filterChain(){
return this.filterChain;
}
/**
*
* @return
*/
public MessageSplitter messageSplitter() {
return this.messageSplitter;
}
/**
*
* @param messageSplitter
*/
public void messageSplitter(MessageSplitter messageSplitter) {
this.messageSplitter = messageSplitter;
}
public abstract S getSession();
/**
*
*
* @throws IOException IO
*/
public abstract void start() throws IOException;
/**
*
*
*
* @exception IOException IO
*/
public abstract void syncStart() throws IOException;
/**
* Accept Socket
* @throws IOException IO
*/
protected abstract void acceptStart() throws IOException;
/**
*
* @return true:,false:
*/
public abstract boolean isOpen();
/**
*
* @return true:,false:
*/
public abstract boolean isConnected();
/**
*
* @return
*/
public abstract boolean close();
/**
* , SSL ,
*/
public void waitConnect() {
try {
TEnv.wait(readTimeout, ()->!isRegister);
// SSL
if(getSession().isSSLMode()) {
getSession().getSSLParser().waitHandShakeDone();
}
}catch(Exception e){
Logger.error(e);
close();
}
}
/**
* SocketSelector
* @param ops
*/
public void bindToSocketSelector(int ops) {
EventRunner eventRunner = null;
if(connectModel == ConnectModel.LISTENER) {
eventRunner = ACCEPT_EVENT_RUNNER_GROUP.choseEventRunner();
} else {
eventRunner = IO_EVENT_RUNNER_GROUP.choseEventRunner();
}
SocketSelector socketSelector = (SocketSelector)eventRunner.attachment();
socketSelector.register(this, ops);
}
}
|
package gov.nih.nci.calab.ui.core;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.characterization.CharacterizationFileBean;
import gov.nih.nci.calab.dto.characterization.ConditionBean;
import gov.nih.nci.calab.dto.characterization.ControlBean;
import gov.nih.nci.calab.dto.characterization.DatumBean;
import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;
/**
* This action serves as the base action for all characterization related action
* classes. It includes common operations such as download, updateManufacturers.
*
* @author pansu
*/
/* CVS $Id: BaseCharacterizationAction.java,v 1.3 2006-11-19 20:31:16 zengje Exp $ */
public abstract class BaseCharacterizationAction extends AbstractDispatchAction {
/**
* clear session data from the input form
*
* @param session
* @param theForm
* @param mapping
* @throws Exception
*/
protected abstract void clearMap(HttpSession session,
DynaValidatorForm theForm, ActionMapping mapping) throws Exception;
/**
* Pepopulate data for the form
*
* @param request
* @param theForm
* @throws Exception
*/
protected abstract void initSetup(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception;
/**
* Set the appropriate type of characterization bean in the form
* from the chararacterization domain obj.
* @param theForm
* @param aChar
* @throws Exception
*/
protected abstract void setFormCharacterizationBean(DynaValidatorForm theForm,
Characterization aChar) throws Exception;
/**
* Set up the input form for adding new characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
HttpSession session = request.getSession();
clearMap(session, theForm, mapping);
initSetup(request, theForm);
return mapping.getInputForward();
}
/**
* Set request attributes required in load file for different types of characterizations
* @param request
*/
protected abstract void setLoadFileRequest(HttpServletRequest request);
/**
* Set up the form for updating existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String characterizationId = (String) theForm.get("characterizationId");
SearchNanoparticleService service = new SearchNanoparticleService();
Characterization aChar = service
.getCharacterizationAndTableBy(characterizationId);
if (aChar == null)
// aChar = service.getCharacterizationBy(compositionId);
aChar = service.getCharacterizationAndTableBy(characterizationId);
HttpSession session = request.getSession();
// clear session data from the input forms
clearMap(session, theForm, mapping);
theForm.set("characterizationId", characterizationId);
int fileNumber = 0;
for (DerivedBioAssayData obj : aChar.getDerivedBioAssayDataCollection()) {
if (obj.getFile() != null) {
CharacterizationFileBean fileBean = new CharacterizationFileBean();
fileBean.setName(obj.getFile().getFilename());
fileBean.setPath(obj.getFile().getPath());
fileBean.setId((obj.getFile().getId().toString()));
request.getSession().setAttribute(
"characterizationFile" + fileNumber, fileBean);
} else {
request.getSession().removeAttribute(
"characterizationFile" + fileNumber);
}
fileNumber++;
}
if (aChar.getInstrument() != null) {
String instrumentType = aChar.getInstrument().getInstrumentType()
.getName();
InitSessionSetup.getInstance().setManufacturerPerType(session,
instrumentType);
session.setAttribute("selectedInstrumentType", instrumentType);
}
initSetup(request, theForm);
setFormCharacterizationBean(theForm, aChar);
return mapping.getInputForward();
}
/**
* Prepare the form for viewing existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return setupUpdate(mapping, form, request, response);
}
/**
* Load file action for characterization file loading.
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward loadFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleName = (String) theForm.get("particleName");
String fileNumber = (String) theForm.get("fileNumber");
request.setAttribute("particleName", particleName);
request.setAttribute("fileNumber", fileNumber);
SubmitNanoparticleService service = new SubmitNanoparticleService();
List<CharacterizationFileBean> files = service
.getAllRunFiles(particleName);
request.setAttribute("allRunFiles", files);
setLoadFileRequest(request);
return mapping.findForward("loadFile");
}
/**
* Download action to handle characterization file download and viewing
*
* @param
* @return
*/
public ActionForward download(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String fileId = request.getParameter("fileId");
SubmitNanoparticleService service = new SubmitNanoparticleService();
CharacterizationFileBean fileBean = service.getFile(fileId);
String fileRoot = PropertyReader.getProperty(
CalabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir");
File dFile = new File(fileRoot + File.separator + fileBean.getPath());
if (dFile.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename="
+ fileBean.getName());
response.setHeader("Cache-Control", "no-cache");
java.io.InputStream in = new FileInputStream(dFile);
java.io.OutputStream out = response.getOutputStream();
byte[] bytes = new byte[32768];
int numRead = 0;
while ((numRead = in.read(bytes)) > 0) {
out.write(bytes, 0, numRead);
}
out.close();
} else {
throw new Exception("ERROR: file not found.");
}
return null;
}
/**
* Update multiple children on the same form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward updateManufacturers(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
HttpSession session = request.getSession();
CharacterizationBean aChar = (CharacterizationBean) theForm
.get("achar");
if (aChar.getInstrument() != null) {
String type = aChar.getInstrument().getType();
session.setAttribute("selectedInstrumentType", type);
// type);
InitSessionSetup.getInstance().setManufacturerPerType(session,
aChar.getInstrument().getType());
}
return mapping.getInputForward();
}
public void updateCharacterizationTables(CharacterizationBean achar) {
String numberOfCharacterizationTables = achar
.getNumberOfDerivedBioAssayData();
int tableNum = Integer.parseInt(numberOfCharacterizationTables);
List<DerivedBioAssayDataBean> origTables = achar
.getDerivedBioAssayData();
int origNum = (origTables == null) ? 0 : origTables.size();
List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>();
// create new ones
if (origNum == 0) {
for (int i = 0; i < tableNum; i++) {
DerivedBioAssayDataBean table = new DerivedBioAssayDataBean();
tables.add(table);
}
}
// use keep original table info
else if (tableNum <= origNum) {
for (int i = 0; i < tableNum; i++) {
tables.add((DerivedBioAssayDataBean) origTables.get(i));
}
} else {
for (int i = 0; i < origNum; i++) {
tables.add((DerivedBioAssayDataBean) origTables.get(i));
}
for (int i = origNum; i < tableNum; i++) {
tables.add(new DerivedBioAssayDataBean());
}
}
achar.setDerivedBioAssayData(tables);
}
/**
* Update multiple children on the same form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public void addConditions(CharacterizationBean achar, String index) {
ControlBean control = null;
int tableIndex = new Integer(index).intValue();
DerivedBioAssayDataBean derivedBioAssayData = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayData().get(tableIndex);
DatumBean datum = (DatumBean) derivedBioAssayData.getDatumList().get(0);
if (datum.getControl() != null) {
datum.setControl(control);
}
List<ConditionBean> conditions = new ArrayList<ConditionBean>();
ConditionBean particleConcentrationCondition = new ConditionBean();
particleConcentrationCondition.setType("Particle Concentration");
conditions.add(particleConcentrationCondition);
ConditionBean molecularConcentrationCondition = new ConditionBean();
molecularConcentrationCondition.setType("Molecular Concentration");
molecularConcentrationCondition.setValueUnit("uM");
conditions.add(molecularConcentrationCondition);
datum.setConditionList(conditions);
}
/**
* Update multiple children on the same form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public void addControl(CharacterizationBean achar, String index) {
List<ConditionBean> conditionList = null;
int tableIndex = new Integer(index).intValue();
DerivedBioAssayDataBean derivedBioAssayData = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayData().get(tableIndex);
DatumBean datum = (DatumBean) derivedBioAssayData.getDatumList().get(0);
if (datum.getConditionList() != null) {
datum.setConditionList(conditionList);
}
ControlBean control = new ControlBean();
datum.setControl(control);
}
/**
* Update multiple children on the same form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public void updateConditions(CharacterizationBean achar, String index) {
int tableIndex = new Integer(index).intValue();
DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayData().get(tableIndex);
DatumBean datumBean = (DatumBean) (derivedBioAssayDataBean
.getDatumList().get(0));
String numberOfConditions = datumBean.getNumberOfConditions();
int conditionNum = Integer.parseInt(numberOfConditions);
List<ConditionBean> origConditions = datumBean.getConditionList();
int origNum = (origConditions == null) ? 0 : origConditions.size();
List<ConditionBean> conditions = new ArrayList<ConditionBean>();
// create new ones
if (origNum == 0) {
for (int i = 0; i < conditionNum; i++) {
ConditionBean condition = new ConditionBean();
conditions.add(condition);
}
}
// use keep original table info
else if (conditionNum <= origNum) {
for (int i = 0; i < conditionNum; i++) {
conditions.add((ConditionBean) origConditions.get(i));
}
} else {
for (int i = 0; i < origNum; i++) {
conditions.add((ConditionBean) origConditions.get(i));
}
for (int i = origNum; i < conditionNum; i++) {
conditions.add(new ConditionBean());
}
}
datumBean.setConditionList(conditions);
}
public boolean loginRequired() {
return true;
}
}
|
package gov.nih.nci.calab.ui.core;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.characterization.CharacterizationSummaryBean;
import gov.nih.nci.calab.dto.characterization.DatumBean;
import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean;
import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean;
import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean;
import gov.nih.nci.calab.dto.characterization.physical.ShapeBean;
import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean;
import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean;
import gov.nih.nci.calab.dto.common.LabFileBean;
import gov.nih.nci.calab.dto.common.ProtocolFileBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.particle.ParticleBean;
import gov.nih.nci.calab.exception.CalabException;
import gov.nih.nci.calab.service.common.FileService;
import gov.nih.nci.calab.service.particle.NanoparticleCharacterizationService;
import gov.nih.nci.calab.service.particle.NanoparticleService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.ui.particle.InitParticleSetup;
import gov.nih.nci.calab.ui.protocol.InitProtocolSetup;
import gov.nih.nci.calab.ui.security.InitSecuritySetup;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
/**
* This action serves as the base action for all characterization related action
* classes. It includes common operations such as download, updateManufacturers.
*
* @author pansu
*/
/*
* CVS $Id: BaseCharacterizationAction.java,v 1.73 2007/08/02 21:41:47 zengje
* Exp $
*/
public abstract class BaseCharacterizationAction extends AbstractDispatchAction {
protected CharacterizationBean prepareCreate(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
HttpSession session = request.getSession();
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
// validate that characterization file/derived data can't be empty
for (DerivedBioAssayDataBean derivedDataFileBean : charBean
.getDerivedBioAssayDataList()) {
if (derivedDataFileBean.getType().length() == 0
&& derivedDataFileBean.getCategories().length == 0
&& derivedDataFileBean.getDisplayName().length() == 0
&& derivedDataFileBean.getDatumList().size() == 0) {
throw new RuntimeException(
"has an empty section for characterization file/derived data. Please remove it prior to saving.");
}
}
for (DerivedBioAssayDataBean derivedDataFileBean : charBean
.getDerivedBioAssayDataList()) {
Map<String, Integer> uniqueDatumMap = new HashMap<String, Integer>();
for (DatumBean datumBean : derivedDataFileBean.getDatumList()) {
// validate that neither name nor value can be empty
if (datumBean.getName().length() == 0
|| datumBean.getValue().length() == 0) {
throw new RuntimeException(
"Derived data name and value can't be empty.");
}
if (datumBean.getStatisticsType().equalsIgnoreCase("boolean")) {
if (!datumBean.getValue().equalsIgnoreCase("true")
&& !datumBean.getValue().equalsIgnoreCase("false")
&& !datumBean.getValue().equalsIgnoreCase("yes")
&& !datumBean.getValue().equalsIgnoreCase("no")) {
throw new RuntimeException(
"The datum value for boolean type should be 'True'/'False' or 'Yes'/'No'.");
}
} else {
if (!StringUtils.isDouble(datumBean.getValue())
&& !StringUtils.isInteger(datumBean.getValue())) {
throw new RuntimeException(
"The datum value should be a number.");
}
}
// validate derived data has unique name, statistics type and
// category
String uniqueStr = datumBean.getName() + ":"
+ datumBean.getStatisticsType() + ":"
+ datumBean.getCategory();
if (uniqueDatumMap.get(uniqueStr) != null) {
throw new RuntimeException(
"no two derived data can have the same name, statistics type and category.");
} else {
uniqueDatumMap.put(uniqueStr, 1);
}
}
}
// set createdBy and createdDate for the characterization
UserBean user = (UserBean) session.getAttribute("user");
Date date = new Date();
charBean.setCreatedBy(user.getLoginName());
charBean.setCreatedDate(date);
ParticleBean particle = (ParticleBean) theForm.get("particle");
charBean.setParticle(particle);
return charBean;
}
protected void postCreate(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
ParticleBean particle = (ParticleBean) theForm.get("particle");
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
// save new lookup up types in the database definition tables.
NanoparticleCharacterizationService service = new NanoparticleCharacterizationService();
service.addNewCharacterizationDataDropdowns(charBean, charBean
.getName());
request.getSession().setAttribute("newCharacterizationCreated", "true");
request.getSession().setAttribute("newCharacterizationSourceCreated",
"true");
request.getSession().setAttribute("newInstrumentCreated", "true");
request.getSession().setAttribute("newCharacterizationFileTypeCreated",
"true");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
request.setAttribute("theParticle", particle);
}
protected CharacterizationBean[] prepareCopy(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
ParticleBean particle = (ParticleBean) theForm.get("particle");
String[] otherParticles = (String[]) theForm.get("otherParticles");
Boolean copyData = (Boolean) theForm.get("copyData");
CharacterizationBean[] charBeans = new CharacterizationBean[otherParticles.length];
NanoparticleService service = new NanoparticleService();
int i = 0;
for (String particleName : otherParticles) {
CharacterizationBean newCharBean = charBean.copy(copyData
.booleanValue());
// overwrite particle and particle type;
newCharBean.getParticle().setSampleName(particleName);
ParticleBean otherParticle = service.getParticleBy(particleName);
newCharBean.getParticle().setSampleType(
otherParticle.getSampleType());
// reset view title
String timeStamp = StringUtils.convertDateToString(new Date(),
"MMddyyHHmmssSSS");
String autoTitle = CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX
+ timeStamp;
newCharBean.setViewTitle(autoTitle);
List<DerivedBioAssayDataBean> dataList = newCharBean
.getDerivedBioAssayDataList();
// replace particleName in path and uri with new particleName
for (DerivedBioAssayDataBean derivedBioAssayData : dataList) {
String origUri = derivedBioAssayData.getUri();
if (origUri != null)
derivedBioAssayData.setUri(origUri.replace(particle
.getSampleName(), particleName));
}
charBeans[i] = newCharBean;
i++;
}
return charBeans;
}
/**
* clear session data from the input form
*
* @param session
* @param theForm
* @param mapping
* @throws Exception
*/
protected void clearMap(HttpSession session, DynaValidatorForm theForm)
throws Exception {
// reset achar and otherParticles
theForm.set("otherParticles", new String[0]);
theForm.set("copyData", false);
theForm.set("achar", new CharacterizationBean());
theForm.set("morphology", new MorphologyBean());
theForm.set("shape", new ShapeBean());
theForm.set("surface", new SurfaceBean());
theForm.set("solubility", new SolubilityBean());
theForm.set("cytotoxicity", new CytotoxicityBean());
cleanSessionAttributes(session);
}
/**
* Prepopulate data for the input form
*
* @param request
* @param theForm
* @throws Exception
*/
protected void initSetup(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
HttpSession session = request.getSession();
clearMap(session, theForm);
UserBean user = (UserBean) request.getSession().getAttribute("user");
InitParticleSetup.getInstance()
.setAllCharacterizationDropdowns(session);
// set up particle
String particleId = request.getParameter("particleId");
if (particleId != null) {
NanoparticleService particleService = new NanoparticleService();
ParticleBean particle = particleService.getGeneralInfo(particleId);
theForm.set("particle", particle);
request.setAttribute("theParticle", particle);
// set up other particles from the same source
SortedSet<String> allOtherParticleNames = particleService
.getOtherParticles(particle.getSampleSource(), particle
.getSampleName(), user);
session
.setAttribute("allOtherParticleNames",
allOtherParticleNames);
InitParticleSetup.getInstance().setSideParticleMenu(request,
particleId);
} else {
throw new RuntimeException("Particle ID is required.");
}
InitSessionSetup.getInstance().setApplicationOwner(session);
InitParticleSetup.getInstance().setAllInstruments(session);
InitParticleSetup.getInstance().setAllDerivedDataFileTypes(session);
InitParticleSetup.getInstance().setAllPhysicalDropdowns(session);
InitParticleSetup.getInstance().setAllInvitroDropdowns(session);
// set characterization
String submitType = (String) request.getParameter("submitType");
String characterizationId = request.getParameter("characterizationId");
if (characterizationId != null) {
NanoparticleCharacterizationService charService = new NanoparticleCharacterizationService();
CharacterizationBean charBean = charService
.getCharacterizationBy(characterizationId);
if (charBean == null) {
throw new RuntimeException(
"This characterization no longer exists in the database. Please log in again to refresh.");
}
theForm.set("achar", charBean);
}
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
if (achar != null && submitType != null) {
achar.setName(submitType);
InitParticleSetup.getInstance()
.setAllCharacterizationMeasureUnitsTypes(session,
submitType);
InitParticleSetup.getInstance().setDerivedDatumNames(session,
achar.getName());
InitProtocolSetup.getInstance().setProtocolFilesByCharName(session,
achar.getName());
UserService userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
// set up characterization files visibility, and whether file is an
// image
for (DerivedBioAssayDataBean fileBean : achar
.getDerivedBioAssayDataList()) {
boolean status = userService.checkReadPermission(user, fileBean
.getId());
if (status) {
List<String> accessibleGroups = userService
.getAccessibleGroups(fileBean.getId(),
CaNanoLabConstants.CSM_READ_ROLE);
String[] visibilityGroups = accessibleGroups
.toArray(new String[0]);
fileBean.setVisibilityGroups(visibilityGroups);
fileBean.setHidden(false);
} else {
fileBean.setHidden(true);
}
boolean imageStatus = false;
if (fileBean.getType().length() > 0
&& fileBean.getType().equalsIgnoreCase("Graph")
|| fileBean.getType().equalsIgnoreCase("Image")) {
imageStatus = true;
} else if (fileBean.getName() != null) {
imageStatus = StringUtils.isImgFileExt(fileBean.getName());
}
fileBean.setImage(imageStatus);
}
// set up protocol file visibility
ProtocolFileBean protocolFileBean = achar.getProtocolFileBean();
if (protocolFileBean != null) {
boolean status = false;
if (protocolFileBean.getId() != null) {
status = userService.checkReadPermission(user,
protocolFileBean.getId());
}
if (status) {
protocolFileBean.setHidden(false);
} else {
protocolFileBean.setHidden(true);
}
}
}
}
/**
* Clean the session attribture
*
* @param sessioin
* @throws Exception
*/
protected void cleanSessionAttributes(HttpSession session) throws Exception {
for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
String element = (String) e.nextElement();
if (element.startsWith(CaNanoLabConstants.CHARACTERIZATION_FILE)) {
session.removeAttribute(element);
}
}
}
/**
* Set up the input form for adding new characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
return mapping.getInputForward();
}
public ActionForward input(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
// update editable dropdowns
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
ShapeBean shape = (ShapeBean) theForm.get("shape");
MorphologyBean morphology = (MorphologyBean) theForm.get("morphology");
CytotoxicityBean cyto = (CytotoxicityBean) theForm.get("cytotoxicity");
SolubilityBean solubility = (SolubilityBean) theForm.get("solubility");
HttpSession session = request.getSession();
updateAllCharEditables(session, achar);
updateShapeEditable(session, shape);
updateMorphologyEditable(session, morphology);
updateCytotoxicityEditable(session, cyto);
updateSolubilityEditable(session, solubility);
// updateSurfaceEditable(session, surface);
return mapping.findForward("setup");
}
/**
* Set up the form for updating existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
// set characterizations with additional information
if (charBean instanceof ShapeBean) {
theForm.set("shape", charBean);
} else if (charBean instanceof MorphologyBean) {
theForm.set("morphology", charBean);
} else if (charBean instanceof SolubilityBean) {
theForm.set("solubility", charBean);
} else if (charBean instanceof SurfaceBean) {
theForm.set("surface", charBean);
} else if (charBean instanceof SolubilityBean) {
theForm.set("solubility", charBean);
} else if (charBean instanceof CytotoxicityBean) {
theForm.set("cytotoxicity", charBean);
}
return mapping.findForward("setup");
}
public ActionForward detailView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
return mapping.findForward("detailView");
}
public ActionForward summaryView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
String submitType = request.getParameter("submitType");
ParticleBean particle = (ParticleBean) theForm.get("particle");
NanoparticleCharacterizationService service = new NanoparticleCharacterizationService();
List<CharacterizationSummaryBean> charSummaryBeans = service
.getParticleCharacterizationSummaryByName(submitType, particle
.getSampleId());
if (charSummaryBeans == null) {
throw new Exception(
"There are no such characterizations in the database.");
}
// set data labels and file visibility, and whether file is an image
UserService userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
UserBean user = (UserBean) request.getSession().getAttribute("user");
SortedSet<String> datumLabels = new TreeSet<String>();
for (CharacterizationSummaryBean summaryBean : charSummaryBeans) {
Map<String, String> datumMap = summaryBean.getDatumMap();
if (datumMap != null && !datumMap.isEmpty()) {
datumLabels.addAll(datumMap.keySet());
}
DerivedBioAssayDataBean fileBean = summaryBean.getCharFile();
boolean status = userService.checkReadPermission(user, fileBean
.getId());
if (status) {
List<String> accessibleGroups = userService
.getAccessibleGroups(fileBean.getId(),
CaNanoLabConstants.CSM_READ_ROLE);
String[] visibilityGroups = accessibleGroups
.toArray(new String[0]);
fileBean.setVisibilityGroups(visibilityGroups);
fileBean.setHidden(false);
} else {
fileBean.setHidden(true);
}
boolean imageStatus = false;
if (fileBean.getType().length() > 0
&& fileBean.getType().equalsIgnoreCase("Graph")
|| fileBean.getType().equalsIgnoreCase("Image")) {
imageStatus = true;
} else if (fileBean.getName() != null) {
imageStatus = StringUtils.isImgFileExt(fileBean.getName());
}
fileBean.setImage(imageStatus);
}
request.setAttribute("nameCharacterizationSummary", charSummaryBeans);
request.setAttribute("datumLabels", datumLabels);
return mapping.findForward("summaryView");
}
/**
* Load file action for characterization file loading.
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward loadFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
ParticleBean particle = (ParticleBean) theForm.get("particle");
request.setAttribute("loadFileForward", mapping.findForward("setup")
.getPath());
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
int fileNum = Integer.parseInt(request.getParameter("fileNumber"));
DerivedBioAssayDataBean derivedBioAssayDataBean = achar
.getDerivedBioAssayDataList().get(fileNum);
derivedBioAssayDataBean.setParticleName(particle.getSampleName());
derivedBioAssayDataBean.setCharacterizationName(achar.getName());
request.setAttribute("file", derivedBioAssayDataBean);
return mapping.findForward("loadFile");
}
/**
* Download action to handle characterization file download and viewing
*
* @param
* @return
*/
public ActionForward download(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String fileId = request.getParameter("fileId");
FileService service = new FileService();
LabFileBean fileBean = service.getFile(fileId);
String fileRoot = PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir");
File dFile = new File(fileRoot + File.separator + fileBean.getUri());
if (dFile.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename="
+ fileBean.getName());
response.setHeader("cache-control", "Private");
java.io.InputStream in = new FileInputStream(dFile);
java.io.OutputStream out = response.getOutputStream();
byte[] bytes = new byte[32768];
int numRead = 0;
while ((numRead = in.read(bytes)) > 0) {
out.write(bytes, 0, numRead);
}
out.close();
} else {
throw new CalabException(
"File to download doesn't exist on the server");
}
return null;
}
public ActionForward addFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
List<DerivedBioAssayDataBean> origTables = achar
.getDerivedBioAssayDataList();
int origNum = (origTables == null) ? 0 : origTables.size();
List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>();
for (int i = 0; i < origNum; i++) {
tables.add(origTables.get(i));
}
// add a new one
tables.add(new DerivedBioAssayDataBean());
achar.setDerivedBioAssayDataList(tables);
ParticleBean particle = (ParticleBean) theForm.get("particle");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
return input(mapping, form, request, response);
}
public ActionForward removeFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String fileIndexStr = (String) request.getParameter("compInd");
int fileInd = Integer.parseInt(fileIndexStr);
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
List<DerivedBioAssayDataBean> origTables = achar
.getDerivedBioAssayDataList();
int origNum = (origTables == null) ? 0 : origTables.size();
List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>();
for (int i = 0; i < origNum; i++) {
tables.add(origTables.get(i));
}
// remove the one at the index
if (origNum > 0) {
tables.remove(fileInd);
}
achar.setDerivedBioAssayDataList(tables);
ParticleBean particle = (ParticleBean) theForm.get("particle");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
return input(mapping, form, request, response);
}
public ActionForward addData(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
String fileIndexStr = (String) request.getParameter("compInd");
int fileInd = Integer.parseInt(fileIndexStr);
DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayDataList().get(fileInd);
List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList();
int origNum = (origDataList == null) ? 0 : origDataList.size();
List<DatumBean> dataList = new ArrayList<DatumBean>();
for (int i = 0; i < origNum; i++) {
DatumBean dataPoint = (DatumBean) origDataList.get(i);
dataList.add(dataPoint);
}
dataList.add(new DatumBean());
derivedBioAssayDataBean.setDatumList(dataList);
ParticleBean particle = (ParticleBean) theForm.get("particle");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
return input(mapping, form, request, response);
}
public ActionForward removeData(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
String fileIndexStr = (String) request.getParameter("compInd");
int fileInd = Integer.parseInt(fileIndexStr);
String dataIndexStr = (String) request.getParameter("childCompInd");
int dataInd = Integer.parseInt(dataIndexStr);
DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayDataList().get(fileInd);
List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList();
int origNum = (origDataList == null) ? 0 : origDataList.size();
List<DatumBean> dataList = new ArrayList<DatumBean>();
for (int i = 0; i < origNum; i++) {
DatumBean dataPoint = (DatumBean) origDataList.get(i);
dataList.add(dataPoint);
}
if (origNum > 0)
dataList.remove(dataInd);
derivedBioAssayDataBean.setDatumList(dataList);
ParticleBean particle = (ParticleBean) theForm.get("particle");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
return input(mapping, form, request, response);
// return mapping.getInputForward(); this gives an
// IndexOutOfBoundException in the jsp page
}
/**
* Pepopulate data for the form
*
* @param request
* @param theForm
* @throws Exception
*/
public ActionForward deleteConfirmed(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
ParticleBean particle = (ParticleBean) theForm.get("particle");
String charId = request.getParameter("characterizationId");
NanoparticleCharacterizationService service = new NanoparticleCharacterizationService();
service.deleteCharacterizations(new String[] { charId });
// signal the session that characterization has been changed
request.getSession().setAttribute("newCharacterizationCreated", "true");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.delete.characterization");
msgs.add("message", msg);
saveMessages(request, msgs);
return mapping.findForward("success");
}
// add edited option to all editable dropdowns
private void updateAllCharEditables(HttpSession session,
CharacterizationBean achar) throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
achar.getCharacterizationSource(), "characterizationSources");
InitSessionSetup.getInstance().updateEditableDropdown(session,
achar.getInstrumentConfigBean().getInstrumentBean().getType(),
"allInstrumentTypes");
InitSessionSetup.getInstance().updateEditableDropdown(
session,
achar.getInstrumentConfigBean().getInstrumentBean()
.getManufacturer(), "allManufacturers");
for (DerivedBioAssayDataBean derivedBioAssayDataBean : achar
.getDerivedBioAssayDataList()) {
InitSessionSetup.getInstance().updateEditableDropdown(session,
derivedBioAssayDataBean.getType(),
"allDerivedDataFileTypes");
if (derivedBioAssayDataBean != null) {
for (String category : derivedBioAssayDataBean.getCategories()) {
InitSessionSetup.getInstance().updateEditableDropdown(
session, category, "derivedDataCategories");
}
for (DatumBean datum : derivedBioAssayDataBean.getDatumList()) {
InitSessionSetup.getInstance().updateEditableDropdown(
session, datum.getName(), "datumNames");
InitSessionSetup.getInstance().updateEditableDropdown(
session, datum.getStatisticsType(),
"charMeasureTypes");
InitSessionSetup.getInstance().updateEditableDropdown(
session, datum.getUnit(), "charMeasureUnits");
}
}
}
}
// add edited option to all editable dropdowns
private void updateShapeEditable(HttpSession session, ShapeBean shape)
throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
shape.getType(), "allShapeTypes");
}
private void updateMorphologyEditable(HttpSession session,
MorphologyBean morphology) throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
morphology.getType(), "allMorphologyTypes");
}
private void updateCytotoxicityEditable(HttpSession session,
CytotoxicityBean cyto) throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
cyto.getCellLine(), "allCellLines");
}
private void updateSolubilityEditable(HttpSession session,
SolubilityBean solubility) throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
solubility.getSolvent(), "allSolventTypes");
}
// private void updateSurfaceEditable(HttpSession session,
// SurfaceBean surface) throws Exception {
public boolean loginRequired() {
return true;
}
public boolean canUserExecute(UserBean user) throws Exception {
return InitSecuritySetup.getInstance().userHasCreatePrivilege(user,
CaNanoLabConstants.CSM_PG_PARTICLE);
}
}
|
package org.rstudio.core.client;
import org.rstudio.studio.client.workbench.prefs.model.UserPrefs;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.PreElement;
import com.google.gwt.junit.client.GWTTestCase;
import junit.framework.Assert;
// Note on test coverage: the VirtualConsole has two side effects; it operates on a
// DOM, if supplied, and also maintains an internal string with the output results.
// The "consolify" tests are testing the internal string only, and most of the other
// tests are only testing the DOM. Ideally these should all be extended to do both.
public class VirtualConsoleTests extends GWTTestCase
{
@Override
public String getModuleName()
{
return "org.rstudio.studio.RStudioTests";
}
private static class FakePrefs implements VirtualConsole.Preferences
{
@Override
public int truncateLongLinesInConsoleHistory()
{
return truncateLines_;
}
@Override
public String consoleAnsiMode()
{
return ansiMode_;
}
@Override
public boolean screenReaderEnabled()
{
return screenReaderEnabled_;
}
public int truncateLines_ = 1000;
public String ansiMode_ = UserPrefs.ANSI_CONSOLE_MODE_ON;
public boolean screenReaderEnabled_ = false;
}
private static String consolify(String text)
{
VirtualConsole console = new VirtualConsole(null, new FakePrefs());
console.submit(text);
return console.toString();
}
private VirtualConsole getVC(Element ele)
{
return new VirtualConsole(ele, new FakePrefs());
}
private static String setCsiCode(int code)
{
return setCsiCode(String.valueOf(code));
}
private static String setCsiCode(String code)
{
return AnsiCode.CSI + code + AnsiCode.SGR;
}
private static String setForegroundIndex(int color)
{
return setCsiCode(AnsiCode.FOREGROUND_EXT + ";" + AnsiCode.EXT_BY_INDEX + ";" + color);
}
private static String setBackgroundIndex(int color)
{
return setCsiCode(AnsiCode.BACKGROUND_EXT + ";" + AnsiCode.EXT_BY_INDEX + ";" + color);
}
public void testSimpleText()
{
String simple = consolify("foo");
Assert.assertEquals("foo", simple);
}
public void testEmbeddedBackspace()
{
String backspace = consolify("bool\bk");
Assert.assertEquals("book", backspace);
}
public void testTrailingBackspace()
{
String backspace = consolify("bool\bk");
Assert.assertEquals("book", backspace);
}
public void testCarriageReturn()
{
String cr = consolify("hello\rj");
Assert.assertEquals("jello", cr);
}
public void testNewlineCarriageReturn()
{
String cr = consolify("L1\nL2\rL3");
Assert.assertEquals("L1\nL3", cr);
}
public void testSimpleColor()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("Error", "error");
Assert.assertEquals(
"<span class=\"error\">Error</span>",
ele.getInnerHTML());
}
public void testTwoColors()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("Output 1", "one");
vc.submit("Output 2", "two");
Assert.assertEquals(
"<span class=\"one\">Output 1</span>" +
"<span class=\"two\">Output 2</span>",
ele.getInnerHTML());
}
public void testColorOverwrite()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("XXXX\r", "X");
vc.submit("YY", "Y");
Assert.assertEquals(
"<span class=\"Y\">YY</span>" +
"<span class=\"X\">XX</span>",
ele.getInnerHTML());
}
public void testColorSplit()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("123456");
vc.submit("\b\b\b\bXX", "X");
Assert.assertEquals(
"<span>12</span>" +
"<span class=\"X\">XX</span>" +
"<span>56</span>",
ele.getInnerHTML());
}
public void testColorOverlap()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("123", "A");
vc.submit("456", "B");
vc.submit("\b\b\b\bXX", "X");
Assert.assertEquals(
"<span class=\"A\">12</span>" +
"<span class=\"X\">XX</span>" +
"<span class=\"B\">56</span>",
ele.getInnerHTML());
}
public void testFormFeed()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("Sample1\n");
vc.submit("Sample2\n");
vc.submit("Sample3\f");
vc.submit("Sample4");
Assert.assertEquals("<span>Sample4</span>", ele.getInnerHTML());
}
public void testCarriageReturnWithStyleChange()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("World", "a");
// replace first character of line with green 'X', then change
// second character to red 'Y'
vc.submit("\r\033[32mX\033[31mY\033[0m", "a");
Assert.assertEquals(
"<span class=\"a xtermColor2\">X</span>" +
"<span class=\"a xtermColor1\">Y</span>" +
"<span class=\"a\">rld</span>",
ele.getInnerHTML());
}
public void testCarriageReturnWithStyleChange2()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("Hello\nWorld", "a");
// replace first character of current line with green 'X', then change
// second character to red 'Y'
vc.submit("\r\033[32mX\033[31mY\033[0m", "a");
Assert.assertEquals(
"<span class=\"a\">Hello\n</span>" +
"<span class=\"a xtermColor2\">X</span>" +
"<span class=\"a xtermColor1\">Y</span>" +
"<span class=\"a\">rld</span>",
ele.getInnerHTML());
}
public void testCarriageReturnWithStyleChange3()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("Hello\nWorld", "a");
vc.submit("\r\033[32m123\033[31m45\033[0m", "a");
Assert.assertEquals(
"<span class=\"a\">Hello\n</span>" +
"<span class=\"a xtermColor2\">123</span>" +
"<span class=\"a\"></span>" +
"<span class=\"a xtermColor1\">45</span>",
ele.getInnerHTML());
}
public void testAnsiColorStyleHelper()
{
Assert.assertEquals("xtermColor0",
AnsiCode.clazzForColor(AnsiCode.FOREGROUND_MIN));
Assert.assertEquals("xtermColor7",
AnsiCode.clazzForColor(AnsiCode.FOREGROUND_MAX));
Assert.assertEquals("xtermBgColor0",
AnsiCode.clazzForBgColor(AnsiCode.BACKGROUND_MIN));
Assert.assertEquals("xtermBgColor7",
AnsiCode.clazzForBgColor(AnsiCode.BACKGROUND_MAX));
}
public void testAnsiIntenseColorStyleHelper()
{
Assert.assertEquals("xtermColor8",
AnsiCode.clazzForColor(AnsiCode.FOREGROUND_INTENSE_MIN));
Assert.assertEquals("xtermColor15",
AnsiCode.clazzForColor(AnsiCode.FOREGROUND_INTENSE_MAX));
Assert.assertEquals("xtermBgColor8",
AnsiCode.clazzForBgColor(AnsiCode.BACKGROUND_INTENSE_MIN));
Assert.assertEquals("xtermBgColor15",
AnsiCode.clazzForBgColor(AnsiCode.BACKGROUND_INTENSE_MAX));
}
public void testMinAnsiForegroundColor()
{
int color = AnsiCode.FOREGROUND_MIN;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setCsiCode(color) + "Hello");
String expected ="<span class=\"xtermColor0\">Hello</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testMaxAnsiForegroundColor()
{
int color = AnsiCode.FOREGROUND_MAX;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setCsiCode(color) + "Hello World");
String expected ="<span class=\"xtermColor7\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testMinAnsiBgColor()
{
int color = AnsiCode.BACKGROUND_MIN;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setCsiCode(color) + "pretty");
String expected ="<span class=\"" +
AnsiCode.clazzForBgColor(color) + "\">pretty</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testMaxAnsiBgColor()
{
int color = AnsiCode.BACKGROUND_MAX;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setCsiCode(color) + "colors");
String expected ="<span class=\"" +
AnsiCode.clazzForBgColor(color) + "\">colors</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testResetAnsiForegroundColor()
{
int color = AnsiCode.ForeColorNum.RED;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
setCsiCode(color) + "Hello " +
setCsiCode(AnsiCode.RESET_FOREGROUND) + "World");
String expected =
"<span class=\"" +
AnsiCode.clazzForColor(color) + "\">Hello </span>" +
"<span>World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testResetAnsiBgColor()
{
int color = AnsiCode.BackColorNum.GREEN;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
setCsiCode(color) + "Sunny " +
setCsiCode(AnsiCode.RESET_BACKGROUND) + "Days");
String expected = "<span class=\"" + AnsiCode.clazzForBgColor(color) +
"\">Sunny </span><span>Days</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiForegroundAndBgColor()
{
int color = AnsiCode.ForeColorNum.MAGENTA;
int bgColor = AnsiCode.BackColorNum.GREEN;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setCsiCode(color) + setCsiCode(bgColor) + "Hello");
String expected ="<span class=\"" +
AnsiCode.clazzForColor(color) + " " +
AnsiCode.clazzForBgColor(bgColor) + "\">Hello</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testResetAnsiColors()
{
int color = AnsiCode.ForeColorNum.YELLOW;
int bgColor = AnsiCode.BackColorNum.CYAN;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
setCsiCode(color) +
setCsiCode(bgColor) + "Colorful " +
setCsiCode(AnsiCode.RESET) + "Bland");
String expected ="<span class=\"" +
AnsiCode.clazzForColor(color) + " " +
AnsiCode.clazzForBgColor(bgColor) +
"\">Colorful </span><span>Bland</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testMinAnsiIntenseForegroundColor()
{
int color = AnsiCode.FOREGROUND_INTENSE_MIN;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setCsiCode(color) + "Hello");
String expected ="<span class=\"" +
AnsiCode.clazzForColor(color) +
"\">Hello</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testMaxAnsiIntenseForegroundColor()
{
int color = AnsiCode.FOREGROUND_INTENSE_MAX;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setCsiCode(color) + "Hello World");
String expected ="<span class=\"" +
AnsiCode.clazzForColor(color) + "\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testMinAnsiIntenseBgColor()
{
int color = AnsiCode.BACKGROUND_INTENSE_MIN;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setCsiCode(color) + "pretty");
String expected ="<span class=\"" +
AnsiCode.clazzForBgColor(color) + "\">pretty</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testMaxAnsiIntenseBgColor()
{
int color = AnsiCode.BACKGROUND_INTENSE_MAX;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + color + AnsiCode.SGR + "colors");
String expected ="<span class=\"" +
AnsiCode.clazzForBgColor(color) + "\">colors</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testResetAnsiIntenseForegroundColor()
{
int color = AnsiCode.FOREGROUND_INTENSE_MIN + 1;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
AnsiCode.CSI + color + AnsiCode.SGR + "Hello " +
AnsiCode.CSI + AnsiCode.RESET_FOREGROUND + AnsiCode.SGR + "World");
String expected =
"<span class=\"" +
AnsiCode.clazzForColor(color) + "\">Hello </span>" +
"<span>World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testResetAnsiIntenseBgColor()
{
int color = AnsiCode.BACKGROUND_INTENSE_MIN + 1;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
AnsiCode.CSI + color + AnsiCode.SGR + "Sunny " +
AnsiCode.CSI + AnsiCode.RESET_BACKGROUND + AnsiCode.SGR + "Days");
String expected = "<span class=\"" + AnsiCode.clazzForBgColor(color) +
"\">Sunny </span><span>Days</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiInvertDefaultColors()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + AnsiCode.INVERSE + AnsiCode.SGR + "Sunny Days");
String expected = "<span class=\"xtermInvertColor xtermInvertBgColor\"" +
">Sunny Days</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiInvertRevertDefaultColors()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
AnsiCode.CSI + AnsiCode.INVERSE + AnsiCode.SGR + "Sunny " +
AnsiCode.CSI + AnsiCode.INVERSE_OFF + AnsiCode.SGR + "Days");
String expected = "<span class=\"xtermInvertColor xtermInvertBgColor\"" +
">Sunny </span><span>Days</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiInvertCustomBgColor()
{
int bgColor = AnsiCode.BackColorNum.GREEN;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
AnsiCode.CSI + bgColor + AnsiCode.SGR +
AnsiCode.CSI + AnsiCode.INVERSE + AnsiCode.SGR + "Sunny Days");
String expected = "<span class=\"xtermColor2 xtermInvertBgColor\"" +
">Sunny Days</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiInvertCustomFgColor()
{
int fgColor = AnsiCode.ForeColorNum.BLUE;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
AnsiCode.CSI + fgColor + AnsiCode.SGR +
AnsiCode.CSI + AnsiCode.INVERSE + AnsiCode.SGR + "Sunny Days");
String expected = "<span class=\"xtermInvertColor xtermBgColor4\"" +
">Sunny Days</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiForeground256Color()
{
int color = 120;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setForegroundIndex(color) + "Hello World");
String expected ="<span class=\"xtermColor120\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiBackground256Color()
{
int color = 213;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setBackgroundIndex(color) + "Hello World");
String expected ="<span class=\"xtermBgColor213\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsi256Color()
{
int color = 65;
int bgColor = 252;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setForegroundIndex(color) + setBackgroundIndex(bgColor) + "Hello World");
String expected ="<span class=\"xtermColor65 xtermBgColor252\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiInvert256Color()
{
int color = 61;
int bgColor = 129;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(setForegroundIndex(color) + setBackgroundIndex(bgColor) +
AnsiCode.CSI + AnsiCode.INVERSE + AnsiCode.SGR + "Hello World");
String expected ="<span class=\"xtermColor129 xtermBgColor61\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiInvert256FgColor()
{
int color = 77;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + AnsiCode.FOREGROUND_EXT + ";" +
AnsiCode.EXT_BY_INDEX + ";" + color + AnsiCode.SGR +
AnsiCode.CSI + AnsiCode.INVERSE + AnsiCode.SGR + "Hello World");
String expected ="<span class=\"xtermInvertColor xtermBgColor77\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiInvert256BgColor()
{
int bgColor = 234;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + AnsiCode.BACKGROUND_EXT + ";" +
AnsiCode.EXT_BY_INDEX + ";" + bgColor + AnsiCode.SGR +
AnsiCode.CSI + AnsiCode.INVERSE + AnsiCode.SGR + "Hello World");
String expected ="<span class=\"xtermColor234 xtermInvertBgColor\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiComplexSequence1()
{
int fgColor = AnsiCode.ForeColorNum.GREEN;
int bgColor = 230;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
AnsiCode.CSI + fgColor + ";" +
AnsiCode.BACKGROUND_EXT + ";" + AnsiCode.EXT_BY_INDEX + ";" + bgColor + ";" +
AnsiCode.BOLD + ";" + AnsiCode.UNDERLINE + ";" + AnsiCode.BOLD_BLURRED_OFF + ";" +
AnsiCode.INVERSE_OFF + AnsiCode.SGR + "Hello World");
String expected ="<span class=\"xtermColor2 xtermBgColor230 xtermUnderline\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiComplexSequence2()
{
int fgColor = AnsiCode.ForeColorNum.GREEN;
int bgColor = 230;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
AnsiCode.CSI + fgColor + ";" +
AnsiCode.BACKGROUND_EXT + ";" + AnsiCode.EXT_BY_INDEX + ";" + bgColor + ";" +
AnsiCode.BOLD + ";" + AnsiCode.UNDERLINE + ";" + AnsiCode.BOLD_BLURRED_OFF + ";" +
AnsiCode.INVERSE_OFF + AnsiCode.SGR + "Hello World",
"existingStyle moreExisting");
String expected ="<span class=\"existingStyle moreExisting xtermColor2 xtermBgColor230 xtermUnderline\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiUnsupportedRGBExtendedColorScheme()
{
// don't currently support specifying color via RGB, which is
// ESC[38;2;r;g;bm or ESC[48;2;r;g;bm
// in those cases want to ignore the RGB sequence and carry on
// processing following codes
int red = 123;
int green = 231;
int blue = 121;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
AnsiCode.CSI + AnsiCode.FOREGROUND_EXT + ";" + AnsiCode.EXT_BY_RGB + ";" +
red + ";" + green + ";" + blue + ";" + AnsiCode.BOLD + AnsiCode.SGR +
"Hello World");
String expected ="<span class=\"xtermBold\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiMultiUnsupportedRGBExtendedColorScheme()
{
int red = 123;
int green = 231;
int blue = 121;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(
AnsiCode.CSI + AnsiCode.BOLD + ";" +
AnsiCode.FOREGROUND_EXT + ";" + AnsiCode.EXT_BY_RGB + ";" +
red + ";" + green + ";" + blue + ";" +
AnsiCode.UNDERLINE + ";" +
AnsiCode.BACKGROUND_EXT + ";" + AnsiCode.EXT_BY_RGB + ";" +
red + ";" + green + ";" + blue + ";" +
AnsiCode.FOREGROUND_EXT + ";" + AnsiCode.EXT_BY_INDEX + ";" + 255 +
AnsiCode.SGR +
"Hello World");
String expected ="<span class=\"xtermBold xtermUnderline xtermColor255\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiCodeSplitAcrossSubmits()
{
int color = AnsiCode.ForeColorNum.MAGENTA;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + color);
vc.submit(AnsiCode.SGR + "Hello");
String expected ="<span class=\"" +
AnsiCode.clazzForColor(color) + "\">Hello</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiCodeSplitAcrossSubmitsWithParentStyle()
{
int color = AnsiCode.ForeColorNum.MAGENTA;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + color, "myStyle");
vc.submit(AnsiCode.SGR + "Hello", "myStyle");
String expected ="<span class=\"myStyle " +
AnsiCode.clazzForColor(color) + "\">Hello</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testMultipleAnsiCodesSplitsAcrossSubmits()
{
int color = AnsiCode.ForeColorNum.MAGENTA;
int bgColor = AnsiCode.BackColorNum.GREEN;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + color);
vc.submit(AnsiCode.SGR + AnsiCode.CSI);
vc.submit(Integer.toString(bgColor));
vc.submit(AnsiCode.SGR + "Hello");
String expected ="<span class=\"" +
AnsiCode.clazzForColor(color) + " " +
AnsiCode.clazzForBgColor(bgColor) + "\">Hello</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiCodeAtEndOfSubmitCall()
{
int color = AnsiCode.ForeColorNum.MAGENTA;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + color);
vc.submit(AnsiCode.SGR);
vc.submit("Hello");
String expected ="<span class=\"" +
AnsiCode.clazzForColor(color) + "\">Hello</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testSplitAnsiCodeFollowedByMoreTextSubmits()
{
int color = AnsiCode.ForeColorNum.MAGENTA;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + color);
vc.submit(AnsiCode.SGR);
vc.submit("Hello");
vc.submit(" World");
String expected ="<span class=\"" +
AnsiCode.clazzForColor(color) + "\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiCodeFollowedByMoreTextSubmits()
{
int color = AnsiCode.ForeColorNum.RED;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + color + AnsiCode.SGR, "someClazz");
vc.submit("Hello World", "someClazz");
String expected ="<span class=\"someClazz " +
AnsiCode.clazzForColor(color) + "\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiComplexSequence1WithStripping()
{
int fgColor = AnsiCode.ForeColorNum.GREEN;
int bgColor = 230;
PreElement ele = Document.get().createPreElement();
FakePrefs prefs = new FakePrefs();
prefs.ansiMode_ = UserPrefs.ANSI_CONSOLE_MODE_STRIP;
VirtualConsole vc = new VirtualConsole(ele, prefs);
vc.submit(
AnsiCode.CSI + fgColor + ";" +
AnsiCode.BACKGROUND_EXT + ";" + AnsiCode.EXT_BY_INDEX + ";" + bgColor + ";" +
AnsiCode.BOLD + ";" + AnsiCode.UNDERLINE + ";" + AnsiCode.BOLD_BLURRED_OFF + ";" +
AnsiCode.INVERSE_OFF + AnsiCode.SGR + "Hello World", "myOriginalStyle");
String expected ="<span class=\"myOriginalStyle\">Hello World</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiComplexSequence1WithPassThrough()
{
int fgColor = AnsiCode.ForeColorNum.GREEN;
int bgColor = 230;
PreElement ele = Document.get().createPreElement();
FakePrefs prefs = new FakePrefs();
prefs.ansiMode_ = UserPrefs.ANSI_CONSOLE_MODE_OFF;
VirtualConsole vc = new VirtualConsole(ele, prefs);
vc.submit(
AnsiCode.CSI + fgColor + ";" +
AnsiCode.BACKGROUND_EXT + ";" + AnsiCode.EXT_BY_INDEX + ";" + bgColor + ";" +
AnsiCode.BOLD + ";" + AnsiCode.UNDERLINE + ";" + AnsiCode.BOLD_BLURRED_OFF + ";" +
AnsiCode.INVERSE_OFF + AnsiCode.SGR + "Hello World", "myOriginalStyle");
String expected ="<span class=\"myOriginalStyle\"><ESC>[32;48;5;230;1;4;22;27mHello World</span>";
Assert.assertEquals(expected, AnsiCode.prettyPrint(ele.getInnerHTML()));
}
public void testMultipleAnsiCodesSplitsAcrossSubmitsWithStripping()
{
int color = AnsiCode.ForeColorNum.MAGENTA;
int bgColor = AnsiCode.BackColorNum.GREEN;
PreElement ele = Document.get().createPreElement();
FakePrefs prefs = new FakePrefs();
prefs.ansiMode_ = UserPrefs.ANSI_CONSOLE_MODE_STRIP;
VirtualConsole vc = new VirtualConsole(ele, prefs);
vc.submit(AnsiCode.CSI + color);
vc.submit(AnsiCode.SGR + AnsiCode.CSI);
vc.submit(Integer.toString(bgColor));
vc.submit(AnsiCode.SGR + "Hello");
String expected ="<span>Hello</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
}
public void testAnsiCodeSplitAcrossSubmitsWithParentStyleWithPassthrough()
{
int color = AnsiCode.ForeColorNum.MAGENTA;
PreElement ele = Document.get().createPreElement();
FakePrefs prefs = new FakePrefs();
prefs.ansiMode_ = UserPrefs.ANSI_CONSOLE_MODE_OFF;
VirtualConsole vc = new VirtualConsole(ele, prefs);
vc.submit(AnsiCode.CSI + color, "myStyle");
vc.submit(AnsiCode.SGR + "Hello", "myStyle");
String expected ="<span class=\"myStyle\"><ESC>[35mHello</span>";
Assert.assertEquals(expected, AnsiCode.prettyPrint(ele.getInnerHTML()));
}
public void testMultipleCarriageReturn()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("hello world\r \rgoodbye");
Assert.assertEquals("<span>goodbye </span>", ele.getInnerHTML());
Assert.assertEquals("goodbye ", vc.toString());
}
public void testNonDestructiveBackspace()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("hello world\b\b\b\b\b");
Assert.assertEquals("<span>hello world</span>", ele.getInnerHTML());
Assert.assertEquals("hello world", vc.toString());
}
public void testSingleSupportedANSICodes()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(AnsiCode.CSI + "?25lBuilding sites \342\200\246 " +
AnsiCode.CSI + "?25h\r" + AnsiCode.CSI + "[K");
Assert.assertEquals("<span>Building sites \342\200\246 </span>", ele.getInnerHTML());
Assert.assertEquals("Building sites \342\200\246 ", vc.toString());
}
public void testMultipleUnknownANSICodes()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("We are " + AnsiCode.CSI + "?25lbuilding sites \342\200\246" +
AnsiCode.CSI + "?25h\r" + AnsiCode.CSI + "[K");
Assert.assertEquals("<span>We are building sites \342\200\246</span>", ele.getInnerHTML());
Assert.assertEquals("We are building sites \342\200\246", vc.toString());
}
public void testMultiCarriageReturnsWithoutColorsMultiSubmits()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("123");
vc.submit("x \r");
vc.submit("456");
vc.submit("x \r");
vc.submit("789");
Assert.assertEquals("<span>789x </span>", ele.getInnerHTML());
Assert.assertEquals("789x ", vc.toString());
}
public void testMultiCarriageReturnWithoutColors()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("123" + "x \r" + "456" + "x \r" + "789");
Assert.assertEquals("<span>789x </span>", ele.getInnerHTML());
Assert.assertEquals("789x ", vc.toString());
}
public void testMultiCarriageReturnWithColors()
{
// cat(c(crayon::red("123"), "x \r", crayon::red("456"), "x \r", crayon::red("789\n")), sep = "")
String red = AnsiCode.CSI + AnsiCode.ForeColorNum.RED + AnsiCode.SGR;
String reset = AnsiCode.CSI + AnsiCode.RESET_FOREGROUND + AnsiCode.SGR;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(red + "123" + reset + "x \r" +
red + "456" + reset + "x \r" +
red + "789");
String expected =
"<span class=\"" + AnsiCode.clazzForColor(AnsiCode.ForeColorNum.RED) +
"\">789</span><span>x </span>";
Assert.assertEquals(expected, ele.getInnerHTML());
Assert.assertEquals("789x ", vc.toString());
}
public void testCRNoColorsIssue2665Part1()
{
// this checks the output without colors involved
// cat(" xxx", "yyy", "xxx")
// cat("\r")
// cat("xxx", "yyy", "zzz")
// cat("\n")
// test writing over a previously written line (via \r) with
// no colors involved, the second line shorter than the first,
// ending with a \n
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(" xxx yyy xxx");
vc.submit("\r");
vc.submit("xxx yyy zzz");
vc.submit("\n");
String expected = "<span>xxx yyy zzzx\n</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
Assert.assertEquals("xxx yyy zzzx\n", vc.toString());
}
public void testCRNoColorsIssue2665Part2()
{
// this checks the output without colors involved
// cat(" xxx", "yyy", "xxx")
// cat("\r")
// cat(" xxx", "yyy", "zzz")
// cat("\n")
// test writing over a previously written line (via \r) with
// no colors involved, and the second line the same length as
// the first, ending with a \n
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(" xxx yyy xxx");
vc.submit("\r");
vc.submit(" xxx yyy zzz");
vc.submit("\n");
String expected = "<span> xxx yyy zzz\n</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
Assert.assertEquals(" xxx yyy zzz\n", vc.toString());
}
public void testCRColorsIssue2665Part1()
{
// cat(" xxx", crayon::blue("yyy"), "xxx")
// cat("\r")
// cat("xxx", crayon::red("yyy"), "zzz")
// cat("\n")
// test writing over a previously written line (via \r) with
// colors involved, and the second line shorter than the first line,
// ending with \n
String red = AnsiCode.CSI + AnsiCode.ForeColorNum.RED + AnsiCode.SGR;
String redCode = "\"" + AnsiCode.clazzForColor(AnsiCode.ForeColorNum.RED) + "\"";
String blue = AnsiCode.CSI + AnsiCode.ForeColorNum.BLUE + AnsiCode.SGR;
String blueCode = "\"" + AnsiCode.clazzForColor(AnsiCode.ForeColorNum.BLUE) + "\"";
String reset = AnsiCode.CSI + AnsiCode.RESET_FOREGROUND + AnsiCode.SGR;
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit(" xxx " + blue + "yyy" + reset + " xxx");
vc.submit("\r");
vc.submit("xxx " + red + "yyy" + reset + " zzz");
vc.submit("\n");
String expected =
"<span>xxx </span>" +
"<span class=" + redCode + ">yyy</span>" +
"<span class=" + blueCode + "></span>" +
"<span></span><span> zzzx\n</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
Assert.assertEquals("xxx yyy zzzx\n", vc.toString());
}
public void testProgressBar4777Part1()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("=>
vc.submit("\r");
vc.submit("==>
vc.submit("\r");
vc.submit("==>
vc.submit("\r");
vc.submit("===>
vc.submit("\r");
vc.submit("====>
vc.submit("\r");
vc.submit("====>
vc.submit("\r");
vc.submit("======>
vc.submit("\r");
vc.submit("=======>---- 1.22 kB/s");
vc.submit("\r");
vc.submit("========>--- 1.23 kB/s");
vc.submit("\r");
vc.submit("=========>--- 1.3 kB/s");
vc.submit("\r");
vc.submit("==========>- 1.32 kB/s");
vc.submit("\r");
String lastLine = "===========> 1.33 kB/s";
vc.submit(lastLine);
String expected = "<span>===========> 1.33 kB/s</span>";
Assert.assertEquals(expected, ele.getInnerHTML());
Assert.assertEquals(lastLine, vc.toString());
}
public void testProgressBar4777Part2()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
String color = "\033[32m";
String restore = "\033[39m";
vc.submit("=>
vc.submit("\r");
vc.submit("==>
vc.submit("\r");
vc.submit("==>
vc.submit("\r");
vc.submit("===>
vc.submit("\r");
vc.submit("====>
vc.submit("\r");
vc.submit("====>
vc.submit("\r");
vc.submit("======>
vc.submit("\r");
vc.submit("=======>---- " + color + "1.22 kB/s " + restore);
vc.submit("\r");
vc.submit("========>--- " + color + "1.23 kB/s " + restore);
vc.submit("\r");
vc.submit("=========>-- " + color + "1.30 kB/s " + restore);
vc.submit("\r");
vc.submit("==========>- " + color + "1.32 kB/s " + restore);
vc.submit("\r");
vc.submit("===========> " + color + "1.33 kB/s " + restore);
Assert.assertTrue(true);
String expected = "<span>===========> </span><span class=\"xtermColor2\">1.33 kB/s </span>";
Assert.assertEquals(expected, ele.getInnerHTML());
Assert.assertEquals("===========> 1.33 kB/s " , vc.toString());
}
public void testProgressBar4777Part3()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
String color = "\033[32m";
String restore = "\033[39m";
vc.submit("aa " + color + "11 " + restore);
vc.submit("\r");
vc.submit("bbb " + color + "2 " + restore);
vc.submit("\r");
vc.submit("cc " + color + "33 " + restore);
String expected = "<span>cc </span><span class=\"xtermColor2\"></span><span class=\"xtermColor2\">33 </span>";
Assert.assertEquals(expected, ele.getInnerHTML());
Assert.assertEquals("cc 33 ", vc.toString());
}
public void testScreenReaderOffNoTextNotCaptured()
{
PreElement ele = Document.get().createPreElement();
VirtualConsole vc = getVC(ele);
vc.submit("Hello World", "someclass", false, true);
Assert.assertEquals(vc.getNewText(), "");
}
public void testScreenReaderOnTextCaptured()
{
PreElement ele = Document.get().createPreElement();
FakePrefs prefs = new FakePrefs();
prefs.screenReaderEnabled_ = true;
VirtualConsole vc = new VirtualConsole(ele, prefs);
String text = "Hello World\nHow are you?";
vc.submit(text, "someclass", false, true);
String newText = vc.getNewText();
Assert.assertEquals(newText, text);
}
}
|
package com.nubicz.customviews;
import java.util.HashMap;
import android.graphics.Typeface;
public class TypeFaceCache {
public static HashMap<String,Typeface> pCache = null;
public static Typeface getFont(1String path){
if(pCache == null){
}
}
}
|
package org.jetel.data.parser;
import java.io.IOException;
import java.io.InputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.IParserExceptionHandler;
import org.jetel.exception.JetelException;
import org.jetel.exception.PolicyType;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.string.QuotingDecoder;
import org.jetel.util.string.StringUtils;
/**
* Parsing plain text data.
*
* Known bugs:
* - Method skip() doesn't recognize records without final delimiter/recordDelimiter,
* for example last record in file without termination enter.
* That's why skip() doesn't count unfinished records.
*
* @author Martin Zatopek, David Pavlis
* @since September 29, 2005
* @see Parser
* @see org.jetel.data.Defaults
* @revision $Revision: 1.9 $
*/
public class DataParser extends AbstractTextParser {
private static final int RECORD_DELIMITER_IDENTIFIER = -1;
private static final int DEFAULT_FIELD_DELIMITER_IDENTIFIER = -2;
private final static Log logger = LogFactory.getLog(DataParser.class);
private IParserExceptionHandler exceptionHandler;
private ReadableByteChannel reader;
private CharBuffer charBuffer;
private ByteBuffer byteBuffer;
private StringBuilder fieldBuffer;
private CharBuffer recordBuffer;
private CharsetDecoder decoder;
private int fieldLengths[];
private boolean[] quotedFields;
private int recordCounter;
private int numFields;
private AhoCorasick delimiterSearcher;
private StringBuilder tempReadBuffer;
private boolean[] isAutoFilling;
// private boolean[] isSkipBlanks;
private boolean[] isSkipLeadingBlanks;
private boolean[] isSkipTrailingBlanks;
private boolean[] eofAsDelimiters;
private boolean releaseInputSource = true;
private boolean hasRecordDelimiter = false;
private boolean hasDefaultFieldDelimiter = false;
private QuotingDecoder qDecoder = new QuotingDecoder();
private boolean isEof;
private int bytesProcessed;
private DataFieldMetadata[] metadataFields;
/**
* We are in the middle of process of record parsing.
*/
private boolean recordIsParsed;
public DataParser(TextParserConfiguration cfg){
super(cfg);
decoder = Charset.forName(cfg.getCharset()).newDecoder();
reader = null;
exceptionHandler = cfg.getExceptionHandler();
}
/**
* Returns parser speed for specified configuration. See {@link TextParserFactory#getParser(TextParserConfiguration)}.
*/
public static Integer getParserSpeed(TextParserConfiguration cfg){
for (DataFieldMetadata field : cfg.getMetadata().getFields()) {
if (field.isByteBased() && !field.isAutoFilled()) {
logger.debug("Parser cannot be used for the specified data as they contain byte-based field '" + field);
return null;
}
}
return 10;
}
/**
* @see org.jetel.data.parser.Parser#getNext()
*/
@Override
public DataRecord getNext() throws JetelException {
DataRecord record = new DataRecord(cfg.getMetadata());
record.init();
record = parseNext(record);
if(exceptionHandler != null ) { //use handler only if configured
while(exceptionHandler.isExceptionThrowed()) {
exceptionHandler.setRawRecord(getLastRawRecord());
exceptionHandler.handleException();
record = parseNext(record);
}
}
return record;
}
/**
* @see org.jetel.data.parser.Parser#getNext(org.jetel.data.DataRecord)
*/
public DataRecord getNext(DataRecord record) throws JetelException {
record = parseNext(record);
if(exceptionHandler != null ) { //use handler only if configured
while(exceptionHandler.isExceptionThrowed()) {
exceptionHandler.setRawRecord(getLastRawRecord());
exceptionHandler.handleException();
record = parseNext(record);
}
}
return record;
}
@Override
public void init() throws ComponentNotReadyException {
//init private variables
if (cfg.getMetadata() == null) {
throw new ComponentNotReadyException("Metadata are null");
}
byteBuffer = ByteBuffer.allocateDirect(Defaults.Record.MAX_RECORD_SIZE);
charBuffer = CharBuffer.allocate(Defaults.Record.MAX_RECORD_SIZE);
charBuffer.flip(); // initially empty
fieldBuffer = new StringBuilder(Defaults.DataParser.FIELD_BUFFER_LENGTH);
recordBuffer = CharBuffer.allocate(Defaults.Record.MAX_RECORD_SIZE);
tempReadBuffer = new StringBuilder(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE);
numFields = cfg.getMetadata().getNumFields();
isAutoFilling = new boolean[numFields];
// isSkipBlanks = new boolean[numFields];
isSkipLeadingBlanks = new boolean[numFields];
isSkipTrailingBlanks = new boolean[numFields];
eofAsDelimiters = new boolean[numFields];
//aho-corasick initialize
delimiterSearcher = new AhoCorasick();
// create array of delimiters & initialize them
String[] delimiters;
for (int i = 0; i < numFields; i++) {
if(cfg.getMetadata().getField(i).isDelimited()) {
delimiters = cfg.getMetadata().getField(i).getDelimiters();
if(delimiters != null && delimiters.length > 0) { //it is possible in case eofAsDelimiter tag is set
for(int j = 0; j < delimiters.length; j++) {
delimiterSearcher.addPattern(delimiters[j], i);
}
} else {
delimiterSearcher.addPattern(null, i);
}
}
isAutoFilling[i] = cfg.getMetadata().getField(i).getAutoFilling() != null;
isSkipLeadingBlanks[i] = isSkipFieldLeadingBlanks(i);
// isSkipBlanks[i] = skipLeadingBlanks
// || trim == Boolean.TRUE
// || (trim == null && metadata.getField(i).isTrim());
isSkipTrailingBlanks[i] = isSkipFieldTrailingBlanks(i);
eofAsDelimiters[i] = cfg.getMetadata().getField(i).isEofAsDelimiter();
}
//aho-corasick initialize
if(cfg.getMetadata().isSpecifiedRecordDelimiter()) {
hasRecordDelimiter = true;
delimiters = cfg.getMetadata().getRecordDelimiters();
for(int j = 0; j < delimiters.length; j++) {
delimiterSearcher.addPattern(delimiters[j], RECORD_DELIMITER_IDENTIFIER);
}
}
if(cfg.getMetadata().isSpecifiedFieldDelimiter()) {
hasDefaultFieldDelimiter = true;
delimiters = cfg.getMetadata().getFieldDelimiters();
for(int j = 0; j < delimiters.length; j++) {
delimiterSearcher.addPattern(delimiters[j], DEFAULT_FIELD_DELIMITER_IDENTIFIER);
}
}
delimiterSearcher.compile();
// create array of field sizes and quoting & initialize them
fieldLengths = new int[numFields];
quotedFields = new boolean[numFields];
for (int i = 0; i < numFields; i++) {
if(cfg.getMetadata().getField(i).isFixed()) {
fieldLengths[i] = cfg.getMetadata().getField(i).getSize();
}
char type = cfg.getMetadata().getFieldType(i);
quotedFields[i] = cfg.isQuotedStrings()
&& type != DataFieldMetadata.BYTE_FIELD
&& type != DataFieldMetadata.BYTE_FIELD_COMPRESSED;
}
metadataFields = cfg.getMetadata().getFields();
}
@Override
public void setReleaseDataSource(boolean releaseInputSource) {
this.releaseInputSource = releaseInputSource;
}
@Override
public void setDataSource(Object inputDataSource) throws IOException {
if (releaseInputSource) releaseDataSource();
decoder.reset();// reset CharsetDecoder
byteBuffer.clear();
byteBuffer.flip();
charBuffer.clear();
charBuffer.flip();
fieldBuffer.setLength(0);
recordBuffer.clear();
tempReadBuffer.setLength(0);
recordCounter = 0;// reset record counter
bytesProcessed = 0;
if (inputDataSource == null) {
reader = null;
isEof = true;
} else {
isEof = false;
if (inputDataSource instanceof CharBuffer) {
reader = null;
charBuffer = (CharBuffer) inputDataSource;
} else if (inputDataSource instanceof ReadableByteChannel) {
reader = ((ReadableByteChannel)inputDataSource);
} else {
reader = Channels.newChannel((InputStream)inputDataSource);
}
}
}
/**
* Discard bytes for incremental reading.
*
* @param bytes
* @throws IOException
*/
private void discardBytes(int bytes) throws IOException {
while (bytes > 0) {
if (reader instanceof FileChannel) {
((FileChannel)reader).position(bytes);
return;
}
byteBuffer.clear();
if (bytes < Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE) byteBuffer.limit(bytes);
try {
reader.read(byteBuffer);
} catch (IOException e) {
break;
}
bytes =- Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE;
}
byteBuffer.clear();
byteBuffer.flip();
}
/**
* Release data source
* @throws IOException
*
*/
private void releaseDataSource() throws IOException {
if (reader == null) {
return;
}
reader.close();
reader = null;
}
/**
* @see org.jetel.data.parser.Parser#close()
*/
public void close() throws IOException {
if(reader != null && reader.isOpen()) {
reader.close();
}
}
private DataRecord parseNext(DataRecord record) {
int fieldCounter;
int character = -1;
int mark;
boolean inQuote, quoteFound;
boolean skipLBlanks, skipTBlanks;
boolean quotedField;
recordCounter++;
if (cfg.isVerbose()) {
recordBuffer.clear();
}
recordIsParsed = false;
for (fieldCounter = 0; fieldCounter < numFields; fieldCounter++) {
// skip all fields that are internally filled
if (isAutoFilling[fieldCounter]) {
continue;
}
skipLBlanks = isSkipLeadingBlanks[fieldCounter];
skipTBlanks = isSkipTrailingBlanks[fieldCounter];
quotedField = quotedFields[fieldCounter];
fieldBuffer.setLength(0);
if (fieldLengths[fieldCounter] == 0) { //delimited data field
inQuote = false;
quoteFound = false;
try {
while ((character = readChar()) != -1) {
recordIsParsed = true;
//delimiter update
delimiterSearcher.update((char) character);
//skip leading blanks
if (skipLBlanks && !Character.isWhitespace(character)) {
skipLBlanks = false;
}
//quotedStrings
if (quotedField) {
if (fieldBuffer.length() == 0 && !inQuote) { //first quote character
if (qDecoder.isStartQuote((char) character)) {
inQuote = true;
continue;
}
} else {
if (inQuote && qDecoder.isEndQuote((char) character)) { //quote character found in quoted field
if (!quoteFound) { // do nothing, we will see if we get one more quoting character next time
quoteFound = true;
continue;
} else { //we found double quotes "" - will be handled as a escape sequence for single quote
quoteFound = false;
}
} else {
if (quoteFound) {
//final quote character for field found (no double quote) so we return the last read character back to reading stream
//and check whether the field delimiter follows
tempReadBuffer.append((char) character);
if (!followFieldDelimiter(fieldCounter)) { //after ending quote can i find delimiter
findFirstRecordDelimiter();
return parsingErrorFound("Bad quote format", record, fieldCounter);
}
break;
}
}
}
}
//fieldDelimiter update
if(!skipLBlanks) {
fieldBuffer.append((char) character);
if (fieldBuffer.length() > Defaults.DataParser.FIELD_BUFFER_LENGTH) {
return parsingErrorFound("Field delimiter was not found (this could be caused by insufficient field buffer size - DataParser.FIELD_BUFFER_LENGTH=" + Defaults.DataParser.FIELD_BUFFER_LENGTH + " - increase the constant if necessary)", record, fieldCounter);
}
}
//test field delimiter
if (!inQuote) {
if(delimiterSearcher.isPattern(fieldCounter)) {
// fieldBuffer.setLength(fieldBuffer.length() - delimiterSearcher.getMatchLength());
if(!skipLBlanks) {
fieldBuffer.setLength(Math.max(0, fieldBuffer.length() - delimiterSearcher.getMatchLength()));
}
if (skipTBlanks) {
StringUtils.trimTrailing(fieldBuffer);
}
if(cfg.isTreatMultipleDelimitersAsOne())
while(followFieldDelimiter(fieldCounter));
break;
}
//test default field delimiter
if(defaultFieldDelimiterFound()) {
findFirstRecordDelimiter();
return parsingErrorFound("Unexpected default field delimiter, probably record has too many fields.", record, fieldCounter);
}
//test record delimiter
if(recordDelimiterFound()) {
return parsingErrorFound("Unexpected record delimiter, probably record has too few fields.", record, fieldCounter);
}
}
}
} catch (Exception ex) {
throw new RuntimeException(getErrorMessage(ex.getMessage(), null, metadataFields[fieldCounter]), ex);
}
} else { //fixlen data field
mark = 0;
fieldBuffer.setLength(0);
try {
for(int i = 0; i < fieldLengths[fieldCounter]; i++) {
//end of file
if ((character = readChar()) == -1) {
break;
} else {
recordIsParsed = true;
}
//delimiter update
delimiterSearcher.update((char) character);
//test record delimiter
if(recordDelimiterFound()) {
return parsingErrorFound("Unexpected record delimiter, probably record is too short.", record, fieldCounter);
}
//skip leading blanks
if (skipLBlanks)
if(Character.isWhitespace(character)) continue;
else skipLBlanks = false;
//keep track of trailing blanks
if(!Character.isWhitespace(character)) {
mark = i;
}
fieldBuffer.append((char) character);
}
//removes tailing blanks
if(/*skipTBlanks && */character != -1 && fieldBuffer.length() > 0) {
fieldBuffer.setLength(fieldBuffer.length() -
(fieldLengths[fieldCounter] - mark - 1));
}
//check record delimiter presence for last field
if(hasRecordDelimiter && fieldCounter + 1 == numFields) {
int followRecord = followRecordDelimiter();
if(followRecord>0) { //record delimiter is not found
return parsingErrorFound("Too many characters found", record, fieldCounter);
}
if(followRecord<0) { //record delimiter is not found
return parsingErrorFound("Unexpected record delimiter, probably record is too short.", record, fieldCounter);
}
}
} catch (Exception ex) {
throw new RuntimeException(getErrorMessage(ex.getMessage(), null, metadataFields[fieldCounter]), ex);
}
}
// did we have EOF situation ?
if (character == -1) {
try {
if (!recordIsParsed) {
reader.close();
return null;
} else {
//maybe the field has EOF delimiter
if(eofAsDelimiters[fieldCounter]) {
populateField(record, fieldCounter, fieldBuffer);
return record;
}
return parsingErrorFound("Unexpected end of file", record, fieldCounter);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e1) {
throw new RuntimeException(getErrorMessage(e1.getMessage(), null, metadataFields[fieldCounter]), e1);
}
}
//populate field
populateField(record, fieldCounter, fieldBuffer);
}
return record;
}
private DataRecord parsingErrorFound(String exceptionMessage, DataRecord record, int fieldNum) {
if(exceptionHandler != null) {
exceptionHandler.populateHandler("Parsing error: " + exceptionMessage, record, recordCounter, fieldNum , getLastRawRecord(), new BadDataFormatException("Parsing error: " + exceptionMessage));
return record;
} else {
throw new RuntimeException("Parsing error: " + exceptionMessage + " (" + getLastRawRecord() + ")");
}
}
private int readChar() throws IOException {
final char character;
final int size;
CoderResult result;
if(tempReadBuffer.length() > 0) { // the tempReadBuffer is used as a cache of already read characters which should be read again
character = tempReadBuffer.charAt(0);
tempReadBuffer.deleteCharAt(0);
return character;
}
if (charBuffer.hasRemaining()) {
character = charBuffer.get();
if (cfg.isVerbose()) {
try {
recordBuffer.put(character);
} catch (BufferOverflowException e) {
throw new RuntimeException("Parse error: The size of data buffer for data record is only " + recordBuffer.limit() + ". Set appropriate parameter in defautProperties file.", e);
}
}
return character;
}
if (isEof || reader == null)
return -1;
charBuffer.clear();
if (byteBuffer.hasRemaining())
byteBuffer.compact();
else
byteBuffer.clear();
if ((size = reader.read(byteBuffer)) == -1) {
isEof = true;
} else {
bytesProcessed += size;
}
byteBuffer.flip();
result = decoder.decode(byteBuffer, charBuffer, isEof);
// if (result == CoderResult.UNDERFLOW) {
// // try to load additional data
// byteBuffer.compact();
// if (reader.read(byteBuffer) == -1) {
// isEof = true;
// byteBuffer.flip();
// decoder.decode(byteBuffer, charBuffer, isEof);
// } else
if (result.isError()) {
throw new IOException(result.toString()+" when converting from "+decoder.charset());
}
if (isEof) {
result = decoder.flush(charBuffer);
if (result.isError()) {
throw new IOException(result.toString()+" when converting from "+decoder.charset());
}
}
charBuffer.flip();
if (charBuffer.hasRemaining()) {
final int ret = charBuffer.get();
if (cfg.isVerbose()) {
try {
recordBuffer.put((char) ret);
} catch (BufferOverflowException e) {
throw new RuntimeException("Parse error: The size of data buffer for data record is only " + recordBuffer.limit() + ". Set appropriate parameter in defautProperties file.", e);
}
}
return ret;
} else {
return -1;
}
}
/**
* Assembles error message when exception occures during parsing
*
* @param exceptionMessage
* message from exception getMessage() call
* @param recNo
* recordNumber
* @param fieldNo
* fieldNumber
* @return error message
* @since September 19, 2002
*/
private String getErrorMessage(String exceptionMessage, CharSequence value, DataFieldMetadata metadataField) {
StringBuffer message = new StringBuffer();
message.append(exceptionMessage);
message.append(" when parsing record
message.append(recordCounter);
if (metadataField != null) {
message.append(" field ");
message.append(metadataField.getName());
}
if (value != null) {
message.append(" value \"").append(value).append("\"");
}
return message.toString();
}
/**
* Finish incomplete fields <fieldNumber, metadata.getNumFields()>.
*
* @param record
* incomplete record
* @param fieldNumber
* first incomlete field in record
*/
// private void finishRecord(DataRecord record, int fieldNumber) {
// for(int i = fieldNumber; i < metadata.getNumFields(); i++) {
// record.getField(i).setToDefaultValue();
/**
* Populate field.
*
* @param record
* @param fieldNum
* @param data
*/
private final void populateField(DataRecord record, int fieldNum, StringBuilder data) {
try {
record.getField(fieldNum).fromString(data);
} catch(BadDataFormatException bdfe) {
if(exceptionHandler != null) {
exceptionHandler.populateHandler(bdfe.getMessage(), record,
recordCounter, fieldNum , data.toString(), bdfe);
} else {
bdfe.setRecordNumber(recordCounter);
bdfe.setFieldNumber(fieldNum);
bdfe.setOffendingValue(data);
throw bdfe;
}
} catch(Exception ex) {
throw new RuntimeException(getErrorMessage(ex.getMessage(), null, metadataFields[fieldNum]));
}
}
/**
* Find first record delimiter in input channel.
*/
private boolean findFirstRecordDelimiter() throws JetelException {
if(!cfg.getMetadata().isSpecifiedRecordDelimiter()) {
return false;
}
int character;
try {
while ((character = readChar()) != -1) {
delimiterSearcher.update((char) character);
//test record delimiter
if (recordDelimiterFound()) {
return true;
}
}
} catch (IOException e) {
throw new JetelException("Can not find a record delimiter.", e);
}
//end of file
return false;
}
/**
* Find end of record for metadata without record delimiter specified.
* @throws JetelException
*/
private boolean findEndOfRecord(int fieldNum) throws JetelException {
int character = 0;
try {
for(int i = fieldNum; i < numFields; i++) {
if (isAutoFilling[i]) continue;
if (metadataFields[i].isDelimited()) {
while((character = readChar()) != -1) {
delimiterSearcher.update((char) character);
if(delimiterSearcher.isPattern(i)) {
break;
}
}
} else { //data field is fixlen
for (int j = 0; j < fieldLengths[i]; j++) {
//end of file
if ((character = readChar()) == -1) {
break;
}
}
}
}
} catch (IOException e) {
throw new JetelException("Can not find end of record.", e);
}
return (character != -1);
}
// private void shiftToNextRecord(int fieldNum) {
// if(metadata.isSpecifiedRecordDelimiter()) {
// findFirstRecordDelimiter();
// } else {
// findEndOfRecord(fieldNum);
/**
* Is record delimiter in the input channel?
* @return
*/
private boolean recordDelimiterFound() {
if(hasRecordDelimiter) {
return delimiterSearcher.isPattern(RECORD_DELIMITER_IDENTIFIER);
} else {
return false;
}
}
/**
* Is default field delimiter in the input channel?
* @return
*/
private boolean defaultFieldDelimiterFound() {
if(hasDefaultFieldDelimiter) {
return delimiterSearcher.isPattern(DEFAULT_FIELD_DELIMITER_IDENTIFIER);
} else {
return false;
}
}
/**
* Follow field delimiter in the input channel?
* @param fieldNum field delimiter identifier
* @return
*/
StringBuffer temp = new StringBuffer();
private boolean followFieldDelimiter(int fieldNum) {
int character;
temp.setLength(0);
try {
while ((character = readChar()) != -1) {
temp.append((char) character);
delimiterSearcher.update((char) character);
if(delimiterSearcher.isPattern(fieldNum)) {
return true;
}
if(delimiterSearcher.getMatchLength() == 0) {
tempReadBuffer.append(temp);
return false;
}
}
} catch (IOException e) {
throw new RuntimeException(getErrorMessage(e.getMessage(), null, null));
}
//end of file
return false;
}
/**
* Follow record delimiter in the input channel?
* @return 0 if record delimiter follows. -1 if record is too short, 1 if record is longer
*/
private int followRecordDelimiter() {
int count = 1;
int character;
try {
while ((character = readChar()) != -1) {
delimiterSearcher.update((char) character);
if(recordDelimiterFound()) {
return (count - delimiterSearcher.getMatchLength());
}
count++;
}
} catch (IOException e) {
throw new RuntimeException(getErrorMessage(e.getMessage(), null, null));
}
//end of file
return -1;
}
public boolean endOfInputChannel() {
return reader == null || !reader.isOpen();
}
public int getRecordCount() {
return recordCounter;
}
public String getLastRawRecord() {
if (cfg.isVerbose()) {
recordBuffer.flip();
String lastRawRecord = recordBuffer.toString();
recordBuffer.position(recordBuffer.limit()); //it is necessary for repeated invocation of this method for the same record
return lastRawRecord;
} else {
return "<Raw record data is not available, please turn on verbose mode.>";
}
}
// /**
// * Skip first line/record in input channel.
// */
// public void skipFirstLine() {
// int character;
// try {
// while ((character = readChar()) != -1) {
// delimiterSearcher.update((char) character);
// if(delimiterSearcher.isPattern(-2)) {
// break;
// if(character == -1) {
// throw new RuntimeException("Skipping first line: record delimiter not found.");
// } catch (IOException e) {
// throw new RuntimeException(getErrorMessage(e.getMessage(), null, -1));
@Override
public int skip(int count) throws JetelException {
int skipped;
if(cfg.getMetadata().isSpecifiedRecordDelimiter()) {
for(skipped = 0; skipped < count; skipped++) {
if(!findFirstRecordDelimiter()) {
break;
}
recordBuffer.clear();
}
} else {
for(skipped = 0; skipped < count; skipped++) {
if(!findEndOfRecord(0)) {
break;
}
recordBuffer.clear();
}
}
return skipped;
}
@Override
public void setExceptionHandler(IParserExceptionHandler handler) {
this.exceptionHandler = handler;
}
@Override
public IParserExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
@Override
public PolicyType getPolicyType() {
if(exceptionHandler != null) {
return exceptionHandler.getType();
}
return null;
}
@Override
public void reset() {
if (releaseInputSource) {
try {
releaseDataSource();
} catch (IOException e) {
e.printStackTrace(); //TODO
}
}
decoder.reset();// reset CharsetDecoder
recordCounter = 0;// reset record counter
bytesProcessed = 0;
}
@Override
public Object getPosition() {
return bytesProcessed;
}
@Override
public void movePosition(Object position) throws IOException {
int pos = 0;
if (position instanceof Integer) {
pos = ((Integer) position).intValue();
} else if (position != null) {
pos = Integer.parseInt(position.toString());
}
if (pos > 0) {
discardBytes(pos);
bytesProcessed = pos;
}
}
@Override
public void preExecute() throws ComponentNotReadyException {
}
@Override
public void postExecute() throws ComponentNotReadyException {
reset();
}
@Override
public void free() throws IOException {
close();
}
}
|
package group.pals.desktop.app.apksigner;
import group.pals.desktop.app.apksigner.i18n.Messages;
import group.pals.desktop.app.apksigner.i18n.R;
import group.pals.desktop.app.apksigner.ui.Dlg;
import group.pals.desktop.app.apksigner.ui.JEditorPopupMenu;
import group.pals.desktop.app.apksigner.utils.Files;
import group.pals.desktop.app.apksigner.utils.Files.JFileChooserEx;
import group.pals.desktop.app.apksigner.utils.KeyTools;
import group.pals.desktop.app.apksigner.utils.Preferences;
import group.pals.desktop.app.apksigner.utils.Signer;
import group.pals.desktop.app.apksigner.utils.Texts;
import group.pals.desktop.app.apksigner.utils.UI;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;
/**
* Panel to sign APK files.
*
* @author Hai Bison
* @since v1.6 beta
*/
public class PanelSigner extends JPanel {
/**
* Auto-generated by Eclipse.
*/
private static final long serialVersionUID = -874904794558103202L;
/**
* The class name.
*/
private static final String CLASSNAME = PanelSigner.class.getName();
/**
* This key holds the last working directory.
*/
private static final String PKEY_LAST_WORKING_DIR = CLASSNAME
+ ".last_working_dir";
/**
* This key holds the last target file filter's ID.
*/
private static final String PKEY_LAST_TARGET_FILE_FILTER_ID = CLASSNAME
+ ".last_target_file_filter_ID";
/**
* Target file filters.
*/
private static final List<FileFilter> TARGET_FILE_FILTERS = Arrays.asList(
Files.newFileFilter(JFileChooser.FILES_ONLY, Texts.REGEX_APK_FILES,
Messages.getString(R.string.desc_apk_files)), Files
.newFileFilter(JFileChooser.FILES_ONLY,
Texts.REGEX_JAR_FILES,
Messages.getString(R.string.desc_jar_files)), Files
.newFileFilter(JFileChooser.FILES_ONLY,
Texts.REGEX_ZIP_FILES,
Messages.getString(R.string.desc_zip_files)));
/**
* Delay time to load keystore's aliases after the user stopped typying the
* keystore's password, in milliseconds.
*/
private static final int DELAY_TIME_TO_LOAD_KEY_ALIASES = 499;
/*
* FIELDS
*/
private File mKeyfile;
private File mTargetFile;
/*
* CONTROLS
*/
private JPasswordField mTextPassword;
@SuppressWarnings("rawtypes")
private JComboBox mCbxAlias;
private JPasswordField mTextAliasPassword;
private JButton mBtnChooseKeyfile;
private JButton mBtnChooseTargetFile;
private JButton mBtnSign;
private JPanel panel;
/**
* Create the panel.
*/
@SuppressWarnings({ "rawtypes" })
public PanelSigner() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 0, 0 };
gridBagLayout.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0 };
gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
Double.MIN_VALUE };
setLayout(gridBagLayout);
mBtnChooseKeyfile = new JButton(
Messages.getString(R.string.desc_load_key_file));
mBtnChooseKeyfile.addActionListener(mBtnChooseKeyfileActionListener);
GridBagConstraints gbc_mBtnChooseKeyfile = new GridBagConstraints();
gbc_mBtnChooseKeyfile.insets = new Insets(10, 3, 5, 3);
gbc_mBtnChooseKeyfile.gridx = 0;
gbc_mBtnChooseKeyfile.gridy = 0;
add(mBtnChooseKeyfile, gbc_mBtnChooseKeyfile);
mTextPassword = new JPasswordField();
mTextPassword
.addPropertyChangeListener(mTextPasswordPropertyChangeListener);
mTextPassword.addKeyListener(mTextPasswordKeyAdapter);
mTextPassword.setHorizontalAlignment(SwingConstants.CENTER);
mTextPassword.setBorder(new TitledBorder(null, Messages
.getString(R.string.password), TitledBorder.LEADING,
TitledBorder.TOP, null, null));
GridBagConstraints gbc_mTextPassword = new GridBagConstraints();
gbc_mTextPassword.insets = new Insets(3, 3, 5, 3);
gbc_mTextPassword.fill = GridBagConstraints.HORIZONTAL;
gbc_mTextPassword.gridx = 0;
gbc_mTextPassword.gridy = 1;
add(mTextPassword, gbc_mTextPassword);
panel = new JPanel();
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.insets = new Insets(3, 3, 3, 3);
gbc_panel.gridx = 0;
gbc_panel.gridy = 2;
add(panel, gbc_panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0 };
gbl_panel.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
panel.setBorder(new TitledBorder(null, Messages
.getString(R.string.alias), TitledBorder.LEADING,
TitledBorder.TOP, null, null));
mCbxAlias = new JComboBox();
mCbxAlias.setMinimumSize(new Dimension(199, 24));
mCbxAlias.addItemListener(mCbxAliasItemListener);
GridBagConstraints gbc_mCbxAlias = new GridBagConstraints();
gbc_mCbxAlias.gridx = 0;
gbc_mCbxAlias.gridy = 0;
panel.add(mCbxAlias, gbc_mCbxAlias);
mCbxAlias.setEditable(true);
mTextAliasPassword = new JPasswordField();
mTextAliasPassword.setHorizontalAlignment(SwingConstants.CENTER);
mTextAliasPassword.setBorder(new TitledBorder(null, Messages
.getString(R.string.alias_password), TitledBorder.LEADING,
TitledBorder.TOP, null, null));
GridBagConstraints gbc_mTextAliasPassword = new GridBagConstraints();
gbc_mTextAliasPassword.insets = new Insets(3, 3, 5, 3);
gbc_mTextAliasPassword.fill = GridBagConstraints.HORIZONTAL;
gbc_mTextAliasPassword.gridx = 0;
gbc_mTextAliasPassword.gridy = 3;
add(mTextAliasPassword, gbc_mTextAliasPassword);
mBtnChooseTargetFile = new JButton(
Messages.getString(R.string.desc_load_target_file));
mBtnChooseTargetFile
.addActionListener(mBtnChooseTargetFileActionListener);
GridBagConstraints gbc_mBtnChooseApkFile = new GridBagConstraints();
gbc_mBtnChooseApkFile.insets = new Insets(3, 3, 5, 3);
gbc_mBtnChooseApkFile.gridx = 0;
gbc_mBtnChooseApkFile.gridy = 4;
add(mBtnChooseTargetFile, gbc_mBtnChooseApkFile);
mBtnSign = new JButton(Messages.getString(R.string.sign));
mBtnSign.addActionListener(mBtnSignActionListener);
GridBagConstraints gbc_mBtnSign = new GridBagConstraints();
gbc_mBtnSign.insets = new Insets(10, 10, 10, 10);
gbc_mBtnSign.gridx = 0;
gbc_mBtnSign.gridy = 5;
add(mBtnSign, gbc_mBtnSign);
JEditorPopupMenu.apply(this);
}// PanelSigner()
/**
* Creates new {@link Timer} which automatically schedules a
* {@link TimerTask} to load current keystore's aliases.
*
* @return the timer.
*/
private Timer createAndScheduleKeyAliasesLoader() {
final boolean[] cancelled = { false };
TimerTask timerTask = new TimerTask() {
@SuppressWarnings("unchecked")
@Override
public void run() {
if (mKeyfile != null && mKeyfile.isFile() && mKeyfile.canRead()) {
char[] pwd = mTextPassword.getPassword();
if (pwd != null && pwd.length > 0) {
DefaultComboBoxModel<Object> model = new DefaultComboBoxModel<Object>(
new Object[] { "" });
for (String keystoreType : new String[] {
KeyTools.KEYSTORE_TYPE_JKS,
KeyTools.KEYSTORE_TYPE_JCEKS,
KeyTools.KEYSTORE_TYPE_PKCS12 }) {
final List<String> aliases = KeyTools.getAliases(
mKeyfile, keystoreType, pwd);
for (final String alias : aliases) {
model.addElement(new Object() {
@Override
public String toString() {
return alias;
}// toString()
});
}// for
if (!aliases.isEmpty())
break;
}// for
if (!cancelled[0]) {
mCbxAlias.setModel(model);
if (model.getSize() > 1)
mCbxAlias.setSelectedIndex(1);
}
}
}
}// run()
};
Timer timer = new Timer() {
@Override
public void cancel() {
cancelled[0] = true;
super.cancel();
}// cancel()
};
timer.schedule(timerTask, DELAY_TIME_TO_LOAD_KEY_ALIASES);
return timer;
}// createAndScheduleKeyAliasesLoader()
/**
* Validates all fields.
*
* @return {@code true} or {@code false}.
*/
private boolean validateFields() {
if (mKeyfile == null || !mKeyfile.isFile() || !mKeyfile.canRead()) {
Dlg.showErrMsg(Messages
.getString(R.string.msg_keyfile_doesnt_exist));
mBtnChooseKeyfile.requestFocus();
return false;
}
if (mTextPassword.getPassword() == null
|| mTextPassword.getPassword().length == 0) {
Dlg.showErrMsg(Messages.getString(R.string.msg_password_is_empty));
mTextPassword.requestFocus();
return false;
}
if (Texts.isEmpty(String.valueOf(mCbxAlias.getSelectedItem()))) {
Dlg.showErrMsg(Messages.getString(R.string.msg_alias_is_empty));
mCbxAlias.requestFocus();
return false;
}
if (mTextAliasPassword.getPassword() == null
|| mTextAliasPassword.getPassword().length == 0) {
Dlg.showErrMsg(Messages
.getString(R.string.msg_alias_password_is_empty));
mTextAliasPassword.requestFocus();
return false;
}
if (mTargetFile == null || !mTargetFile.isFile()
|| !mTargetFile.canWrite()) {
Dlg.showInfoMsg(Messages
.getString(R.string.msg_load_a_file_to_sign));
mBtnChooseTargetFile.requestFocus();
return false;
}
return true;
}// validateFields()
/**
* Signs the target file.
* <p>
* <b>Notes:</b> You should call {@link #validateFields()} first.
* </p>
*/
private void signTargetFile() {
try {
String info = Signer.sign(Preferences.getInstance().getJdkPath(),
mTargetFile, mKeyfile, mTextPassword.getPassword(),
String.valueOf(mCbxAlias.getSelectedItem()),
mTextAliasPassword.getPassword());
if (Texts.isEmpty(info))
Dlg.showInfoMsg(Messages.getString(R.string.msg_file_is_signed));
else
Dlg.showErrMsg(Messages.getString(
R.string.pmsg_error_signing_file, info));
} catch (Exception e) {
Dlg.showErrMsg(Messages.getString(R.string.pmsg_error_signing_file,
e));
}
}// signTargetFile()
/*
* LISTENERS
*/
private final ActionListener mBtnChooseKeyfileActionListener = new ActionListener() {
Timer mTimer;
@Override
public void actionPerformed(ActionEvent e) {
mKeyfile = Files.chooseFile(
new File(Preferences.getInstance().get(
PKEY_LAST_WORKING_DIR, "/")),
Texts.REGEX_KEYSTORE_FILES,
Messages.getString(R.string.desc_keystore_files));
if (mKeyfile != null) {
mBtnChooseKeyfile.setText(mKeyfile.getName());
mBtnChooseKeyfile.setForeground(UI.COLOUR_SELECTED_FILE);
Preferences.getInstance().set(PKEY_LAST_WORKING_DIR,
mKeyfile.getParentFile().getAbsolutePath());
if (mTimer != null)
mTimer.cancel();
mTimer = createAndScheduleKeyAliasesLoader();
mTextPassword.requestFocus();
} else {
mBtnChooseKeyfile.setText(Messages
.getString(R.string.desc_load_key_file));
mBtnChooseKeyfile.setForeground(UI.COLOUR_WAITING_CMD);
}
}// actionPerformed()
};// mBtnChooseKeyfileActionListener
private final PropertyChangeListener mTextPasswordPropertyChangeListener = new PropertyChangeListener() {
final String[] mActionNames = {
JEditorPopupMenu.ACTION_NAME_CLEAR_AND_PASTE,
JEditorPopupMenu.ACTION_NAME_CUT,
JEditorPopupMenu.ACTION_NAME_DELETE,
JEditorPopupMenu.ACTION_NAME_PASTE };
Timer mTimer;
@Override
public void propertyChange(PropertyChangeEvent e) {
for (String action : mActionNames) {
if (action.equals(e.getPropertyName())) {
if (mTimer != null)
mTimer.cancel();
mTimer = createAndScheduleKeyAliasesLoader();
break;
}
}
}// propertyChange()
};// mTextPasswordPropertyChangeListener
private final KeyAdapter mTextPasswordKeyAdapter = new KeyAdapter() {
Timer mTimer;
@Override
public void keyTyped(KeyEvent e) {
if (mTimer != null)
mTimer.cancel();
mTimer = createAndScheduleKeyAliasesLoader();
}// keyTyped()
};// mTextPasswordKeyAdapter
private final ItemListener mCbxAliasItemListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (mCbxAlias.getSelectedItem() != null
&& !Texts.isEmpty(mCbxAlias.getSelectedItem().toString()))
mTextAliasPassword.requestFocus();
}// itemStateChanged()
};// mCbxAliasItemListener
private final ActionListener mBtnChooseTargetFileActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final String lastFileFilterId = Preferences.getInstance().get(
PKEY_LAST_TARGET_FILE_FILTER_ID);
final JFileChooserEx fileChooser = new JFileChooserEx(new File(
Preferences.getInstance().get(PKEY_LAST_WORKING_DIR, "/")));
fileChooser
.setDialogTitle(Messages.getString(R.string.choose_file));
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
for (int i = 0; i < TARGET_FILE_FILTERS.size(); i++) {
FileFilter filter = TARGET_FILE_FILTERS.get(i);
fileChooser.addChoosableFileFilter(filter);
if ((Texts.isEmpty(lastFileFilterId) && i == 0)
|| Integer.toString(i).equals(lastFileFilterId))
fileChooser.setFileFilter(filter);
}
switch (fileChooser.showOpenDialog(null)) {
case JFileChooser.APPROVE_OPTION: {
mTargetFile = fileChooser.getSelectedFile();
mBtnChooseTargetFile.setText(mTargetFile.getName());
mBtnChooseTargetFile.setForeground(UI.COLOUR_SELECTED_FILE);
Preferences.getInstance().set(PKEY_LAST_WORKING_DIR,
mTargetFile.getParentFile().getAbsolutePath());
Preferences.getInstance().set(
PKEY_LAST_TARGET_FILE_FILTER_ID,
Integer.toString(TARGET_FILE_FILTERS
.indexOf(fileChooser.getFileFilter())));
break;
}// APPROVE_OPTION
default: {
mTargetFile = null;
mBtnChooseTargetFile.setText(Messages
.getString(R.string.desc_load_target_file));
mBtnChooseTargetFile.setForeground(UI.COLOUR_WAITING_CMD);
break;
}// default
}
}// actionPerformed()
};// mBtnChooseTargetFileActionListener
private final ActionListener mBtnSignActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (validateFields())
signTargetFile();
}// actionPerformed()
};// mBtnSignActionListener
}
|
package org.apache.jcs.engine.memory.lru;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jcs.engine.CacheConstants;
import org.apache.jcs.engine.CacheElement;
import org.apache.jcs.engine.behavior.ICacheElement;
import org.apache.jcs.engine.behavior.ICompositeCacheAttributes;
import org.apache.jcs.engine.behavior.IElementAttributes;
import org.apache.jcs.engine.control.Cache;
import org.apache.jcs.engine.memory.MemoryCache;
import org.apache.jcs.engine.memory.MemoryElementDescriptor;
import org.apache.jcs.engine.memory.shrinking.ShrinkerThread;
/**
* A fast reference management system. The least recently used items move to
* the end of the list and get spooled to disk if the cache hub is configured
* to use a disk cache. Most of the cache bottelnecks ar ein IO. There are no
* io bottlenecks here, it's all about processing power. Even though there are
* only a few adjustments necessary to maintain the double linked list, we
* might want to find a more efficient memory manager for large cache regions.
* The LRUMemoryCache is most efficeint when the first element is selected. The
* smaller teh region, the better the chance that this will be the case. < .04
* ms per put, p3 866, 1/10 of that per get
*
*@author <a href="mailto:asmuts@yahoo.com">Aaron Smuts</a>
*@author <a href="mailto:jtaylor@apache.org">James Taylor</a>
*@created May 13, 2002
*@version $Id$
*/
public class LRUMemoryCache implements MemoryCache, Serializable
{
private final static Log log =
LogFactory.getLog( LRUMemoryCache.class );
String cacheName;
/**
* Map where items are stored by key
*/
protected Map map = new Hashtable();
// LRU double linked list head/tail nodes
private MemoryElementDescriptor first;
private MemoryElementDescriptor last;
private int max;
/**
* Region Elemental Attributes
*/
public IElementAttributes attr;
/**
* Cache Attributes
*/
public ICompositeCacheAttributes cattr;
/**
* The cache this store is associated with
*/
Cache cache;
// status
private int status = CacheConstants.STATUS_ERROR;
// make configurable
private int chunkSize = 2;
/**
* The background memory shrinker
*/
private ShrinkerThread shrinker;
/**
* Constructor for the LRUMemoryCache object
*/
public LRUMemoryCache()
{
status = CacheConstants.STATUS_ERROR;
}
/**
* For post reflection creation initialization
*
*@param hub
*/
public synchronized void initialize( Cache hub )
{
this.cacheName = hub.getCacheName();
this.cattr = hub.getCacheAttributes();
this.max = this.cattr.getMaxObjects();
this.cache = hub;
status = CacheConstants.STATUS_ALIVE;
log.info( "initialized LRUMemoryCache for " + cacheName );
if ( cattr.getUseMemoryShrinker() && shrinker == null )
{
shrinker = new ShrinkerThread( this );
shrinker.setPriority( shrinker.MIN_PRIORITY );
shrinker.start();
}
}
/**
* Puts an item to the cache.
*
*@param ce Description of the Parameter
*@exception IOException
*/
public void update( ICacheElement ce )
throws IOException
{
// Asynchronisly create a MemoryElement
ce.getElementAttributes().setLastAccessTimeNow();
addFirst( ce );
MemoryElementDescriptor old =
( MemoryElementDescriptor ) map.put( ce.getKey(), first );
// If the node was the same as an existing node, remove it.
if ( first.equals( old ) )
{
removeNode( old );
}
int size = map.size();
// If the element limit is reached, we need to spool
if ( size < this.cattr.getMaxObjects() )
{
return;
}
else
{
log.debug( "In memory limit reached, spooling" );
// Write the last 'chunkSize' items to disk.
int chunkSizeCorrected = Math.min( size, chunkSize );
if ( log.isDebugEnabled() )
{
log.debug( "About to spool to disk cache, map size: " + size
+ ", max objects: " + this.cattr.getMaxObjects()
+ ", items to spool: " + chunkSizeCorrected );
}
// The spool will put them in a disk event queue, so there is no
// need to pre-queue the queuing. This would be a bit wasteful
// and wouldn't save much time in this synchronous call.
MemoryElementDescriptor node;
for ( int i = 0; i < chunkSizeCorrected; i++ )
{
synchronized ( this )
{
cache.spoolToDisk( last.ce );
map.remove( last.ce.getKey() );
removeNode( last );
}
}
if ( log.isDebugEnabled() )
{
log.debug( "After spool map size: " + size );
}
}
}
/**
* Get an item from the cache without affecting its last access time or
* position.
*
*@param key Identifies item to find
*@return Element mathinh key if found, or null
*@exception IOException
*/
public ICacheElement getQuiet( Serializable key )
throws IOException
{
MemoryElementDescriptor me = null;
ICacheElement ce = null;
try
{
me = ( MemoryElementDescriptor ) map.get( key );
if ( me != null )
{
if ( log.isDebugEnabled() )
{
log.debug( cacheName + ": LRUMemoryCache quiet hit for " + key );
}
ce = me.ce;
}
else
{
log.debug( cacheName + ": LRUMemoryCache quiet miss for " + key );
}
}
catch ( Exception e )
{
log.error( e );
}
return ce;
}
/**
* Get an item from the cache
*
*@param key Identifies item to find
*@return Element mathinh key if found, or null
*@exception IOException
*/
public ICacheElement get( Serializable key )
throws IOException
{
MemoryElementDescriptor me = null;
ICacheElement ce = null;
try
{
if ( log.isDebugEnabled() )
{
log.debug( "getting item for key: " + key );
}
me = ( MemoryElementDescriptor ) map.get( key );
if ( me != null )
{
if ( log.isDebugEnabled() )
{
log.debug( cacheName + ": LRUMemoryCache hit for " + key );
}
ce = me.ce;
ce.getElementAttributes().setLastAccessTimeNow();
makeFirst( me );
}
else
{
log.debug( cacheName + ": LRUMemoryCache miss for " + key );
}
}
catch ( Exception e )
{
log.error( e );
}
return ce;
}
/**
* Removes an item from the cache.
*
*@param key
*@return
*@exception IOException
*/
public boolean remove( Serializable key )
throws IOException
{
if ( log.isDebugEnabled() )
{
log.debug( "removing item for key: " + key );
}
boolean removed = false;
// handle partial removal
if ( key instanceof String && ( ( String ) key )
.endsWith( CacheConstants.NAME_COMPONENT_DELIMITER ) )
{
// remove all keys of the same name hierarchy.
synchronized ( map )
{
for ( Iterator itr = map.entrySet().iterator(); itr.hasNext(); )
{
Map.Entry entry = ( Map.Entry ) itr.next();
Object k = entry.getKey();
if ( k instanceof String
&& ( ( String ) k ).startsWith( key.toString() ) )
{
itr.remove();
removeNode( ( MemoryElementDescriptor )
entry.getValue() );
removed = true;
}
}
}
}
else
{
// remove single item.
MemoryElementDescriptor ce =
( MemoryElementDescriptor ) map.remove( key );
if ( ce != null )
{
removeNode( ce );
removed = true;
}
}
return removed;
}
/**
* Removes all cached items from the cache.
*
*@exception IOException
*/
public void removeAll()
throws IOException
{
map = new HashMap();
}
/**
* Prepares for shutdown.
*
*@exception IOException
*/
public void dispose()
throws IOException { }
/**
* Returns the current cache size.
*
*@return The size value
*/
public int getSize()
{
return this.map.size();
}
/**
* Returns the cache status.
*
*@return The status value
*/
public int getStatus()
{
return this.status;
}
/**
* Returns the cache name.
*
*@return The cacheName value
*/
public String getCacheName()
{
return this.cattr.getCacheName();
}
/**
* Gets the iterator attribute of the LRUMemoryCache object
*
*@return The iterator value
*/
public Iterator getIterator()
{
return map.entrySet().iterator();
}
/**
* Get an Array of the keys for all elements in the memory cache
*
*@return An Object[]
*/
public Object[] getKeyArray()
{
// need a better locking strategy here.
synchronized ( this )
{
// may need to lock to map here?
return map.keySet().toArray();
}
}
/**
* Puts an item to the cache.
*
*@param ce Description of the Parameter
*@exception IOException
*/
public void waterfal( ICacheElement ce )
throws IOException
{
this.cache.spoolToDisk( ce );
}
/**
* Returns the CacheAttributes.
*
*@return The CacheAttributes value
*/
public ICompositeCacheAttributes getCacheAttributes()
{
return this.cattr;
}
/**
* Sets the CacheAttributes.
*
*@param cattr The new CacheAttributes value
*/
public void setCacheAttributes( ICompositeCacheAttributes cattr )
{
this.cattr = cattr;
}
/**
* Removes the specified node from the link list.
*
*@param me Description of the Parameter
*/
private synchronized void removeNode( MemoryElementDescriptor me )
{
if ( log.isDebugEnabled() )
{
log.debug( "removing node " + me.ce.getKey() );
}
if ( me.next == null )
{
if ( me.prev == null )
{
// Make sure it really is the only node before setting head and
// tail to null. It is possible that we will be passed a node
// which has already been removed from the list, in which case
// we should ignore it
if ( me == first && me == last )
{
first = last = null;
}
}
else
{
// last but not the first.
last = me.prev;
last.next = null;
me.prev = null;
}
}
else if ( me.prev == null )
{
// first but not the last.
first = me.next;
first.prev = null;
me.next = null;
}
else
{
// neither the first nor the last.
me.prev.next = me.next;
me.next.prev = me.prev;
me.prev = me.next = null;
}
}
/**
* Adds a new node to the end of the link list. Currently not used.
*
*@param ce The feature to be added to the Last
*/
private void addLast( CacheElement ce )
{
MemoryElementDescriptor me = new MemoryElementDescriptor( ce );
if ( first == null )
{
// empty list.
first = me;
}
else
{
last.next = me;
me.prev = last;
}
last = me;
return;
}
/**
* Adds a new node to the start of the link list.
*
*@param ce The feature to be added to the First
*/
private synchronized void addFirst( ICacheElement ce )
{
MemoryElementDescriptor me = new MemoryElementDescriptor( ce );
if ( last == null )
{
// empty list.
last = me;
}
else
{
first.prev = me;
me.next = first;
}
first = me;
return;
}
/**
* Moves an existing node to the start of the link list.
*
*@param ce Description of the Parameter
*/
public void makeFirst( ICacheElement ce )
{
makeFirst( new MemoryElementDescriptor( ce ) );
}
/**
* Moves an existing node to the start of the link list.
*
*@param me Description of the Parameter
*/
public synchronized void makeFirst( MemoryElementDescriptor me )
{
try
{
if ( me.prev == null )
{
// already the first node.
return;
}
me.prev.next = me.next;
if ( me.next == null )
{
// last but not the first.
last = me.prev;
last.next = null;
}
else
{
// neither the last nor the first.
me.next.prev = me.prev;
}
first.prev = me;
me.next = first;
me.prev = null;
first = me;
}
catch ( Exception e )
{
log.error( "Couldn't make first", e );
}
return;
}
/**
* Dump the cache map for debugging.
*/
public void dumpMap()
{
log.debug( "dumpingMap" );
for ( Iterator itr = map.entrySet().iterator(); itr.hasNext(); )
{
//for ( Iterator itr = memCache.getIterator(); itr.hasNext();) {
Map.Entry e = ( Map.Entry ) itr.next();
MemoryElementDescriptor me =
( MemoryElementDescriptor ) e.getValue();
log.debug( "dumpMap> key=" + e.getKey()
+ ", val=" + me.ce.getVal() );
}
}
/**
* Dump the cache entries from first to list for debugging.
*/
public void dumpCacheEntries()
{
log.debug( "dumpingCacheEntries" );
for ( MemoryElementDescriptor me = first; me != null; me = me.next )
{
log.debug( "dumpCacheEntries> key="
+ me.ce.getKey() + ", val=" + me.ce.getVal() );
}
}
}
|
package ru.pinkponies.app;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MyLocationOverlay;
import org.osmdroid.views.overlay.PathOverlay;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;
import ru.pinkponies.app.net.NetworkListener;
import ru.pinkponies.app.net.NetworkingService;
import ru.pinkponies.protocol.AppleUpdatePacket;
import ru.pinkponies.protocol.ClientOptionsPacket;
import ru.pinkponies.protocol.PlayerUpdatePacket;
import ru.pinkponies.protocol.QuestUpdatePacket;
import ru.pinkponies.protocol.SayPacket;
/**
* The main activity class.
*/
public final class MainActivity extends Activity implements LocationListener, NetworkListener {
/**
* The class wide logger.
*/
private static final Logger LOGGER = Logger.getLogger(MainActivity.class.getName());
/**
* The delay between consecutive network IO updates.
*/
private static final int SERVICE_DELAY = 1000;
/**
* The minimum time interval between location updates, in milliseconds.
*/
private static final long LOCATION_UPDATE_MIN_DELAY = 1000;
/**
* The minimum distance between location updates, in meters.
*/
private static final float LOCATION_UPDATE_MIN_DISTANCE = 1;
/**
* The initial map view zoom level.
*/
private static final int MAP_VIEW_INITIAL_ZOOM_LEVEL = 18;
/**
* This value is used when the identifier is not yet defined.
*/
private static final long BAD_ID = -1;
/**
* The size of the objects on the map.
*/
private static final int ICON_SIZE = 48;
/**
* The networking service.
*/
private NetworkingService networkingService;
private final ServiceConnection networkingServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(final ComponentName className, final IBinder binder) {
MainActivity.this.networkingService = ((NetworkingService.LocalBinder) binder).getService();
MainActivity.this.onNetworkingServiceConnected();
LOGGER.info("Service connected");
}
@Override
public void onServiceDisconnected(final ComponentName className) {
MainActivity.this.onNetworkingServiceDisconnected();
MainActivity.this.networkingService = null;
LOGGER.info("Service disconnected");
}
};
private final Timer updateTimer = new Timer();
/**
* The location service manager.
*/
private LocationManager locationManager;
/**
* The map view widget.
*/
private MapView mapView;
/**
* The map controller.
*/
private MapController mapController;
/**
* The overlay displaying player's location.
*/
private MyLocationOverlay locationOverlay;
/**
* The overlay displaying other people locations.
*/
private MyItemizedOverlay personOverlay;
/**
* The overlay displaying apple locations.
*/
private MyItemizedOverlay appleOverlay;
/**
* The overlay displaying quest locations.
*/
private MyItemizedOverlay questOverlay;
/**
* The overlay which displays the path of the player.
*/
private PathOverlay pathOverlay;
/**
* The identifier of the player.
*/
private long myId = BAD_ID;
// private TextOverlay textOverlay;
// private String login = "";
// private String password = "";
/**
* Creates a new itemized overlay. This overlay will render image markers with the given
* resource id.
*
* @param resourceId
* Resource id.
* @return Created itemized overlay.
*/
private MyItemizedOverlay createItemizedOverlay(final int resourceId) {
Drawable marker = this.getResources().getDrawable(resourceId);
Bitmap bitmap = ((BitmapDrawable) marker).getBitmap();
marker = new BitmapDrawable(this.getResources(), Bitmap.createScaledBitmap(bitmap, ICON_SIZE, ICON_SIZE, true));
final ResourceProxy resourceProxy = new DefaultResourceProxyImpl(this.getApplicationContext());
return new MyItemizedOverlay(marker, resourceProxy);
}
/**
* Called when the activity is first created. Initializes GUI, networking, creates overlays.
*
* @param savedInstanceState
* If the activity is being re-initialized after previously being shut down then this
* Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle).
* Note: Otherwise it is null.
*/
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LOGGER.info("onCreate " + this.hashCode());
// Intent intent = getIntent();
// Bundle extras = intent.getExtras();
// login = extras.getString("login");
// password = extras.getString("password");
this.setContentView(R.layout.activity_main);
this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_MIN_DELAY,
LOCATION_UPDATE_MIN_DISTANCE, this);
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_MIN_DELAY,
LOCATION_UPDATE_MIN_DISTANCE, this);
// GUI.
this.mapView = (MapView) this.findViewById(R.id.MainActivityMapview);
this.mapView.setMultiTouchControls(true);
this.mapController = this.mapView.getController();
this.mapController.setZoom(MAP_VIEW_INITIAL_ZOOM_LEVEL);
this.locationOverlay = new MyLocationOverlay(this, this.mapView);
this.mapView.getOverlays().add(this.locationOverlay);
this.pathOverlay = new PathOverlay(Color.GREEN, this);
this.mapView.getOverlays().add(this.pathOverlay);
this.locationOverlay.runOnFirstFix(new Runnable() {
@Override
public void run() {
MainActivity.this.mapView.getController().animateTo(MainActivity.this.locationOverlay.getMyLocation());
}
});
this.mapView.postInvalidate();
// textOverlay = new TextOverlay(this, mapView);
// textOverlay.setPosition(new GeoPoint(55.9, 37.5));
// textOverlay.setText("Hello, world!");
// mapView.getOverlays().add(textOverlay);
this.personOverlay = this.createItemizedOverlay(R.drawable.player);
this.mapView.getOverlays().add(this.personOverlay);
this.appleOverlay = this.createItemizedOverlay(R.drawable.apple);
this.mapView.getOverlays().add(this.appleOverlay);
this.questOverlay = this.createItemizedOverlay(R.drawable.question);
this.mapView.getOverlays().add(this.questOverlay);
// GeoPoint myPoint = new GeoPoint(55929563, 37523862);
// this.myAppleOverlay.addItem(myPoint, "Apple");
LOGGER.info("Starting service");
this.startService(new Intent(this, NetworkingService.class));
this.bindService(new Intent(this, NetworkingService.class), this.networkingServiceConnection,
Context.BIND_AUTO_CREATE);
LOGGER.info("Initialized.");
}
/**
* Called when the activity will start interacting with the user.
*/
@Override
protected void onResume() {
super.onResume();
LOGGER.info("onResume " + this.hashCode());
this.locationOverlay.enableMyLocation();
this.locationOverlay.enableFollowLocation();
}
/**
* Called when the system is about to start resuming a previous activity.
*/
@Override
protected void onPause() {
super.onPause();
LOGGER.info("onPause");
this.locationOverlay.disableMyLocation();
this.locationOverlay.disableFollowLocation();
}
/**
* The final call you receive before your activity is destroyed.
*/
@Override
protected void onDestroy() {
LOGGER.info("onDestroy " + this.hashCode());
if (this.networkingService != null) {
this.unbindService(this.networkingServiceConnection);
this.networkingService.removeListener(this);
this.networkingService = null;
}
this.updateTimer.cancel();
this.locationManager.removeUpdates(this);
super.onDestroy();
}
/**
* This method is called before an activity may be killed so that when it comes back some time
* in the future it can restore its state.
*
* @param outState
* Bundle in which this activity state is placed.
*/
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
LOGGER.info("onSaveInstanceState " + this.hashCode());
outState.putInt("zoomLevel", this.mapView.getZoomLevel());
}
/**
* This method is called after onStart() when the activity is being re-initialized from a
* previously saved state, given here in savedInstanceState.
*
* @param outState
* The data most recently supplied in onSaveInstanceState(Bundle).
*/
@Override
protected void onRestoreInstanceState(final Bundle outState) {
LOGGER.info("onRestoreInstanceState " + this.hashCode());
MainActivity.LOGGER.info("MainActivity:onSaveInstanceState");
super.onRestoreInstanceState(outState);
outState.getInt("zoomLevel");
this.mapController.setZoom(outState.getInt("zoomLevel"));
}
/**
* Called once, the first time the options menu is displayed.
*
* @param menu
* The options menu.
* @return True.
*/
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
this.getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* Called when the logout button is pressed.
*
* @param view
* The button widget.
*/
public void onLogoutClick(final View view) {
this.goToLoginActivity();
this.finish();
}
protected void onNetworkingServiceDisconnected() {
if (this.networkingService != null) {
this.networkingService.removeListener(this);
this.networkingService = null;
}
}
protected void onNetworkingServiceConnected() {
this.networkingService.addListener(this);
this.sendMessageToNetwork("connect");
this.sendMessageToNetwork("service");
}
/**
* Called when there is a new message from the networking service.
*
* @param message
* The message which was received.
*/
@Override
public void onMessage(final Object message) {
LOGGER.info(message.toString());
if (message.equals("connected")) {
this.sendMessageToNetwork("login");
this.updateTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
MainActivity.this.sendMessageToNetwork("service");
}
}, 0, MainActivity.SERVICE_DELAY);
} else if (message.equals("failed")) {
this.showMessageBox("Socket exception.", null);
} else if (message instanceof ClientOptionsPacket) {
final ClientOptionsPacket packet = (ClientOptionsPacket) message;
this.myId = packet.getClientId();
} else if (message instanceof SayPacket) {
final SayPacket packet = (SayPacket) message;
LOGGER.info(packet.toString());
} else if (message instanceof PlayerUpdatePacket) {
final PlayerUpdatePacket packet = (PlayerUpdatePacket) message;
if (this.myId != BAD_ID && packet.getClientId() != this.myId) {
final GeoPoint point = new GeoPoint(packet.getLocation().getLatitude(), packet.getLocation()
.getLongitude());
final String title = "Player" + String.valueOf(packet.getClientId());
this.personOverlay.removeItem(title);
this.personOverlay.addItem(point, title);
}
} else if (message instanceof AppleUpdatePacket) {
final AppleUpdatePacket packet = (AppleUpdatePacket) message;
final String title = "Apple" + String.valueOf(packet.getAppleId());
if (packet.getStatus()) {
final GeoPoint point = new GeoPoint(packet.getLocation().getLatitude(), packet.getLocation()
.getLongitude());
this.appleOverlay.addItem(point, title);
} else {
this.appleOverlay.removeItem(title);
}
LOGGER.info("Apple " + String.valueOf(packet.getAppleId()) + " updated.");
} else if (message instanceof QuestUpdatePacket) {
final QuestUpdatePacket packet = (QuestUpdatePacket) message;
final String title = "Quest" + String.valueOf(packet.getQuestId());
if (packet.getStatus()) {
final GeoPoint point = new GeoPoint(packet.getLocation().getLatitude(), packet.getLocation()
.getLongitude());
this.questOverlay.addItem(point, title);
} else {
this.questOverlay.removeItem(title);
}
LOGGER.info("Quest " + String.valueOf(packet.getQuestId()) + " updated.");
}
}
/**
* Asynchronously sends the given message to the networking thread.
*
* @param message
* The message to send.
*/
private void sendMessageToNetwork(final Object message) {
this.networkingService.sendMessage(message);
}
/**
* Switches current activity to login activity.
*/
public void goToLoginActivity() {
final Intent intent = new Intent(MainActivity.this, LoginActivity.class);
this.startActivity(intent);
this.onDestroy();
}
/**
* Called when the player's location is changed.
*
* @param location
* The new location, as a Location object.
*/
@Override
public void onLocationChanged(final Location location) {
final double longitude = location.getLongitude();
final double latitude = location.getLatitude();
final double altitude = location.getAltitude();
final GeoPoint point = new GeoPoint(latitude, longitude);
this.pathOverlay.addPoint(point);
final ru.pinkponies.protocol.Location loc = new ru.pinkponies.protocol.Location(longitude, latitude, altitude);
final PlayerUpdatePacket packet = new PlayerUpdatePacket(this.myId, loc);
this.sendMessageToNetwork(packet);
MainActivity.LOGGER.info("Location updated.");
}
/**
* Called when the location provider is disabled by the user.
*
* @param provider
* The name of the location provider associated with this update.
*/
@Override
public void onProviderDisabled(final String provider) {
}
/**
* Called when the location provider is enabled by the user.
*
* @param provider
* The name of the location provider associated with this update.
*/
@Override
public void onProviderEnabled(final String provider) {
}
/**
* Called when the provider status changes. This method is called when a provider is unable to
* fetch a location or if the provider has recently become available after a period of
* unavailability.
*
* @param provider
* The name of the location provider associated with this update.
* @param status
* The status of the provider.
* @param extras
* Extra information about this update.
*/
@Override
public void onStatusChanged(final String provider, final int status, final Bundle extras) {
}
/**
* Shows a message box with the specified title and message.
*
* @param title
* The title of the message box.
* @param message
* The message that will be shown in the message box.
*/
public void showMessageBox(final String title, final String message) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int id) {
}
});
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
|
package au.csiro.portal.services;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.auscope.portal.core.server.http.HttpServiceCaller;
import org.auscope.portal.core.services.BaseWFSService;
import org.auscope.portal.core.services.PortalServiceException;
import org.auscope.portal.core.services.methodmakers.WFSGetFeatureMethodMaker;
import org.auscope.portal.core.services.methodmakers.WFSGetFeatureMethodMaker.ResultType;
import org.auscope.portal.core.services.responses.ows.OWSExceptionParser;
import org.auscope.portal.core.util.DOMUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import au.csiro.portal.models.Borehole;
import au.csiro.portal.models.Point3D;
import au.csiro.portal.xml.BoreholeNamespace;
@Service
public class Borehole3DService extends BaseWFSService {
private static final String ENDPOINT = "http://services-test.auscope.org/nvcl/wfs";
private static final String FEATURE_TYPE = "demo:boreholes";
@Autowired
public Borehole3DService(HttpServiceCaller httpServiceCaller,
WFSGetFeatureMethodMaker wfsMethodMaker) {
super(httpServiceCaller, wfsMethodMaker);
}
public List<Borehole> getBoreholes(String featureId, Integer maxFeatures) throws PortalServiceException {
HttpRequestBase request = null;
List<Borehole> boreholes = new ArrayList<Borehole>();
try {
request = this.generateWFSRequest(ENDPOINT, FEATURE_TYPE, featureId, null, maxFeatures, "http://www.opengis.net/gml/srs/epsg.xml#700001", ResultType.Results);
String response = this.httpServiceCaller.getMethodResponseAsString(request);
Document responseDoc = DOMUtil.buildDomFromString(response, true);
OWSExceptionParser.checkForExceptionResponse(responseDoc);
NamespaceContext nc = new BoreholeNamespace();
XPathExpression exprBoreholes = DOMUtil.compileXPathExpr("wfs:FeatureCollection/gml:featureMembers/demo:boreholes", nc);
NodeList boreholeNodes = (NodeList) exprBoreholes.evaluate(responseDoc, XPathConstants.NODESET);
for (int i = 0; i < boreholeNodes.getLength(); i++) {
Node boreholeNode = boreholeNodes.item(i);
String name = ((Node) DOMUtil.compileXPathExpr("gml:name", nc).evaluate(boreholeNode, XPathConstants.NODE)).getTextContent();
String depth = ((Node) DOMUtil.compileXPathExpr("demo:totaldepth", nc).evaluate(boreholeNode, XPathConstants.NODE)).getTextContent();
String pointList = ((Node) DOMUtil.compileXPathExpr("demo:shape/gml:LineString/gml:posList", nc).evaluate(boreholeNode, XPathConstants.NODE)).getTextContent();
String[] pointValues = pointList.split(" ");
Point3D[] points = new Point3D[pointValues.length / 3];
for (int j = 0; j < points.length; j++) {
points[j] = new Point3D(Double.parseDouble(pointValues[j * 3]),
Double.parseDouble(pointValues[(j * 3) + 1]),
Double.parseDouble(pointValues[(j * 3) + 2]));
}
boreholes.add(new Borehole(name, Double.parseDouble(depth), points));
}
return boreholes;
} catch (Exception ex) {
throw new PortalServiceException(request, ex);
}
}
public InputStream getImageStream(String boreholeId) throws Exception{
HttpGet method = new HttpGet();
URIBuilder builder = new URIBuilder("http://nvclwebservices.vm.csiro.au/NVCLDataServices/Display_Tray_Thumb.html");
builder.setParameter("logid", boreholeId); //The access token I am getting after the Login
builder.setParameter("sampleno", "1");
method.setURI(builder.build());
return this.httpServiceCaller.getMethodResponseAsStream(method);
}
public File getImageFile(String boreholeId) throws Exception{
HttpGet method = new HttpGet();
URIBuilder builder = new URIBuilder("http://nvclwebservices.vm.csiro.au/NVCLDataServices/Display_Tray_Thumb.html");
builder.setParameter("logid", boreholeId); //The access token I am getting after the Login
builder.setParameter("sampleno", "1");
method.setURI(builder.build());
InputStream in = this.httpServiceCaller.getMethodResponseAsStream(method);
File file = File.createTempFile("sprint", "png");
FileOutputStream out = new FileOutputStream(file);
IOUtils.copy(in,out);
out.flush();
return file;
}
}
|
package au.gov.ga.geodesy.domain.model.event;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.beans.factory.annotation.Configurable;
@Entity
@Table(name = "DOMAIN_EVENT")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "EVENT_NAME")
@Configurable
public abstract class Event implements Cloneable {
@Id
@GeneratedValue(generator = "surrogateKeyGenerator")
@SequenceGenerator(name = "surrogateKeyGenerator", sequenceName = "SEQ_EVENT")
private Integer id;
@Column(name = "TIME_RAISED", nullable = false)
private Date timeRaised;
@Column(name = "SUBSCRIBER", nullable = false)
public String subscriber;
@Column(name = "TIME_HANDLED")
public Date timeHandled;
@Column(name = "TIME_PUBLISHED")
public Date timePublished;
@Column(name = "RETRIES")
public Integer retries;
@Transient
/**
* Return a Human digestable message about this event. Used in email for example.
*
* @return the message
*/
// TODO: could this be toString instead?
public String getMessage() {
String message = "Event: " + this.getClass().getSimpleName() + ", Time Raised: " + this.getEventTime();
return message;
}
public Event() {
setTimeRaised(new Date());
}
public Date getEventTime() {
return timeRaised;
}
private void setTimeRaised(Date t) {
timeRaised = t;
}
public String getSubscriber() {
return subscriber;
}
protected void setSubscriber(String s) {
subscriber = s;
}
public Date getTimeHandled() {
return timeHandled;
}
private void setTimeHandled(Date t) {
timeHandled = t;
}
public Date getTimePublished() {
return timePublished;
}
public void setTimePublished(Date timePublished) {
this.timePublished = timePublished;
}
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public void published() {
if (getTimePublished() != null) {
setRetries(getRetries() == null ? 1 : getRetries() + 1);
}
setTimePublished(new Date());
}
public void handled() {
if (timeHandled == null) {
setTimeHandled(new Date());
}
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
|
package be.pielambr.minerva4j.client;
import be.pielambr.minerva4j.beans.Announcement;
import be.pielambr.minerva4j.beans.Course;
import be.pielambr.minerva4j.beans.Document;
import be.pielambr.minerva4j.beans.Event;
import be.pielambr.minerva4j.exceptions.LoginFailedException;
import be.pielambr.minerva4j.parsers.AnnouncementParser;
import be.pielambr.minerva4j.parsers.CourseParser;
import be.pielambr.minerva4j.parsers.DocumentParser;
import be.pielambr.minerva4j.parsers.EventParser;
import be.pielambr.minerva4j.utility.Constants;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.squareup.okhttp.*;
import jodd.jerry.Jerry;
import jodd.lagarto.dom.Node;
import sun.rmi.runtime.Log;
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URI;
import java.util.*;
public class MinervaClient {
private final OkHttpClient _browser;
private Map<String, List<String>> _map;
private boolean loggedin;
private final String _username;
private final String _password;
/**
* Default constructor for the Minerva client
* @param username Username for the user
* @param password Password for the user
*/
public MinervaClient(String username, String password) {
_username = username;
_password = password;
_browser = new OkHttpClient();
_browser.setFollowRedirects(false);
// Save cookies
_browser.setCookieHandler(new CookieHandler() {
@Override
public Map<String, List<String>> get(URI uri, Map<String, List<String>> map) throws IOException {
if(!loggedin && map.containsKey("Location") && map.get("Location").get(0).equals("/mobile/")){
_map = new HashMap<String, List<String>>();
_map.put("Cookie", map.get("Set-Cookie"));
loggedin = true;
}
return _map != null? _map :map;
}
@Override
public void put(URI uri, Map<String, List<String>> map) throws IOException {
if(!loggedin && map.containsKey("Location") && map.get("Location").get(0).equals("/mobile/")){
_map = new HashMap<String, List<String>>();
_map.put("Cookie", map.get("Set-Cookie"));
loggedin = true;
}
}
});
}
/**
* Needs to be called after constructor to login
* @throws LoginFailedException Is thrown if login fails
*/
public void connect() throws LoginFailedException, IOException {
login();
verifyLogin();
}
private void login() throws IOException {
RequestBody formBody = new FormEncodingBuilder()
.add("username", _username)
.add("password", _password)
.build();
Request login = new Request.Builder()
.url(Constants.LOGIN_URL)
.post(formBody)
.build();
_browser.newCall(login).execute();
return;
}
/**
* Verifies login for the user after calling connect
* @return Returns true if the login was correct
* @throws LoginFailedException Is thrown if the login was incorrect
*/
public boolean verifyLogin() throws LoginFailedException, IOException {
// Check index page
Request index = new Request.Builder()
.url(Constants.INDEX_URL)
.build();
Response response = _browser.newCall(index).execute();
// Check to see if we find a course list
if (response != null) {
Jerry i = Jerry.jerry(response.body().string());
Node node = i.$(Constants.COURSE_LIST).get(0);
if (node != null) {
return true;
}
}
throw new LoginFailedException();
}
/**
* Returns a list of announcements
* @param course The course for which the announcements need to be retrieved
* @return Returns a list of announcements
*/
public List<Announcement> getAnnouncements(Course course) throws IOException {
List<Announcement> announcements = AnnouncementParser.getAnnouncements(this, course);
return announcements;
}
/**
* Returns a list of courses
* @return A list of courses for the current user
*/
public List<Course> getCourses() throws IOException {
return CourseParser.getCourses(this);
}
/**
* Returns a list of ducments for a given course
* @param course The course for which the documents needs to be retrieved
* @return A list of documents
*/
public List<Document> getDocuments(Course course) throws IOException {
List<Document> documents = DocumentParser.getDocuments(this, course);
return documents;
}
public OkHttpClient getClient() {
return this._browser;
}
/**
* Returns a valid download URL for a given document
* @param course The course in which the document is uploaded
* @param document The document
* @return A valid download URL for the document
*/
public String getDocumentDownloadURL(Course course, Document document) throws IOException {
Request request = new Request.Builder()
.url(Constants.AJAX_URL + course.getCode() + Constants.DOCUMENTS + document.getId())
.build();
Response response = _browser.newCall(request).execute();
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(response.body().string());
return element.getAsJsonObject().get("url").getAsString();
}
/**
* This method checks if the last request redirected us to login,
* meaning we have been logged out and logs us back in
*/
public void checkLogin(Response response) throws IOException {
if(response.request().httpUrl().toString().contains(Constants.LOGIN_URL)) {
login();
}
}
/**
* Returns a list of all events
* @return A list of all events
*/
public List<Event> getEvents() throws IOException {
return EventParser.getEvents(this);
}
/**
* Returns a list of all events in a timespan
* @param start Start of timespan
* @param end End of timespan
* @return A list of all events in a timespan
*/
public List<Event> getEvents(Date start, Date end) throws IOException {
return EventParser.getEvents(this, start, end);
}
}
|
import java.io.File;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Vector;
public abstract class BinaryDataFile extends BinaryData{
File file;
protected boolean compressed;
BinaryDataFile(String filename, int numInds, MarkerData md, String collection){
super(numInds,md,collection);
this.file = new File(filename);
}
public void checkFile(byte[] headers) throws IOException{
if (file != null){
if (file.length() != (numSNPs*bytesPerRecord) + headers.length){
if (file.length() == (numSNPs*bytesPerRecord) + 8){
//alternate Oxford format
//Change headers byte[] to be a new byte[] of the correct things as specified by numSNPs and numInds.
ByteBuffer buf = ByteBuffer.allocate(8);
buf.order(ByteOrder.LITTLE_ENDIAN);
// in the case of remote data we need to compare the total snps as this is the value in the header
buf.putInt(this.totNumSNPs);
if (file.getName().endsWith("bed") || file.getName().endsWith("gen.bin") ){
// the inds value in the header is the number of columns--three values per ind
buf.putInt(this.numInds*3);
}else if (file.getName().endsWith("bnt") || file.getName().endsWith("int.bin")){
// the inds value in the header is the number of columns--two values per ind
buf.putInt(this.numInds*2);
}
buf.clear();
headers = new byte[8];
buf.get(headers, 0, 8);
bntHeaderOffset = 8;
bedHeaderOffset = 8;
} else{
throw new IOException(file +
" is not properly formatted.\n(Incorrect length.)");
}
}
} else{
//this is a useless message, but it implies badness 10000
throw new IOException("File is null?!?");
}
//are the headers acceptable for this file?
BufferedInputStream binaryIS = new BufferedInputStream(new FileInputStream(file),8192);
byte[] fromFile = new byte[headers.length];
binaryIS.read(fromFile,0,headers.length);
for (int i = 0; i < headers.length; i++){
if (fromFile[i] != headers[i]){
throw new IOException(file +
" is not properly formatted.\n(Magic number is incorrect.)");
}
}
}
public Vector getRecord(String markerName){
//do some checks on getting the data and handle errors centrally
int snpIndex;
try {
if((snpIndex = md.getIndex(markerName,md.getSampleCollectionIndex(collection))) >= 0) {
return getRecord(snpIndex);
}
}catch(IOException ioe) {
//TODO: handle me
//TODO: I don't know anything about that SNP?
}
return(null);
}
public boolean isCompressed(){
return compressed;
}
abstract Vector getRecord(int index) throws IOException;
}
|
package cc.twittertools.post;
import static cc.twittertools.post.Tweet.userNameFromFile;
import it.unimi.dsi.fastutil.ints.Int2ShortMap;
import it.unimi.dsi.fastutil.ints.Int2ShortOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.longs.LongSet;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.Charsets;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ucl.feeney.bryan.numpy.CsrShortMatrixBuilder;
import cc.twittertools.util.FilesInFoldersIterator;
import cc.twittertools.words.Vectorizer;
import cc.twittertools.words.dict.Dictionary;
import cc.twittertools.words.dict.LookupDictionary;
import cc.twittertools.words.dict.ExcessUnmappableTokens;
/**
* Extracts paired features from tweets: one references the "text", one references the "event"
*
* The text features will include normal words, and optionally addressees and hash-tags. Hashtags
* can be encoded as normal words (i.e. with the hash marker removed) or as special words (i.e
* retaining the hash-marker).
*
* The event features contain the user ID, the post date, and optionally whether it was a retweet,
* the addressee identifier and [TODO the list of people the user follows.]
* @author bryanfeeney
*
*/
public class TweetFeatureExtractor implements Callable<Integer>
{
private static final int MAX_WORDS_PER_TWEET = 70;
private static final int MAX_USERS = 21000;
private static final int MAX_EXTRA_ADDRESSEES = 39000;
private static final int MAX_CORRUPTED_TWEETS_PER_FILE = 5;
private final static Logger LOG = LoggerFactory.getLogger(TweetFeatureExtractor.class);
/** If true remove all retweet markers from text */
private boolean stripRtMarkersFromText = false;
/** If true, don't include retweets in the output - skip them entirely */
private boolean stripRetweets = false;
/** If true, strip the hash tag marker from hashtags before tokenizing. Note hashtags, left alone, will not be stemed */
private boolean treatHashTagsAsWords = false;
/** If true create separate pairs of event and text matrices per author (e.g. for author topic modelling) */
private boolean aggregateByAuthor = false;
/** The minimum (inclusive) date for tweets. Tweets before this date are not included in the output. */
private DateTime minDateIncl;
/** The maximum (exclusive) date for tweets. Tweets on or after this date are not included in the output */
private DateTime maxDateExcl;
/** the full list of input files to process */
private final Path inputDir;
/** Directory of output files. At a minimum there are two, the event features matrix and the text features matrix. If aggregateByAuthor is true, there will be a matrix pair for every matrix. */
private final Path outputDir;
/** The text tokenizer */
private final Vectorizer vectorizer;
/** The specification of which features to encode */
private final FeatureSpecification featSpec;
/** dictionary of users (including addressees if we're using them) */
private final Dictionary userDict;
/** do we skip an entire tweet if we can't map a single token to an identifier */
private final boolean skipTweetOnUnmappableEventToken;
/** The minium amount of a tweets <em>words</em> that must be tokenized for the tweet to be accepted */
private final double minTokenizedAmt;
/** The minimum number of tokens a tweet must contain to be included in the output */
private final int minTokensPerTweet = 3;
/** How many tweets to process before we quit */
private int maxTweetsToProcess = Integer.MAX_VALUE;
/** If not null, then only tweets tweeted or retweeted from these accounts will be included */
private final Set<String> restrictedUsers;
/**
* Creates a new {@link TweetFeatureExtractor}
* @param inputDir the directory from which the raw tweets are read. This directory
* should contain many sub-directory, each sub-directory should contain several
* files (and only files), and all the files in the all the sub-directories should
* be lists of tweets.
* @param outputDir the directory to which the resulting matrices should be
* written.
* @param vectorizer a pre-configured vectorizer used to convert text to
* a feature vector.
* @param featureSpecification the side-information features which should be encoded
* and included in the output.
* @throws IOException
*/
public TweetFeatureExtractor(Path inputDir, Path outputDir, Vectorizer vectorizer, FeatureSpecification featureSpecification, Collection<String> restrictedUserList) throws IOException {
this.inputDir = inputDir;
this.outputDir = outputDir;
this.vectorizer = vectorizer;
this.featSpec = featureSpecification;
this.skipTweetOnUnmappableEventToken = true;
this.minTokenizedAmt = 2.0 / 3.0;
final int numAuthors;
if (restrictedUserList == null)
{ restrictedUsers = null;
numAuthors = MAX_USERS;
}
else
{ numAuthors = restrictedUserList.size();
restrictedUsers = new HashSet<>(numAuthors);
for (String user : restrictedUserList)
restrictedUsers.add (tidyAccountName (user));
}
int numUsers =
featSpec.isAddresseeInFeatures() ? numAuthors + MAX_EXTRA_ADDRESSEES
: featSpec.isAuthorInFeatures() ? numAuthors
: 0;
userDict = numUsers == 0 ? null : new LookupDictionary (numUsers);
}
/**
* Tidies an account name by trimming and lower-casing it.
*/
private final static String tidyAccountName (String accountName)
{ return accountName == null ? null : accountName.trim().toLowerCase();
}
/**
* Checks to see if tweets from the given account are to be included in the
* output
*/
private final boolean isTweetsFromThisAccountIncluded (String accountName)
{ return restrictedUsers == null ? true : restrictedUsers.contains(tidyAccountName (accountName));
}
/**
* Loads in all tweets, extracts features, encodes them, and writes the encoded
* features to disk. Returns the number of tweets processed.
*/
public Integer call() throws Exception
{ int tweetCount = 0;
if (aggregateByAuthor) // run several instances on subgroups of files based on author
{ Map<String, List<Path>> filesByUser = groupFilesByUser (inputDir);
for (Map.Entry<String, List<Path>> entry : filesByUser.entrySet())
{ String user = entry.getKey();
tweetCount += extractAndWriteFeatures (
entry.getValue().iterator(),
outputDir.resolve(user + "-words"),
outputDir.resolve(user + "-side")
);
}
} // for unit testing only, allow this to run on a single file if that file is less than a minute old.
// The time restriction to just to try to avoid accidental use
else if (! Files.isDirectory(inputDir) && isCreatedLessThanOneMinuteAgo(inputDir))
{ tweetCount = extractAndWriteFeatures (
Collections.singleton(inputDir).iterator(),
outputDir.resolve("words"),
outputDir.resolve("side")
);
} // the standard approach, process all files together in a single batch run.
else
{ try (FilesInFoldersIterator tweetFiles = new FilesInFoldersIterator(inputDir); )
{ tweetCount = extractAndWriteFeatures(
tweetFiles,
outputDir.resolve("words"),
outputDir.resolve("side")
);
}
}
// Write dictionaries out as a big Python script
try (BufferedWriter wtr = Files.newBufferedWriter(outputDir.resolve("dicts.py"), Charsets.UTF_8); )
{ wtr.write("#!/usr/bin/python\n");
wtr.write("# -*- coding: utf-8 -*-\n\n");
wtr.write(eventFeatureSchema());
wtr.write("\n\n");
userDict.writeAsPythonList("users", wtr);
wtr.write("\n\n");
vectorizer.getDict().writeAsPythonList("words", wtr);
wtr.write("\n\n");
}
// Then, just to be sure, write dictionaries out as a series of tab-delimited file
userDict.writeDelimited(outputDir.resolve("userdict.txt"), Charsets.UTF_8);
vectorizer.getDict().writeDelimited(outputDir.resolve("worddict.txt"), Charsets.UTF_8);
return tweetCount;
}
private boolean isCreatedLessThanOneMinuteAgo(Path file) throws IOException
{ return Files.readAttributes(file, BasicFileAttributes.class).creationTime().toMillis() >= (System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(1));
}
/**
* Read all files into memory, then group them by user, using the files' names
* to detect the username.
* @throws Exception
* @throws IOException
*/
private Map<String, List<Path>> groupFilesByUser(Path inputDir) throws IOException, Exception
{ Map<String, List<Path>> map = new HashMap<>();
try (FilesInFoldersIterator files = new FilesInFoldersIterator(inputDir); )
{ while (files.hasNext())
{ Path file = files.next();
String userName = userNameFromFile (file);
addToMultimap (map, userName, file);
}
}
return map;
}
/**
* A MultiMap is a map associating a list of values to a single key. This
* does the tedious job of creating the list if necessary before adding
* the value to that list.
*/
private <K, V> void addToMultimap(Map<K, List<V>> multimap, K key, V value) {
List<V> valueList = multimap.get(key);
if (valueList == null)
{ valueList = new ArrayList<>();
multimap.put (key, valueList);
}
valueList.add(value);
}
/**
* Given an iterator of files, and the names of two output files, extracts information
* relating to all possible tweets, and
* @throws Exception
*/
private int extractAndWriteFeatures (Iterator<Path> tweetFiles, Path wordsFile, Path eventsFile) throws Exception
{ Interval interval = new Interval(minDateIncl, maxDateExcl);
FeatureDimension dim = featSpec.dimensionality(userDict, interval);
CsrShortMatrixBuilder wordMatrix
= new CsrShortMatrixBuilder(vectorizer.getDict().capacity(), 2_500_000, 30);
CsrShortMatrixBuilder eventMatrix
= new CsrShortMatrixBuilder(dim.getTotal(), 2_500_000, 10);
Int2ShortMap wordFeatures = new Int2ShortOpenHashMap(MAX_WORDS_PER_TWEET);
Int2ShortMap eventFeatures = new Int2ShortOpenHashMap(featSpec.maxNonZeroFeatures());
wordFeatures.defaultReturnValue((short) 0);
eventFeatures.defaultReturnValue((short) 0);
int tweetCount = 0;
String lastAccount = "not_the_last_author";
LongSet tweetIDs = new LongOpenHashSet(100_000);
int skippedAsUnmappable = 0;
int skippedAsRetweet = 0;
// We accept 5 corrupted lines per file before abandoning it and moving onto the next
// file. For this reason the next-file loop is labelled.
Tweet tweet = null;
filesLoop:while (tweetFiles.hasNext())
{
int corruptedTweetCount = 0;
Path currentFile = tweetFiles.next();
LOG.info ("Processing tweets in file: " + currentFile);
try (SavedTweetReader rdr = new SavedTweetReader(currentFile); )
{
while (rdr.hasNext() && tweetCount < maxTweetsToProcess)
{
try
{ tweet = rdr.next();
if (! isTweetsFromThisAccountIncluded(tweet.getAccount()))
continue filesLoop; // all tweets in a file belong to a single account
// Do we include this tweet, or do we skip it.
if (stripRetweets && isRetweet(tweet))
{ ++skippedAsRetweet;
LOG.info("Retweets skipped: " + skippedAsRetweet + "/" + tweetCount + " (" + (100 * skippedAsRetweet / Math.max(1, tweetCount)) + "%)");
continue;
}
if (tweet.getLocalTime().isBefore(minDateIncl) || maxDateExcl.isBefore(tweet.getLocalTime()))
{ LOG.info("Skipping tweet posted on " + tweet.getLocalTime() + " as it's outside the set time-range");
continue;
}
// There are some duplicate tweets in the dataset. We <em>presume</em>
// files are sorted by name, and keep a track of each account's IDs
// so we can filter out already processed tweets.
String account = tweet.getAccount().trim().toLowerCase();
long tweetId = tweet.getId();
if (! account.equals(lastAccount))
{ lastAccount = account;
tweetIDs.clear();
}
if (tweetIDs.contains(tweetId))
{ continue;
}
tweetIDs.add(tweetId);
// TODO need some sort of "most-recent-date" idea for when we have an,
// incorrect date, which is something that occurs with retweets.
++tweetCount;
extractFeatures (tweet, dim, wordFeatures, eventFeatures);
wordMatrix.addRow(wordFeatures);
eventMatrix.addRow(eventFeatures);
}
catch (ExcessUnmappableTokens ute)
{ ++skippedAsUnmappable;
LOG.info("Tweets with excess unmappable tokens skipped : " + skippedAsUnmappable + "/" + tweetCount + " (" + (100 * skippedAsUnmappable / Math.max(1, tweetCount)) + "%). Here " + ute.getProportionTokenized() + " of this tweet was tokenized only: " + tweet.getMsg());
LOG.info("Original error was " + ute.getMessage());
}
catch (Exception e)
{ LOG.warn ("Error processing tweet from file " + currentFile + " : " + e.getMessage(), e);
if (++corruptedTweetCount >= MAX_CORRUPTED_TWEETS_PER_FILE)
{ LOG.warn ("Encountered " + corruptedTweetCount + " corrupted tweets in the current file, so skipping it. The current file is " + currentFile);
continue filesLoop; // skip this file.
}
}
}
LOG.info ("Total tweets processed thus far : " + tweetCount);
}
}
try
{ wordMatrix.writeToFile(wordsFile);
LOG.info ("Wrote tweet text features to " + wordsFile);
}
catch (IOException e)
{ LOG.error ("Error writing word features to Python sparse matrix file " + e.getMessage(), e);
}
try
{ eventMatrix.writeToFile(eventsFile);
LOG.info ("Wrote tweet side features to " + eventsFile);
}
catch (IOException e)
{ LOG.error ("Error writing side features to Python sparse matrix file " + e.getMessage(), e);
}
return tweetCount;
}
/**
* Checks is this a retweet. Uses three methods to infer this
* <ul><li>If the request ID and the tweet ID don't match, it's a retweet
* <li>If the account (inferred from the filename) and the author don't match, it's retweet
* <li>If the message contains a retweet marker ("RT") it's a retweet
* </ul>
*/
private boolean isRetweet(Tweet tweet)
{ return tweet.isRetweetFromId() || tweet.isRetweetFromMsg() || ! tweet.getAccount().equals(tweet.getAuthor());
}
/**
* Clears the given maps, extracts word and event features, encodes them, and
* then populates the maps with the encoded features. This is essentially a
* sparse vector representation.
* @param tweet the tweet from which featurse should be extracted
* @param dim the dimension of each of the side-information features.
* @param wordFeatures the features extracted from the text of the tweet
* @param eventFeatures the features extracted from other information about
* the tweet, see {@link FeatureSpecification} for more on these.
*/
private void extractFeatures(Tweet tweet, FeatureDimension dim, Int2ShortMap wordFeatures, Int2ShortMap eventFeatures)
{ List<String> addressees = extractWordFeatures(tweet, wordFeatures);
extractEventFeatures(tweet, dim, addressees, eventFeatures);
}
/**
* Creates a Python string writing out the schema for features
*/
private String eventFeatureSchema()
{ // NOTE Every time extractEventFeatures() is changed, this needs to be changed too
Interval interval = new Interval(minDateIncl, maxDateExcl);
FeatureDimension dim = featSpec.dimensionality(userDict, interval);
String result = "feats = dict()\n";
int step = 0;
if (featSpec.isAddresseeInFeatures())
{ result += "feats['addr'] = " + step + '\n';
step += dim.getAddresseeDim();
}
if (featSpec.isAuthorInFeatures())
{ result += "feats['author'] = " + step + '\n';
step += dim.getAuthorDim();
}
if (featSpec.isDayHourOfWeekInFeatures())
{ result += "feats['day_hour_of_week'] = " + step + '\n';
step += dim.getDayHourOfWeekDim();
}
if (featSpec.isDayOfWeekInFeatures())
{ result += "feats['day_of_week'] = " + step + '\n';
step += dim.getDayOfWeekDim();
}
if (featSpec.isDayOfYearInFeatures())
{ result += "feats['day_of_year'] = " + step + '\n';
step += dim.getDayOfWeekDim();
}
if (featSpec.isHourOfDayInFeatures())
{ result += "feats['hour_of_day'] = " + step + '\n';
step += dim.getHourOfDayDim();
}
if (featSpec.isWeekOfYearInFeatures())
{ result += "feats['week_of_year'] = " + step + '\n';
step += dim.getWeekOfYearDim();
}
if (featSpec.isMonthOfYearInFeatures())
{ result += "feats['month_of_year'] = " + step + '\n';
step += dim.getMonthOfYearDim();
}
if (featSpec.isRtInFeatures())
{ result += "feats['retweet'] = " + step + '\n';
step += dim.getRtDim();
}
if (featSpec.isInterceptInFeatures())
{ result += "feats['intercept'] = " + step + '\n';
step += dim.getInterceptDim();
}
return result;
}
/**
* Extracts and encodes features from the given tweet according to this
* class's configuration. The given map is cleared and filled with the
* encoded features.
*/
private void extractEventFeatures(Tweet tweet, FeatureDimension dim, List<String> addressees, Int2ShortMap eventFeatures)
{ // NOTE Change eventFeatureSchema() whenever you change this method
eventFeatures.clear();
short one = (short) 1;
int step = 0;
if (featSpec.isAddresseeInFeatures())
{ for (String addressee : addressees)
{ int userId = userDict.toInt(addressee);
if (userId == Dictionary.UNMAPPABLE_WORD)
if (skipTweetOnUnmappableEventToken)
throw new ExcessUnmappableTokens (0.5, "Tweet contains the unmappable addressee identifier " + addressee);
else
continue;
inc (eventFeatures, step + userId);
}
step += dim.getAddresseeDim();
}
if (featSpec.isAuthorInFeatures())
{ int authorId = userDict.toInt(tweet.getAccount());
if (authorId == Dictionary.UNMAPPABLE_WORD)
if (skipTweetOnUnmappableEventToken)
throw new ExcessUnmappableTokens (0.5, "Tweet contains the unmappable author identifier " + tweet.getAccount());
eventFeatures.put (step + authorId, one);
step += dim.getAuthorDim();
}
int dayOfWeek = tweet.getLocalTime().getDayOfWeek() - 1;
int hourOfDay = tweet.getLocalTime().getHourOfDay();
if (featSpec.isDayHourOfWeekInFeatures())
{ eventFeatures.put (step + (dayOfWeek * 24) + hourOfDay, one);
step += dim.getDayHourOfWeekDim();
}
if (featSpec.isDayOfWeekInFeatures())
{ eventFeatures.put (step + dayOfWeek, one);
step += dim.getDayOfWeekDim();
}
Interval interval = new Interval (minDateIncl, tweet.getLocalTime());
int days = (int) TimeUnit.MILLISECONDS.toDays(interval.toDurationMillis());
int weeks = days / 7;
int months = interval.toPeriod().getMonths();
if (featSpec.isDayOfYearInFeatures())
{ eventFeatures.put (step + dayOfWeek, one);
step += dim.getDayOfWeekDim();
}
if (featSpec.isHourOfDayInFeatures())
{ eventFeatures.put (step + tweet.getLocalTime().getHourOfDay(), one);
step += dim.getHourOfDayDim();
}
if (featSpec.isWeekOfYearInFeatures())
{ eventFeatures.put(step + weeks, one);
step += dim.getWeekOfYearDim();
}
if (featSpec.isMonthOfYearInFeatures())
{ eventFeatures.put (step + months, one);
step += dim.getMonthOfYearDim();
}
if (featSpec.isRtInFeatures())
{ if (tweet.isRetweetFromId() || tweet.isRetweetFromMsg())
eventFeatures.put (step, one);
step += dim.getRtDim();
}
if (featSpec.isInterceptInFeatures())
{ eventFeatures.put (step, one);
step += dim.getInterceptDim();
}
}
/**
* Tidies the tweet as specified in this class's configuration then encodes
* it into word features. The given map is cleared and filled with the
* encoded features.
*
* @param tweet the tweet to parse
* @param wordFeatures the bag of word ID counts.
* @return the list of addressees
*/
private List<String> extractWordFeatures(Tweet tweet, Int2ShortMap wordFeatures)
{ wordFeatures.clear();
String text = tweet.getMsg();
Pair<String, List<String>> textAndAddressees =
Sigil.ADDRESSEE.extractSigils(text);
// TODO implement this in the tokenizer?
if (stripRtMarkersFromText)
text = Sigil.RETWEET.stripFromMsg(text);
if (treatHashTagsAsWords)
text = text.replace ('
// TODO Test whether lucene analyzer will strip the hashes from hash
// tags, in which case we have to do this backwards by replacing
// # with HASH_TAG etc.
// TODO Awful hack ("text.toLowerCase()") as we haven't got a case-sensitive dictionary for URLs
int[] tokens = vectorizer.toInts(text.toLowerCase(), minTokenizedAmt);
if (tokens.length < minTokensPerTweet)
throw new ExcessUnmappableTokens ((double) tokens.length, "Tweet contains only " + tokens.length + " tokens, which is less than the minimum of " + minTokensPerTweet + " and so it has been excluded");
for (int wordId : tokens)
{ inc(wordFeatures, wordId);
}
return textAndAddressees.getRight();
}
/**
* Increments the value associated with the given key. If the key doesn't
* exist, it's assumed the value to be incremented is zero, so we just
* put 1.
*/
private void inc(Int2ShortMap map, int key)
{ map.put (key, (short) (map.get(key) + 1));
}
public boolean isStripRtMarkersFromText() {
return stripRtMarkersFromText;
}
public void setStripRtMarkersFromText(boolean stripRtMarkersFromText) {
this.stripRtMarkersFromText = stripRtMarkersFromText;
}
public boolean isStripRetweets() {
return stripRetweets;
}
public void setStripRetweets(boolean stripRetweets) {
this.stripRetweets = stripRetweets;
}
public boolean isTreatHashTagsAsWords() {
return treatHashTagsAsWords;
}
public void setTreatHashTagsAsWords(boolean treatHashTagsAsWords) {
this.treatHashTagsAsWords = treatHashTagsAsWords;
}
public boolean isAggregateByAuthor() {
return aggregateByAuthor;
}
public void setAggregateByAuthor(boolean aggregateByAuthor) {
this.aggregateByAuthor = aggregateByAuthor;
}
public DateTime getMinDateIncl() {
return minDateIncl;
}
public void setMinDateIncl(DateTime minDateIncl) {
this.minDateIncl = minDateIncl;
}
public DateTime getMaxDateExcl() {
return maxDateExcl;
}
public void setMaxDateExcl(DateTime maxDateExcl) {
this.maxDateExcl = maxDateExcl;
}
public Path getOutputDir()
{ return outputDir;
}
public Vectorizer getVectorizer()
{ return vectorizer;
}
public FeatureSpecification getFeatSpec()
{ return featSpec;
}
public Dictionary getUserDict()
{ return userDict;
}
}
|
package cn.springmvc.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springmvc.utils.HttpUtils;
import cn.springmvc.model.PriceTag;
import cn.springmvc.service.PriceTagService;
@Scope("prototype")
@Controller
@RequestMapping("/pricetags")
public class PriceTagController {
@Autowired
private PriceTagService priceTagService;
/**
* @author Josh Yang
* @description
* @date 2015-12-28
* @return JSON
*/
@ResponseBody
@RequestMapping(method=RequestMethod.GET)
public Map<String, Object> getAllPriceTags() {
List<PriceTag> tags = null;
try {
tags = priceTagService.selectAllPriceTags();
} catch (Exception e) {
e.printStackTrace();
return HttpUtils.generateResponse("1", "", null);
}
return HttpUtils.generateResponse("0", "", tags);
}
/**
* @author Josh Yang
* @description
* @date 2015-12-28
* @return JSON
*/
@ResponseBody
@RequestMapping(method=RequestMethod.POST)
public Map<String, Object> addNewPriceTag(@RequestBody PriceTag pt) {
try {
int result = priceTagService.insertPriceTag(pt);
if (result != 0) {
return HttpUtils.generateResponse("1", "", null);
}
} catch (Exception e) {
e.printStackTrace();
return HttpUtils.generateResponse("1", "", null);
}
return HttpUtils.generateResponse("0", "", null);
}
/**
* @author Josh Yang
* @description id
* @date 2015-12-28
* @return JSON
*/
@ResponseBody
@RequestMapping(value="/{id}",method=RequestMethod.GET)
public Map<String, Object> getPriceTagInfoById(@PathVariable String id) {
PriceTag pt = null;
try {
pt = priceTagService.selectPriceTagById(id);
} catch (Exception e) {
e.printStackTrace();
return HttpUtils.generateResponse("1", "", null);
}
return HttpUtils.generateResponse("0", "", pt);
}
/**
* @author Josh Yang
* @description id
* @date 2015-12-28
* @return JSON
*/
@ResponseBody
@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
public Map<String, Object> deletePriceTagById(@PathVariable String id) {
try {
int result = priceTagService.deletePriceTag(id);
if (result != 0) {
return HttpUtils.generateResponse("1", "", null);
}
} catch (Exception e) {
e.printStackTrace();
return HttpUtils.generateResponse("1", "", null);
}
return HttpUtils.generateResponse("0", "", null);
}
/**
* @author Josh Yang
* @description id
* @date 2015-12-28
* @return JSON
*/
@ResponseBody
@RequestMapping(value="/{id}", method=RequestMethod.PATCH)
public Map<String, Object> updatePriceTag(@PathVariable String id, @RequestBody PriceTag pt) {
PriceTag priceTag = null;
try {
int result = priceTagService.updatePriceTag(pt);
if (result != 0) {
return HttpUtils.generateResponse("1", "", null);
}
priceTag = priceTagService.selectPriceTagById(id);
} catch (Exception e) {
e.printStackTrace();
return HttpUtils.generateResponse("1", "", null);
}
return HttpUtils.generateResponse("0", "", priceTag);
}
public void getPriceTagsWithAjax() {
}
}
|
package co.phoenixlab.discord.stats;
import static java.lang.Math.*;
public class RunningAverage {
private double running;
private int count;
private double min;
private double max;
public RunningAverage() {
running = 0;
count = 0;
min = Double.MAX_VALUE;
max = 0D;
}
public void add(long val) {
running = (running * (double) count + (double) val) / (double) (count + 1);
count++;
min = min(min, val);
max = max(max, val);
}
public void add(int val) {
running = (running * (double) count + (double) val) / (double) (count + 1);
count++;
min = min(min, val);
max = max(max, val);
}
public void add(float val) {
running = (running * (double) count + (double) val) / (double) (count + 1);
count++;
min = min(min, val);
max = max(max, val);
}
public void add(double val) {
running = (running * (double) count + (double) val) / (double) (count + 1);
count++;
min = min(min, val);
max = max(max, val);
}
public double getRunningAverage() {
return running;
}
public int getSize() {
return count;
}
public double getMin() {
return min;
}
public double getMax() {
return max;
}
public String summary() {
return String.format("%.2f/%.2f/%.2f", min, running, max);
}
}
|
package com.aif.language.sentence;
import com.aif.language.common.ISplitter;
import com.aif.language.common.VisibilityReducedForTestPurposeOnly;
import java.util.*;
import java.util.stream.Collectors;
public class SentenceSplitter implements ISplitter<List<String>, List<String>> {
private final ISentenceSeparatorExtractor sentenceSeparatorExtractor;
public SentenceSplitter(final ISentenceSeparatorExtractor sentenceSeparatorExtractor) {
this.sentenceSeparatorExtractor = sentenceSeparatorExtractor;
}
public SentenceSplitter() {
this(ISentenceSeparatorExtractor.Type.STAT.getInstance());
}
@Override
public List<List<String>> split(final List<String> tokens) {
final Optional<List<Character>> optionalSeparators = sentenceSeparatorExtractor.extract(tokens);
if (!optionalSeparators.isPresent()) {
return new ArrayList<List<String>>(){{add(tokens);}};
}
final List<Character> separators = optionalSeparators.get();
final List<Boolean> listOfPositions = SentenceSplitter.mapToBooleans(tokens, separators);
final SentenceIterator sentenceIterator = new SentenceIterator(tokens, listOfPositions);
final List<List<String>> sentences = new ArrayList<>();
while (sentenceIterator.hasNext()) {
sentences.add(sentenceIterator.next());
}
sentences.forEach(sentence -> prepareSentences(sentence, separators));
return sentences
.parallelStream()
.map(sentence -> SentenceSplitter.prepareSentences(sentence, separators))
.collect(Collectors.toList());
}
@VisibilityReducedForTestPurposeOnly
static List<String> prepareSentences(final List<String> sentence, final List<Character> separators) {
final List<String> preparedTokens = new ArrayList<>();
for (String token: sentence) {
preparedTokens.addAll(prepareToken(token, separators));
}
return preparedTokens;
}
@VisibilityReducedForTestPurposeOnly
static List<String> prepareToken(final String token, final List<Character> separators) {
final List<String> tokens = new ArrayList<>(3);
final int lastPosition = lastNonSeparatorPosition(token, separators);
final int firstPosition = firstNonSeparatorPosition(token, separators);
if (firstPosition != 0) {
tokens.add(token.substring(0, firstPosition));
}
tokens.add(token.substring(firstPosition, lastPosition));
if (lastPosition != token.length()) {
tokens.add(token.substring(lastPosition, token.length()));
}
return tokens;
}
@VisibilityReducedForTestPurposeOnly
static int firstNonSeparatorPosition(final String token, final List<Character> separarors) {
if (!separarors.contains(token.charAt(0))) {
return 0;
}
int i = 0;
while (i < token.length() && separarors.contains(token.charAt(i))) {
i++;
}
if (i == token.length()) {
return 0;
}
return i;
}
@VisibilityReducedForTestPurposeOnly
static int lastNonSeparatorPosition(final String token, final List<Character> separators) {
if (!separators.contains(token.charAt(token.length() - 1))) {
return token.length();
}
int i = token.length() - 1;
while (i > 0 && separators.contains(token.charAt(i))) {
i
}
i++;
if (i == 0) {
return token.length();
}
return i;
}
@VisibilityReducedForTestPurposeOnly
static List<Boolean> mapToBooleans(final List<String> tokens, final List<Character> separators) {
final List<Boolean> result = new ArrayList<>(tokens.size());
for (int i = 0; i < tokens.size(); i++) {
final String token = tokens.get(i);
if (separators.contains(token.charAt(token.length() - 1))) {
result.add(true);
} else if (i != tokens.size() - 1 && separators.contains(token.charAt(0))) {
result.add(true);
} else {
result.add(false);
}
}
return result;
}
@VisibilityReducedForTestPurposeOnly
static class SentenceIterator implements Iterator<List<String>> {
private final List<String> tokens;
private final List<Boolean> endTokens;
private int currentPosition = 0;
public SentenceIterator(List<String> tokens, List<Boolean> endTokens) {
assert tokens != null;
assert endTokens != null;
assert tokens.size() == endTokens.size();
this.tokens = tokens;
this.endTokens = endTokens;
}
@Override
public boolean hasNext() {
return currentPosition != tokens.size();
}
@Override
public List<String> next() {
final List<String> sentence = getNextSentence();
return sentence;
}
private List<String> getNextSentence() {
final int oldIndex = currentPosition;
currentPosition = getNextTrueIndex();
return this.tokens.subList(oldIndex, currentPosition);
}
private int getNextTrueIndex() {
int startIndex = currentPosition;
if (endTokens.size() == startIndex) {
return startIndex;
}
do {
if (endTokens.get(startIndex)) {
startIndex++;
return startIndex;
}
startIndex++;
} while(startIndex < endTokens.size() - 1);
return startIndex + 1;
}
}
}
|
package com.alibaba.excel.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.alibaba.excel.converters.AutoConverter;
import com.alibaba.excel.converters.Converter;
/**
* @author jipengfei
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ExcelProperty {
/**
* The name of the sheet header.
*
* <p>
* write: It automatically merges when you have more than one head
* <p>
* read: When you have multiple heads, take the first one
*
* @return The name of the sheet header
*/
String[] value() default {""};
/**
* Index of column
*
* Read or write it on the index of column,If it's equal to -1, it's sorted by Java class.
*
* priority: index > order > default sort
*
* @return Index of column
*/
int index() default -1;
/**
* Defines the sort order for an column.
*
* priority: index > order > default sort
*
* @return Order of column
*/
int order() default Integer.MAX_VALUE;
/**
* Force the current field to use this converter.
*
* @return Converter
*/
Class<? extends Converter> converter() default AutoConverter.class;
/**
*
* default @see com.alibaba.excel.util.TypeUtil if default is not meet you can set format
*
* @return Format string
* @deprecated please use {@link com.alibaba.excel.annotation.format.DateTimeFormat}
*/
@Deprecated
String format() default "";
}
|
// Implementation of the Blueprints Interface for ArangoDB by triAGENS GmbH Cologne.
package com.arangodb.blueprints;
import java.util.Iterator;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.arangodb.blueprints.client.ArangoDBBaseQuery;
import com.arangodb.blueprints.client.ArangoDBException;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.GraphQuery;
import com.tinkerpop.blueprints.Predicate;
import com.tinkerpop.blueprints.Vertex;
public class ArangoDBGraphQuery extends ArangoDBQuery implements GraphQuery {
/**
* the logger
*/
private static final Logger logger = Logger.getLogger(ArangoDBVertexIterable.class);
/**
* Creates a graph query for a ArangoDB graph
*
* @param graph
* the ArangoDB graph
*/
public ArangoDBGraphQuery(final ArangoDBGraph graph) {
super(graph);
}
public <T extends Comparable<T>> ArangoDBGraphQuery has(final String key, final T value, final Compare compare) {
super.has(key, value, compare);
return this;
}
@Override
public Iterable<Edge> edges() {
ArangoDBBaseQuery query;
try {
query = graph.getClient().getGraphEdges(graph.getRawGraph(), propertyFilter, new Vector<String>(), limit,
count);
return new ArangoDBEdgeIterable(graph, query);
} catch (ArangoDBException e) {
logger.debug("error while reading edges", e);
return new ArangoDBEdgeIterable(graph, null);
}
}
@Override
public Iterable<Vertex> vertices() {
ArangoDBBaseQuery query;
try {
query = graph.getClient().getGraphVertices(graph.getRawGraph(), propertyFilter, limit, count);
return new ArangoDBVertexIterable(graph, query);
} catch (ArangoDBException e) {
logger.debug("error while reading vertices", e);
return new ArangoDBVertexIterable(graph, null);
}
}
/**
* Executes the query and returns the number of result elements
*
* @return number of elements
*/
public long count() {
ArangoDBBaseQuery query;
try {
query = graph.getClient().getGraphEdges(graph.getRawGraph(), propertyFilter, new Vector<String>(), limit,
true);
return query.getCursorResult().getCount();
} catch (ArangoDBException e) {
logger.error("error in AQL query", e);
}
return -1;
}
/**
* Executes the query and returns the identifiers of result elements
*
* @return the identifiers of result elements
*/
public Iterator<String> vertexIds() {
return new VertexIterator(vertices());
}
@Override
public ArangoDBGraphQuery has(String key) {
super.has(key);
return this;
}
@Override
public ArangoDBGraphQuery hasNot(String key) {
super.hasNot(key);
return this;
}
@Override
public ArangoDBGraphQuery has(String key, Object value) {
super.has(key, value);
return this;
}
@Override
public ArangoDBGraphQuery hasNot(String key, Object value) {
super.hasNot(key, value);
return this;
}
@Override
public ArangoDBGraphQuery has(String key, Predicate prdct, Object value) {
super.has(key, prdct, value);
return this;
}
@Override
public <T extends Comparable<?>> ArangoDBGraphQuery interval(String key, T startValue, T endValue) {
super.interval(key, startValue, endValue);
return this;
}
@Override
public ArangoDBGraphQuery limit(int limit) {
super.limit(limit);
return this;
}
class VertexIterator implements Iterator<String> {
private Iterator<Vertex> iter = vertices().iterator();
public VertexIterator(Iterable<Vertex> iterable) {
iter = iterable.iterator();
}
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public String next() {
if (!iter.hasNext()) {
return null;
}
Vertex v = iter.next();
if (v == null) {
return null;
}
return v.getId().toString();
}
@Override
public void remove() {
iter.remove();
}
}
}
|
package com.auth0.client.mgmt;
import com.auth0.json.mgmt.EmailTemplate;
import com.auth0.net.CustomRequest;
import com.auth0.net.Request;
import com.auth0.utils.Asserts;
import com.fasterxml.jackson.core.type.TypeReference;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
@SuppressWarnings({"WeakerAccess", "unused"})
public class EmailTemplatesEntity extends BaseManagementEntity {
public static final String TEMPLATE_VERIFY_EMAIL = "verify_email";
public static final String TEMPLATE_RESET_EMAIL = "reset_email";
public static final String TEMPLATE_WELCOME_EMAIL = "welcome_email";
public static final String TEMPLATE_BLOCKED_ACCOUNT = "blocked_account";
public static final String TEMPLATE_STOLEN_CREDENTIALS = "stolen_credentials";
public static final String TEMPLATE_ENROLLMENT_EMAIL = "enrollment_email";
public static final String TEMPLATE_CHANGE_PASSWORD = "change_password";
public static final String TEMPLATE_PASSWORD_RESET = "password_reset";
public static final String TEMPLATE_MFA_OOB_CODE = "mfa_oob_code";
EmailTemplatesEntity(OkHttpClient client, HttpUrl baseUrl, String apiToken) {
super(client, baseUrl, apiToken);
}
public Request<EmailTemplate> get(String templateName) {
Asserts.assertNotNull(templateName, "template name");
HttpUrl.Builder builder = baseUrl
.newBuilder()
.addPathSegments("api/v2/email-templates")
.addPathSegment(templateName);
String url = builder.build().toString();
CustomRequest<EmailTemplate> request = new CustomRequest<>(client, url, "GET", new TypeReference<EmailTemplate>() {
});
request.addHeader("Authorization", "Bearer " + apiToken);
return request;
}
public Request<EmailTemplate> create(EmailTemplate template) {
Asserts.assertNotNull(template, "template");
String url = baseUrl
.newBuilder()
.addPathSegments("api/v2/email-templates")
.build()
.toString();
CustomRequest<EmailTemplate> request = new CustomRequest<>(this.client, url, "POST", new TypeReference<EmailTemplate>() {
});
request.addHeader("Authorization", "Bearer " + apiToken);
request.setBody(template);
return request;
}
public Request<EmailTemplate> update(String templateName, EmailTemplate template) {
Asserts.assertNotNull(templateName, "template name");
Asserts.assertNotNull(template, "template");
String url = baseUrl
.newBuilder()
.addPathSegments("api/v2/email-templates")
.addPathSegment(templateName)
.build()
.toString();
CustomRequest<EmailTemplate> request = new CustomRequest<>(this.client, url, "PATCH", new TypeReference<EmailTemplate>() {
});
request.addHeader("Authorization", "Bearer " + apiToken);
request.setBody(template);
return request;
}
}
|
package com.elastic.support.diagnostics;
import com.beust.jcommander.JCommander;
import com.elastic.support.diagnostics.chain.DiagnosticChainExec;
import com.elastic.support.diagnostics.chain.DiagnosticContext;
import com.elastic.support.util.ArchiveUtils;
import com.elastic.support.util.SystemProperties;
import com.elastic.support.util.SystemUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Diagnostic {
private InputParams inputs = new InputParams();
private DiagnosticChainExec dc = new DiagnosticChainExec();
private DiagnosticContext ctx = new DiagnosticContext(inputs);
private Logger logger = LogManager.getLogger();
private boolean proceedToRun = true;
Diagnostic(String args[]) {
logger.info("Validating inputs...");
ctx.setInputParams(inputs);
JCommander jc = new JCommander(inputs);
jc.setCaseSensitiveOptions(true);
try {
jc.parse(args);
if(! inputs.getDiagType().equalsIgnoreCase(Constants.LOCAL_DIAG)){
if(StringUtils.isEmpty(inputs.getHost())){
throw new RuntimeException("Inputs error: You must enter the hostname of a running node within the cluster, preferably on the host you are running the diagnostic from.");
}
}
if (!validateAuth(inputs)) {
throw new RuntimeException("Inputs error: If authenticating both username and password are required.");
}
if (inputs.isHelp()) {
jc.usage();
proceedToRun = false;
return;
}
// Set up the output directory
logger.info("Creating temp directory.");
createOutputDir(ctx);
logger.info("Created temp directory: {}", ctx.getTempDir());
// Start logging to file
SystemUtils.createFileAppender(ctx.getTempDir(), "diagnostics.log");
logger.info("Configuring log file.");
} catch (RuntimeException re) {
logger.error("Error during diagnostic initialization: {}", re.getMessage());
jc.usage();
return;
} catch (Exception e) {
logger.error("Error during diagnostic initialization", e);
return;
}
}
public boolean isProceedToRun(){
return proceedToRun;
}
void exec() {
try {
int reps = inputs.getReps();
long interval = inputs.getInterval() * 1000;
if (reps > 1) {
for (int i = 1; i <= reps; i++) {
ctx.setCurrentRep(i);
if (inputs.getDiagType().equalsIgnoreCase(Constants.STANDARD_DIAG) && i < (reps)) {
inputs.setNoLogs(true);
} else {
inputs.setNoLogs(false);
}
dc.runDiagnostic(ctx);
System.out.println("Run " + i + " of " + reps + " completed.");
if (i < reps) {
logger.info("Next run will occur in " + inputs.getInterval() + " seconds.\n");
Thread.sleep(interval);
}
}
} else {
dc.runDiagnostic(ctx);
}
} catch (Exception re) {
logger.error("Execution Error", re);
} finally {
createArchive(ctx);
SystemUtils.cleanup(ctx.getTempDir());
}
}
private boolean validateAuth(InputParams inputs) {
String ptPassword = inputs.getPlainTextPassword();
String userName = inputs.getUsername();
String password = inputs.getPassword();
if (!"".equals(ptPassword)) {
password = ptPassword;
inputs.setPassword(ptPassword);
}
return !((userName != null && password == null) || (password != null && userName == null));
}
private void createOutputDir(DiagnosticContext context) {
// Set up where we want to put the results - it may come in from the command line
String outputDir = formatOutputDir(context.getInputParams());
context.setOutputDir(outputDir);
logger.info("Results will be written to: " + outputDir);
String diagType = context.getInputParams().getDiagType();
if (!diagType.equals(Constants.ES_DIAG_DEFAULT)) {
context.setDiagName(diagType + "-" + Constants.ES_DIAG);
}
else {
context.setDiagName(Constants.ES_DIAG);
}
String tempDir = outputDir + SystemProperties.fileSeparator + context.getDiagName();
context.setTempDir(tempDir);
// Create the temp directory - delete if first if it exists from a previous run
try {
FileUtils.deleteDirectory(new File(tempDir));
Files.createDirectories(Paths.get(tempDir));
} catch (IOException e) {
logger.error("Temp dir could not be created", e);
throw new RuntimeException("Could not create temp directory - see logs for details.");
}
logger.info("Creating {} as temporary directory.", tempDir);
}
private String formatOutputDir(InputParams inputs) {
if ("cwd".equalsIgnoreCase(inputs.getOutputDir())) {
return SystemProperties.userDir;
} else {
return inputs.getOutputDir();
}
}
private void createArchive(DiagnosticContext context) {
logger.info("Archiving diagnostic results.");
try {
String archiveFilename = SystemProperties.getFileDateString();
if (context.getInputParams().getReps() > 1) {
int currentRep = context.getCurrentRep();
if (currentRep == 1) {
context.setAttribute("archiveFileName", archiveFilename);
}
archiveFilename = context.getStringAttribute("archiveFileName") + "-run-" + currentRep;
}
String dir = context.getTempDir();
ArchiveUtils archiveUtils = new ArchiveUtils();
archiveUtils.createArchive(dir, archiveFilename);
} catch (Exception ioe) {
logger.error("Couldn't create archive. {}", ioe);
}
}
}
|
// FlexReader.java
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.XMLTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.TiffParser;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class FlexReader extends FormatReader {
// -- Constants --
/** Custom IFD entry for Flex XML. */
public static final int FLEX = 65200;
public static final String FLEX_SUFFIX = "flex";
public static final String MEA_SUFFIX = "mea";
public static final String RES_SUFFIX = "res";
public static final String[] MEASUREMENT_SUFFIXES =
new String[] {MEA_SUFFIX, RES_SUFFIX};
public static final String[] SUFFIXES =
new String[] {FLEX_SUFFIX, MEA_SUFFIX};
public static final String SCREENING = "Screening";
public static final String ARCHIVE = "Archive";
// -- Static fields --
/**
* Mapping from server names stored in the .mea file to actual server names.
*/
private static HashMap<String, String[]> serverMap =
new HashMap<String, String[]>();
// -- Fields --
/** Scale factor for each image. */
protected double[][][] factors;
/** Camera binning values. */
private int binX, binY;
private int plateCount;
private int wellCount;
private int fieldCount;
private int wellRows, wellColumns;
private Vector<String> channelNames;
private Vector<Float> xPositions, yPositions;
private Vector<Float> xSizes, ySizes;
private Vector<String> cameraIDs, objectiveIDs, lightSourceIDs;
private HashMap<String, Vector<String>> lightSourceCombinationIDs;
private Vector<String> cameraRefs, binnings, objectiveRefs;
private Vector<String> lightSourceCombinationRefs;
private Vector<String> filterSets;
private HashMap<String, String> filterSetMap;
private Vector<String> measurementFiles;
private String plateName, plateBarcode;
private int nRows = 0, nCols = 0;
/**
* List of .flex files belonging to this dataset.
* Indices into the array are the well row and well column.
*/
private String[][] flexFiles;
private IFDList[][] ifds;
/** Specifies the row and column index into 'flexFiles' for a given well. */
private int[][] wellNumber;
// -- Constructor --
/** Constructs a new Flex reader. */
public FlexReader() { super("Evotec Flex", SUFFIXES); }
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> files = new Vector<String>();
files.addAll(measurementFiles);
if (!noPixels) {
int[] lengths = new int[] {fieldCount, wellCount, plateCount};
int[] pos = FormatTools.rasterToPosition(lengths, getSeries());
int row = wellCount == 1 ? 0 : wellNumber[pos[1]][0];
int col = wellCount == 1 ? 0 : wellNumber[pos[1]][1];
files.add(flexFiles[row][col]);
}
return files.toArray(new String[files.size()]);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int[] lengths = new int[] {fieldCount, wellCount, plateCount};
int[] pos = FormatTools.rasterToPosition(lengths, getSeries());
int imageNumber = getImageCount() * pos[0] + no;
int wellRow = wellNumber[pos[1]][0];
int wellCol = wellNumber[pos[1]][1];
if (wellCount == 1) {
wellRow = 0;
wellCol = 0;
}
IFD ifd = ifds[wellRow][wellCol].get(imageNumber);
RandomAccessInputStream s =
new RandomAccessInputStream(flexFiles[wellRow][wellCol]);
TiffParser tp = new TiffParser(s);
int nBytes = ifd.getBitsPerSample()[0] / 8;
// expand pixel values with multiplication by factor[no]
byte[] bytes = tp.getSamples(ifd, buf, x, y, w, h);
s.close();
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int num = bytes.length / bpp;
double factor = factors[wellRow][wellCol][imageNumber];
if (factor != 1d || nBytes != bpp) {
for (int i=num-1; i>=0; i
int q = nBytes == 1 ? bytes[i] & 0xff :
DataTools.bytesToInt(bytes, i * bpp, bpp, isLittleEndian());
q = (int) (q * factor);
DataTools.unpackBytes(q, buf, i * bpp, bpp, isLittleEndian());
}
}
else {
System.arraycopy(bytes, 0, buf, 0, bytes.length);
}
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
factors = null;
binX = binY = 0;
plateCount = wellCount = fieldCount = 0;
channelNames = null;
measurementFiles = null;
xSizes = ySizes = null;
cameraIDs = objectiveIDs = lightSourceIDs = null;
lightSourceCombinationIDs = null;
lightSourceCombinationRefs = null;
cameraRefs = objectiveRefs = binnings = null;
wellRows = wellColumns = 0;
xPositions = yPositions = null;
filterSets = null;
filterSetMap = null;
plateName = plateBarcode = null;
nRows = nCols = 0;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
debug("FlexReader.initFile(" + id + ")");
super.initFile(id);
measurementFiles = new Vector<String>();
if (id.toLowerCase().endsWith(".flex")) {
initFlexFile(id);
}
else initMeaFile(id);
}
// -- Helper methods --
/** Initialize the dataset from a .mea file. */
private void initMeaFile(String id) throws FormatException, IOException {
Location file = new Location(id).getAbsoluteFile();
measurementFiles.add(file.getAbsolutePath());
// parse the .mea file to get a list of .flex files
RandomAccessInputStream s = new RandomAccessInputStream(id);
MeaHandler handler = new MeaHandler();
String xml = s.readString((int) s.length());
s.close();
XMLTools.parseXML(xml, handler);
Vector<String> flex = handler.getFlexFiles();
if (flex.size() == 0) {
debug("Could not build .flex list from .mea.");
String[] files = findFiles(file);
if (files != null) {
for (String f : files) {
if (checkSuffix(f, FLEX_SUFFIX)) flex.add(f);
}
}
if (flex.size() == 0) {
throw new FormatException(".flex files were not found. " +
"Did you forget to specify the server names?");
}
}
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
groupFiles(flex.toArray(new String[flex.size()]), store);
populateMetadataStore(store);
}
private void initFlexFile(String id) throws FormatException, IOException {
boolean doGrouping = true;
Location currentFile = new Location(id).getAbsoluteFile();
try {
String name = currentFile.getName();
int[] well = getWell(name);
if (well[0] > nRows) nRows = well[0];
if (well[1] > nCols) nCols = well[1];
}
catch (NumberFormatException e) {
traceDebug(e);
doGrouping = false;
}
if (!isGroupFiles()) doGrouping = false;
if (isGroupFiles()) {
try {
findFiles(currentFile);
}
catch (NullPointerException e) {
traceDebug(e);
}
catch (IOException e) {
traceDebug(e);
}
if (measurementFiles.size() == 0) {
warn("Measurement files not found.");
}
}
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
Vector<String> flex = new Vector<String>();
if (doGrouping) {
// group together .flex files that are in the same directory
Location dir = currentFile.getParentFile();
String[] files = dir.list(true);
for (String file : files) {
// file names should be nnnnnnnnn.flex, where 'n' is 0-9
if (file.endsWith(".flex") && file.length() == 14) {
flex.add(new Location(dir, file).getAbsolutePath());
}
else {
doGrouping = false;
break;
}
}
}
String[] files = doGrouping ? flex.toArray(new String[flex.size()]) :
new String[] {currentFile.getAbsolutePath()};
groupFiles(files, store);
populateMetadataStore(store);
}
private void populateMetadataStore(MetadataStore store) {
MetadataTools.populatePixels(store, this, true);
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
Location currentFile = new Location(getCurrentFile()).getAbsoluteFile();
if (plateName == null) plateName = currentFile.getParentFile().getName();
if (plateBarcode != null) plateName = plateBarcode + " " + plateName;
store.setPlateName(plateName, 0);
store.setPlateRowNamingConvention("A", 0);
store.setPlateColumnNamingConvention("1", 0);
int[] lengths = new int[] {fieldCount, wellCount, plateCount};
for (int row=0; row<wellRows; row++) {
for (int col=0; col<wellColumns; col++) {
store.setWellRow(new Integer(row), 0, row * wellColumns + col);
store.setWellColumn(new Integer(col), 0, row * wellColumns + col);
}
}
for (int i=0; i<getSeriesCount(); i++) {
int[] pos = FormatTools.rasterToPosition(lengths, i);
String imageID = MetadataTools.createLSID("Image", i);
store.setImageID(imageID, i);
store.setImageInstrumentRef(instrumentID, i);
char wellRow = (char) ('A' + wellNumber[pos[1]][0]);
store.setImageName("Well " + wellRow + "-" + (wellNumber[pos[1]][1] + 1) +
"; Field #" + (pos[0] + 1), i);
int seriesIndex = i * getImageCount();
if (seriesIndex < objectiveRefs.size()) {
store.setObjectiveSettingsObjective(objectiveRefs.get(seriesIndex), i);
}
if (seriesIndex < lightSourceCombinationRefs.size()) {
String lightSourceCombo = lightSourceCombinationRefs.get(seriesIndex);
Vector<String> lightSources =
lightSourceCombinationIDs.get(lightSourceCombo);
for (int c=0; c<getEffectiveSizeC(); c++) {
int index = i * getImageCount() + c;
if (index < cameraRefs.size()) {
store.setDetectorSettingsDetector(cameraRefs.get(index), i, c);
}
if (index < binnings.size()) {
store.setDetectorSettingsBinning(binnings.get(index), i, c);
}
if (lightSources != null && c < lightSources.size()) {
store.setLightSourceSettingsLightSource(lightSources.get(c), i, c);
}
else if (c > 0 && lightSources != null && lightSources.size() == 1) {
store.setLightSourceSettingsLightSource(lightSources.get(0), i, c);
}
if (index < filterSets.size()) {
String filterSetID = filterSetMap.get(filterSets.get(index));
store.setLogicalChannelFilterSet(filterSetID, i, c);
}
}
}
int sizeIndex = i * getImageCount();
if (sizeIndex < xSizes.size()) {
store.setDimensionsPhysicalSizeX(xSizes.get(sizeIndex), i, 0);
}
if (sizeIndex < ySizes.size()) {
store.setDimensionsPhysicalSizeY(ySizes.get(sizeIndex), i, 0);
}
int well = wellNumber[pos[1]][0] * wellColumns + wellNumber[pos[1]][1];
if (wellRows == 0 && wellColumns == 0) {
well = pos[1];
store.setWellRow(new Integer(wellNumber[pos[1]][0]), pos[2], pos[1]);
store.setWellColumn(new Integer(wellNumber[pos[1]][1]), pos[2], pos[1]);
}
store.setWellSampleIndex(new Integer(i), pos[2], well, pos[0]);
store.setWellSampleImageRef(imageID, pos[2], well, pos[0]);
if (pos[0] < xPositions.size()) {
store.setWellSamplePosX(xPositions.get(pos[0]), pos[2], well, pos[0]);
}
if (pos[0] < yPositions.size()) {
store.setWellSamplePosY(yPositions.get(pos[0]), pos[2], well, pos[0]);
}
}
}
/**
* Returns a two-element array containing the well row and well column
* corresponding to the given file.
*/
private int[] getWell(String file) {
String name = file.substring(file.lastIndexOf(File.separator) + 1);
if (name.length() == 14) {
// expect nnnnnnnnn.flex
try {
int row = Integer.parseInt(name.substring(0, 3)) - 1;
int col = Integer.parseInt(name.substring(3, 6)) - 1;
return new int[] {row, col};
}
catch (NumberFormatException e) { }
}
return new int[] {0, 0};
}
/**
* Returns the IFDs of the first well that has data. May not be
* <code>[0][0]</code> as the acquisition may have been column or row offset.
* @return List of the first well's IFDs.
*/
private IFDList firstWellIfds() {
for (int i = 0; i < ifds.length; i++) {
for (int j = 0; j < ifds[i].length; j++) {
if (ifds[i][j] != null) return ifds[i][j];
}
}
return null;
}
/**
* Parses XML metadata from the Flex file corresponding to the given well.
* If the 'firstFile' flag is set, then the core metadata is also
* populated.
*/
private void parseFlexFile(int currentWell, int wellRow, int wellCol,
boolean firstFile, MetadataStore store)
throws FormatException, IOException
{
if (flexFiles[wellRow][wellCol] == null) return;
if (channelNames == null) channelNames = new Vector<String>();
if (xPositions == null) xPositions = new Vector<Float>();
if (yPositions == null) yPositions = new Vector<Float>();
if (xSizes == null) xSizes = new Vector<Float>();
if (ySizes == null) ySizes = new Vector<Float>();
if (cameraIDs == null) cameraIDs = new Vector<String>();
if (lightSourceIDs == null) lightSourceIDs = new Vector<String>();
if (objectiveIDs == null) objectiveIDs = new Vector<String>();
if (lightSourceCombinationIDs == null) {
lightSourceCombinationIDs = new HashMap<String, Vector<String>>();
}
if (lightSourceCombinationRefs == null) {
lightSourceCombinationRefs = new Vector<String>();
}
if (cameraRefs == null) cameraRefs = new Vector<String>();
if (objectiveRefs == null) objectiveRefs = new Vector<String>();
if (binnings == null) binnings = new Vector<String>();
if (filterSets == null) filterSets = new Vector<String>();
if (filterSetMap == null) filterSetMap = new HashMap<String, String>();
// parse factors from XML
IFD ifd = ifds[wellRow][wellCol].get(0);
String xml = XMLTools.sanitizeXML(ifd.getIFDStringValue(FLEX, true));
Vector<String> n = new Vector<String>();
Vector<String> f = new Vector<String>();
DefaultHandler handler =
new FlexHandler(n, f, store, firstFile, currentWell);
XMLTools.parseXML(xml.getBytes(), handler);
if (firstFile) populateCoreMetadata(wellRow, wellCol, n);
int totalPlanes = getSeriesCount() * getImageCount();
// verify factor count
int nsize = n.size();
int fsize = f.size();
if (nsize != fsize || nsize != totalPlanes) {
warnDebug("mismatch between image count, " +
"names and factors (count=" + totalPlanes +
", names=" + nsize + ", factors=" + fsize + ")");
}
for (int i=0; i<nsize; i++) addGlobalMeta("Name " + i, n.get(i));
for (int i=0; i<fsize; i++) addGlobalMeta("Factor " + i, f.get(i));
// parse factor values
factors[wellRow][wellCol] = new double[totalPlanes];
int max = 0;
for (int i=0; i<fsize; i++) {
String factor = f.get(i);
double q = 1;
try {
q = Double.parseDouble(factor);
}
catch (NumberFormatException exc) {
warnDebug("invalid factor #" + i + ": " + factor);
}
if (i < factors[wellRow][wellCol].length) {
factors[wellRow][wellCol][i] = q;
if (q > factors[wellRow][wellCol][max]) max = i;
}
}
if (fsize < factors[wellRow][wellCol].length) {
Arrays.fill(factors[wellRow][wellCol], fsize,
factors[wellRow][wellCol].length, 1);
}
// determine pixel type
if (factors[wellRow][wellCol][max] > 256) {
core[0].pixelType = FormatTools.UINT32;
}
else if (factors[wellRow][wellCol][max] > 1) {
core[0].pixelType = FormatTools.UINT16;
}
for (int i=1; i<core.length; i++) {
core[i].pixelType = getPixelType();
}
}
/** Populate core metadata using the given list of image names. */
private void populateCoreMetadata(int wellRow, int wellCol,
Vector<String> imageNames)
throws FormatException
{
if (getSizeC() == 0 && getSizeT() == 0) {
Vector<String> uniqueChannels = new Vector<String>();
for (int i=0; i<imageNames.size(); i++) {
String name = imageNames.get(i);
String[] tokens = name.split("_");
if (tokens.length > 1) {
// fields are indexed from 1
int fieldIndex = Integer.parseInt(tokens[0]);
if (fieldIndex > fieldCount) fieldCount = fieldIndex;
}
else tokens = name.split(":");
String channel = tokens[tokens.length - 1];
if (!uniqueChannels.contains(channel)) uniqueChannels.add(channel);
}
if (fieldCount == 0) fieldCount = 1;
core[0].sizeC = (int) Math.max(uniqueChannels.size(), 1);
if (getSizeZ() == 0) core[0].sizeZ = 1;
core[0].sizeT =
imageNames.size() / (fieldCount * getSizeC() * getSizeZ());
}
if (getSizeC() == 0) {
core[0].sizeC = (int) Math.max(channelNames.size(), 1);
}
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeT() == 0) core[0].sizeT = 1;
if (plateCount == 0) plateCount = 1;
if (wellCount == 0) wellCount = 1;
if (fieldCount == 0) fieldCount = 1;
// adjust dimensions if the number of IFDs doesn't match the number
// of reported images
IFDList ifdList = ifds[wellRow][wellCol];
IFD ifd = ifdList.get(0);
core[0].imageCount = getSizeZ() * getSizeC() * getSizeT();
if (getImageCount() * fieldCount != ifdList.size()) {
core[0].imageCount = ifdList.size() / fieldCount;
core[0].sizeZ = 1;
core[0].sizeC = 1;
core[0].sizeT = ifdList.size() / fieldCount;
}
core[0].sizeX = (int) ifd.getImageWidth();
core[0].sizeY = (int) ifd.getImageLength();
core[0].dimensionOrder = "XYCZT";
core[0].rgb = false;
core[0].interleaved = false;
core[0].indexed = false;
core[0].littleEndian = ifd.isLittleEndian();
core[0].pixelType = ifd.getPixelType();
int seriesCount = plateCount * wellCount * fieldCount;
if (seriesCount > 1) {
CoreMetadata oldCore = core[0];
core = new CoreMetadata[seriesCount];
Arrays.fill(core, oldCore);
}
}
/**
* Search for files that correspond to the given file.
* If the given file is a .mea file, then the corresponding files will be
* .res and .flex files.
* If the given file is a .flex file, then the corresponding files will be
* .res and .mea files.
*/
private String[] findFiles(Location baseFile) throws IOException {
// we're assuming that the directory structure looks something like this:
// top level directory
// top level flex dir top level measurement dir
// plate #0 ... plate #n plate #0 ... plate #n
// .flex ... .flex .mea .res
// or like this:
// top level directory
// Flex plate #0 ... #n #0 ... Measurement plate #n
// or that the .mea and .res are in the same directory as the .flex files
Vector<String> fileList = new Vector<String>();
String[] suffixes = null;
if (checkSuffix(baseFile.getName(), FLEX_SUFFIX)) {
suffixes = new String[] {MEA_SUFFIX, RES_SUFFIX};
}
else if (checkSuffix(baseFile.getName(), MEA_SUFFIX)) {
suffixes = new String[] {FLEX_SUFFIX, RES_SUFFIX};
}
Location plateDir = baseFile.getParentFile();
String[] files = plateDir.list(true);
// check if the measurement files are in the same directory
for (String file : files) {
String lfile = file.toLowerCase();
String path = new Location(plateDir, file).getAbsolutePath();
if (checkSuffix(file, suffixes)) {
fileList.add(path);
}
}
// file list is valid (i.e. can be returned) if there is at least
// one file with each of the desired suffixes
boolean validList = true;
for (String suffix : suffixes) {
boolean foundSuffix = false;
for (String file : fileList) {
if (checkSuffix(file, suffix)) {
foundSuffix = true;
break;
}
}
if (!foundSuffix) {
validList = false;
break;
}
}
if (validList) {
for (String file : fileList) {
if (checkSuffix(file, MEASUREMENT_SUFFIXES)) {
measurementFiles.add(file);
}
}
return fileList.toArray(new String[fileList.size()]);
}
Location flexDir = null;
try {
flexDir = plateDir.getParentFile();
}
catch (NullPointerException e) { }
if (flexDir == null) return null;
// check if the measurement directory and the Flex directory
// have the same parent
Location measurementDir = null;
String[] flexDirList = flexDir.list(true);
if (flexDirList.length > 1) {
String plateName = plateDir.getName();
for (String file : flexDirList) {
if (!file.equals(plateName) &&
(plateName.startsWith(file) || file.startsWith(plateName)))
{
measurementDir = new Location(flexDir, file);
break;
}
}
}
// check if Flex directories and measurement directories have
// a different parent
if (measurementDir == null) {
Location topDir = flexDir.getParentFile();
String[] topDirList = topDir.list(true);
for (String file : topDirList) {
if (!flexDir.getAbsolutePath().endsWith(file)) {
measurementDir = new Location(topDir, file);
break;
}
}
if (measurementDir == null) return null;
}
else plateDir = measurementDir;
if (!plateDir.getAbsolutePath().equals(measurementDir.getAbsolutePath())) {
String[] measurementPlates = measurementDir.list(true);
String plate = plateDir.getName();
plateDir = null;
if (measurementPlates != null) {
for (String file : measurementPlates) {
if (file.indexOf(plate) != -1 || plate.indexOf(file) != -1) {
plateDir = new Location(measurementDir, file);
break;
}
}
}
}
if (plateDir == null) return null;
files = plateDir.list(true);
for (String file : files) {
fileList.add(new Location(plateDir, file).getAbsolutePath());
}
for (String file : fileList) {
if (checkSuffix(file, MEASUREMENT_SUFFIXES)) {
measurementFiles.add(file);
}
}
return fileList.toArray(new String[fileList.size()]);
}
private void groupFiles(String[] fileList, MetadataStore store)
throws FormatException, IOException
{
HashMap<String, String> v = new HashMap<String, String>();
for (String file : fileList) {
int[] well = getWell(file);
if (well[0] > nRows) nRows = well[0];
if (well[1] > nCols) nCols = well[1];
if (fileList.length == 1) {
well[0] = 0;
well[1] = 0;
}
v.put(well[0] + "," + well[1], file);
}
nRows++;
nCols++;
if (fileList.length == 1) {
nRows = 1;
nCols = 1;
}
flexFiles = new String[nRows][nCols];
ifds = new IFDList[nRows][nCols];
factors = new double[nRows][nCols][];
wellCount = v.size();
wellNumber = new int[wellCount][2];
RandomAccessInputStream s = null;
boolean firstFile = true;
int currentWell = 0;
for (int row=0; row<nRows; row++) {
for (int col=0; col<nCols; col++) {
flexFiles[row][col] = v.get(row + "," + col);
if (flexFiles[row][col] == null) continue;
wellNumber[currentWell][0] = row;
wellNumber[currentWell][1] = col;
s = new RandomAccessInputStream(flexFiles[row][col]);
TiffParser tp = new TiffParser(s);
ifds[row][col] = tp.getIFDs();
s.close();
parseFlexFile(currentWell, row, col, firstFile, store);
if (firstFile) firstFile = false;
currentWell++;
}
}
}
// -- Helper classes --
/** SAX handler for parsing XML. */
public class FlexHandler extends DefaultHandler {
private Vector<String> names, factors;
private MetadataStore store;
private int nextLaser = -1;
private int nextCamera = 0;
private int nextObjective = -1;
private int nextImage = 0;
private int nextPlate = 0;
private String parentQName;
private String lightSourceID;
private String sliderName;
private int nextFilter;
private int nextDichroic;
private int nextFilterSet;
private int nextSliderRef;
private boolean populateCore = true;
private int well = 0;
private HashMap<String, String> filterMap;
private HashMap<String, String> dichroicMap;
private StringBuffer charData = new StringBuffer();
public FlexHandler(Vector<String> names, Vector<String> factors,
MetadataStore store, boolean populateCore, int well)
{
this.names = names;
this.factors = factors;
this.store = store;
this.populateCore = populateCore;
this.well = well;
filterMap = new HashMap<String, String>();
dichroicMap = new HashMap<String, String>();
}
public void characters(char[] ch, int start, int length) {
charData.append(new String(ch, start, length));
}
public void endElement(String uri, String localName, String qName) {
String value = charData.toString();
charData = new StringBuffer();
if (qName.equals("Image")) {
binnings.add(binX + "x" + binY);
}
else if (qName.equals("PlateName")) {
if (plateName == null) plateName = value;
}
else if (qName.equals("Barcode")) {
if (plateBarcode == null) plateBarcode = value;
store.setPlateExternalIdentifier(value, nextPlate - 1);
}
else if (qName.equals("Wavelength")) {
String lsid = MetadataTools.createLSID("LightSource", 0, nextLaser);
store.setLightSourceID(lsid, 0, nextLaser);
store.setLaserWavelength(new Integer(value), 0, nextLaser);
store.setLaserType("Unknown", 0, nextLaser);
store.setLaserLaserMedium("Unknown", 0, nextLaser);
}
else if (qName.equals("Magnification")) {
store.setObjectiveCalibratedMagnification(new Float(value), 0,
nextObjective);
}
else if (qName.equals("NumAperture")) {
store.setObjectiveLensNA(new Float(value), 0, nextObjective);
}
else if (qName.equals("Immersion")) {
if (value.equals("1.33")) value = "Water";
else if (value.equals("1.00")) value = "Air";
else warn("Unknown immersion medium: " + value);
store.setObjectiveImmersion(value, 0, nextObjective);
}
else if (qName.equals("OffsetX") || qName.equals("OffsetY")) {
Float offset = new Float(Float.parseFloat(value) * 1000000);
if (qName.equals("OffsetX")) xPositions.add(offset);
else yPositions.add(offset);
}
else if (qName.equals("XSize") && "Plate".equals(parentQName)) {
wellRows = Integer.parseInt(value);
}
else if (qName.equals("YSize") && "Plate".equals(parentQName)) {
wellColumns = Integer.parseInt(value);
}
else if ("Image".equals(parentQName)) {
if (fieldCount == 0) fieldCount = 1;
int nImages = firstWellIfds().size() / fieldCount;
if (nImages == 0) nImages = 1; // probably a manually altered dataset
int currentSeries = (nextImage - 1) / nImages;
currentSeries += well * fieldCount;
int currentImage = (nextImage - 1) % nImages;
int seriesCount = 1;
if (plateCount > 0) seriesCount *= plateCount;
if (wellCount > 0) seriesCount *= wellCount;
if (fieldCount > 0) seriesCount *= fieldCount;
if (currentSeries >= seriesCount) return;
if (qName.equals("DateTime")) {
store.setImageCreationDate(value, currentSeries);
}
else if (qName.equals("CameraBinningX")) {
binX = Integer.parseInt(value);
}
else if (qName.equals("CameraBinningY")) {
binY = Integer.parseInt(value);
}
else if (qName.equals("ObjectiveRef")) {
String objectiveID = MetadataTools.createLSID(
"Objective", 0, objectiveIDs.indexOf(value));
objectiveRefs.add(objectiveID);
}
else if (qName.equals("CameraRef")) {
String detectorID =
MetadataTools.createLSID("Detector", 0, cameraIDs.indexOf(value));
cameraRefs.add(detectorID);
}
else if (qName.equals("ImageResolutionX")) {
float v = Float.parseFloat(value) * 1000000;
xSizes.add(new Float(v));
}
else if (qName.equals("ImageResolutionY")) {
float v = Float.parseFloat(value) * 1000000;
ySizes.add(new Float(v));
}
else if (qName.equals("PositionX")) {
Float v = new Float(Float.parseFloat(value) * 1000000);
store.setStagePositionPositionX(v, currentSeries, 0, currentImage);
}
else if (qName.equals("PositionY")) {
Float v = new Float(Float.parseFloat(value) * 1000000);
store.setStagePositionPositionY(v, currentSeries, 0, currentImage);
}
else if (qName.equals("PositionZ")) {
Float v = new Float(Float.parseFloat(value) * 1000000);
store.setStagePositionPositionZ(v, currentSeries, 0, currentImage);
}
else if (qName.equals("TimepointOffsetUsed")) {
store.setPlaneTimingDeltaT(new Float(value), currentSeries, 0,
currentImage);
}
else if (qName.equals("CameraExposureTime")) {
store.setPlaneTimingExposureTime(new Float(value), currentSeries, 0,
currentImage);
}
else if (qName.equals("LightSourceCombinationRef")) {
lightSourceCombinationRefs.add(value);
}
else if (qName.equals("FilterCombinationRef")) {
filterSets.add("FilterSet:" + value);
}
}
else if (qName.equals("FilterCombination")) {
nextFilterSet++;
nextSliderRef = 0;
}
}
public void startElement(String uri,
String localName, String qName, Attributes attributes)
{
if (qName.equals("Array")) {
int len = attributes.getLength();
for (int i=0; i<len; i++) {
String name = attributes.getQName(i);
if (name.equals("Name")) {
names.add(attributes.getValue(i));
}
else if (name.equals("Factor")) factors.add(attributes.getValue(i));
}
}
else if (qName.equals("LightSource")) {
parentQName = qName;
String type = attributes.getValue("LightSourceType");
lightSourceIDs.add(attributes.getValue("ID"));
nextLaser++;
}
else if (qName.equals("LightSourceCombination")) {
lightSourceID = attributes.getValue("ID");
lightSourceCombinationIDs.put(lightSourceID, new Vector<String>());
}
else if (qName.equals("LightSourceRef")) {
Vector<String> v = lightSourceCombinationIDs.get(lightSourceID);
if (v != null) {
int id = lightSourceIDs.indexOf(attributes.getValue("ID"));
String lightSourceID = MetadataTools.createLSID("LightSource", 0, id);
v.add(lightSourceID);
lightSourceCombinationIDs.put(lightSourceID, v);
}
}
else if (qName.equals("Camera")) {
parentQName = qName;
String detectorID = MetadataTools.createLSID("Detector", 0, nextCamera);
store.setDetectorID(detectorID, 0, nextCamera);
store.setDetectorType(attributes.getValue("CameraType"), 0, nextCamera);
cameraIDs.add(attributes.getValue("ID"));
nextCamera++;
}
else if (qName.equals("Objective")) {
parentQName = qName;
nextObjective++;
String objectiveID =
MetadataTools.createLSID("Objective", 0, nextObjective);
store.setObjectiveID(objectiveID, 0, nextObjective);
store.setObjectiveCorrection("Unknown", 0, nextObjective);
objectiveIDs.add(attributes.getValue("ID"));
}
else if (qName.equals("Field")) {
parentQName = qName;
int fieldNo = Integer.parseInt(attributes.getValue("No"));
if (fieldNo > fieldCount && fieldCount < firstWellIfds().size()) {
fieldCount++;
}
}
else if (qName.equals("Plane")) {
parentQName = qName;
int planeNo = Integer.parseInt(attributes.getValue("No"));
if (planeNo > getSizeZ() && populateCore) core[0].sizeZ++;
}
else if (qName.equals("WellShape")) {
parentQName = qName;
}
else if (qName.equals("Image")) {
parentQName = qName;
nextImage++;
//Implemented for FLEX v1.7 and below
String x = attributes.getValue("CameraBinningX");
String y = attributes.getValue("CameraBinningY");
if (x != null) binX = Integer.parseInt(x);
if (y != null) binY = Integer.parseInt(y);
}
else if (qName.equals("Plate")) {
parentQName = qName;
if (qName.equals("Plate")) {
nextPlate++;
plateCount++;
}
}
else if (qName.equals("WellCoordinate")) {
if (wellNumber.length == 1) {
wellNumber[0][0] = Integer.parseInt(attributes.getValue("Row")) - 1;
wellNumber[0][1] = Integer.parseInt(attributes.getValue("Col")) - 1;
}
}
else if (qName.equals("Slider")) {
sliderName = attributes.getValue("Name");
}
else if (qName.equals("Filter")) {
String id = attributes.getValue("ID");
if (sliderName.endsWith("Dichro")) {
String dichroicID =
MetadataTools.createLSID("Dichroic", 0, nextDichroic);
dichroicMap.put(id, dichroicID);
store.setDichroicID(dichroicID, 0, nextDichroic);
store.setDichroicModel(id, 0, nextDichroic);
nextDichroic++;
}
else {
String filterID = MetadataTools.createLSID("Filter", 0, nextFilter);
filterMap.put(id, filterID);
store.setFilterID(filterID, 0, nextFilter);
store.setFilterModel(id, 0, nextFilter);
store.setFilterFilterWheel(sliderName, 0, nextFilter);
nextFilter++;
}
}
else if (qName.equals("FilterCombination")) {
String filterSetID =
MetadataTools.createLSID("FilterSet", 0, nextFilterSet);
store.setFilterSetID(filterSetID, 0, nextFilterSet);
filterSetMap.put("FilterSet:" + attributes.getValue("ID"), filterSetID);
}
else if (qName.equals("SliderRef")) {
String filterName = attributes.getValue("Filter");
String filterID = filterMap.get(filterName);
String dichroicID = dichroicMap.get(filterName);
String slider = attributes.getValue("ID");
if (nextSliderRef == 0 && slider.startsWith("Camera")) {
store.setFilterSetEmFilter(filterID, 0, nextFilterSet);
}
else if (nextSliderRef == 1 && slider.startsWith("Camera")) {
store.setFilterSetExFilter(filterID, 0, nextFilterSet);
}
else if (slider.equals("Primary_Dichro")) {
store.setFilterSetDichroic(dichroicID, 0, nextFilterSet);
}
String lname = filterName.toLowerCase();
if (!lname.startsWith("empty") && !lname.startsWith("blocked")) {
nextSliderRef++;
}
}
}
}
/** SAX handler for parsing XML from .mea files. */
public class MeaHandler extends DefaultHandler {
private Vector<String> flex = new Vector<String>();
private String[] hostnames = null;
// -- MeaHandler API methods --
public Vector<String> getFlexFiles() { return flex; }
// -- DefaultHandler API methods --
public void startElement(String uri,
String localName, String qName, Attributes attributes)
{
if (qName.equals("Host")) {
String hostname = attributes.getValue("name");
hostnames = serverMap.get(hostname);
if (hostnames != null) {
for (int i=0; i<hostnames.length; i++) {
hostnames[i] = hostnames[i].replace('/', File.separatorChar);
hostnames[i] = hostnames[i].replace('\\', File.separatorChar);
}
}
}
else if (qName.equals("Picture")) {
String path = attributes.getValue("path");
if (!path.endsWith(".flex")) path += ".flex";
path = path.replace('/', File.separatorChar);
path = path.replace('\\', File.separatorChar);
debug("Found .flex in .mea: " + path);
if (hostnames != null) {
int numberOfFlexFiles = flex.size();
for (String hostname : hostnames) {
String filename = hostname + File.separator + path;
if (new Location(filename).exists()) {
flex.add(filename);
}
}
if (flex.size() == numberOfFlexFiles) {
warn(path + " was in .mea, but does not actually exist.");
}
}
}
}
}
// -- FlexReader API methods --
/**
* Map the server named 'alias' to the path 'realName'.
* @throw FormatException if 'realName' does not exist.
*/
public static void mapServer(String alias, String realName)
throws FormatException
{
if (alias != null) {
if (realName == null) {
serverMap.remove(alias);
}
else {
// verify that 'realName' exists
Location server = new Location(realName);
if (!server.exists()) {
throw new FormatException("Server " + realName + " was not found.");
}
if (realName.endsWith(File.separator)) {
realName.substring(0, realName.length() - 1);
}
String baseName = realName;
if (baseName.endsWith(SCREENING)) {
baseName = baseName.substring(0, baseName.lastIndexOf(SCREENING));
}
else if (baseName.endsWith(ARCHIVE)) {
baseName = baseName.substring(0, baseName.lastIndexOf(ARCHIVE));
}
Vector<String> names = new Vector<String>();
names.add(baseName);
Location screening =
new Location(baseName + File.separator + SCREENING);
Location archive = new Location(baseName + File.separator + ARCHIVE);
if (screening.exists()) names.add(screening.getAbsolutePath());
if (archive.exists()) names.add(archive.getAbsolutePath());
mapServer(alias, names.toArray(new String[names.size()]));
}
}
}
/**
* Map the server named 'alias' to the path 'realName'.
* @throw FormatException if 'realName' does not exist.
*/
public static void mapServer(String alias, String[] realNames)
throws FormatException
{
if (alias != null) {
if (realNames == null) {
serverMap.remove(alias);
}
else {
for (String server : realNames) {
if (!new Location(server).exists()) {
throw new FormatException("Server " + server + " does not exist.");
}
}
serverMap.put(alias, realNames);
}
}
}
/**
* Read a configuration file with lines of the form:
*
* <server alias>=<real server name>
*
* and call mapServer(String, String) accordingly.
*
* @throw FormatException if configFile does not exist.
* @see mapServer(String, String)
*/
public static void mapServersFromConfigurationFile(String configFile)
throws FormatException, IOException
{
Location file = new Location(configFile);
if (!file.exists()) {
throw new FormatException(
"Configuration file " + configFile + " does not exist.");
}
RandomAccessInputStream s = new RandomAccessInputStream(configFile);
String[] lines = s.readString((int) s.length()).split("[\r\n]");
for (String line : lines) {
int eq = line.indexOf("=");
if (eq == -1 || line.startsWith("#")) continue;
String alias = line.substring(0, eq).trim();
String[] servers = line.substring(eq + 1).trim().split(";");
mapServer(alias, servers);
}
s.close();
}
}
|
package com.elmakers.mine.bukkit.magic;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import com.elmakers.mine.bukkit.api.block.UndoList;
import com.elmakers.mine.bukkit.api.magic.*;
import com.elmakers.mine.bukkit.api.spell.SpellCategory;
import com.elmakers.mine.bukkit.block.MaterialAndData;
import com.elmakers.mine.bukkit.citizens.CitizensController;
import com.elmakers.mine.bukkit.magic.command.*;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
import com.elmakers.mine.bukkit.utility.InventoryUtils;
import com.elmakers.mine.bukkit.utility.NMSUtils;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.configuration.MemorySection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
import com.elmakers.mine.bukkit.api.wand.LostWand;
import com.elmakers.mine.bukkit.wand.Wand;
/**
* This is the main Plugin class for Magic.
*
* An integrating Plugin should generally cast this to MagicAPI and
* use the API interface when interacting with Magic.
*
*/
public class MagicPlugin extends JavaPlugin implements MagicAPI
{
/*
* Singleton Plugin instance
*/
private static MagicPlugin instance;
/*
* Private data
*/
private MagicController controller = null;
/*
* Plugin interface
*/
public MagicPlugin()
{
instance = this;
}
public void onEnable()
{
if (NMSUtils.isLegacy()) {
getLogger().info("Enabling 1.7 support - Magic may stop supporting 1.7 in version 5!");
}
if (controller == null) {
controller = new MagicController(this);
}
if (NMSUtils.getFailed()) {
getLogger().warning("Something went wrong with some Deep Magic, plugin will not load.");
getLogger().warning("Please make sure you are running a compatible version of CraftBukkit or Spigot!");
} else {
initialize();
}
}
protected void initialize()
{
controller.initialize();
TabExecutor magicCommand = new MagicCommandExecutor(this);
getCommand("magic").setExecutor(magicCommand);
getCommand("magic").setTabCompleter(magicCommand);
TabExecutor magicGiveCommand = new MagicGiveCommandExecutor(this);
getCommand("mgive").setExecutor(magicGiveCommand);
getCommand("mgive").setTabCompleter(magicGiveCommand);
TabExecutor magicSkillsCommand = new MagicSkillsCommandExecutor(this);
getCommand("mskills").setExecutor(magicSkillsCommand);
getCommand("mskills").setTabCompleter(magicSkillsCommand);
TabExecutor castCommand = new CastCommandExecutor(this);
getCommand("cast").setExecutor(castCommand);
getCommand("cast").setTabCompleter(castCommand);
getCommand("castp").setExecutor(castCommand);
getCommand("castp").setTabCompleter(castCommand);
TabExecutor wandCommand = new WandCommandExecutor(this);
getCommand("wand").setExecutor(wandCommand);
getCommand("wand").setTabCompleter(wandCommand);
getCommand("wandp").setExecutor(wandCommand);
getCommand("wandp").setTabCompleter(wandCommand);
TabExecutor spellsCommand = new SpellsCommandExecutor(this);
getCommand("spells").setExecutor(spellsCommand);
CitizensController citizens = controller.getCitizens();
if (citizens != null)
{
TabExecutor magicTraitCommand = new MagicTraitCommandExecutor(this, citizens);
getCommand("mtrait").setExecutor(magicTraitCommand);
getCommand("mtrait").setTabCompleter(magicTraitCommand);
}
}
/*
* Help commands
*/
public void onDisable()
{
if (controller != null) {
controller.clear();
controller.save();
}
}
/*
* API Implementation
*/
@Override
public Plugin getPlugin() {
return this;
}
@Override
public boolean hasPermission(CommandSender sender, String pNode) {
return controller.hasPermission(sender, pNode);
}
@Override
public boolean hasPermission(CommandSender sender, String pNode, boolean defaultPermission) {
return controller.hasPermission(sender, pNode, defaultPermission);
}
@Override
public void save() {
controller.save();
}
@Override
public void reload() {
controller.loadConfiguration();
}
@Override
public void clearCache() {
controller.clearCache();
}
@Override
public boolean commit() {
return controller.commitAll();
}
@Override
public Collection<com.elmakers.mine.bukkit.api.magic.Mage> getMages() {
return controller.getMages();
}
@Override
public Collection<com.elmakers.mine.bukkit.api.magic.Mage> getMagesWithPendingBatches() {
Collection<com.elmakers.mine.bukkit.api.magic.Mage> mages = new ArrayList<com.elmakers.mine.bukkit.api.magic.Mage>();
Collection<com.elmakers.mine.bukkit.api.magic.Mage> internal = controller.getPending();
mages.addAll(internal);
return mages;
}
@Override
public Collection<UndoList> getPendingUndo() {
Collection<UndoList> undo = new ArrayList<UndoList>();
undo.addAll(controller.getPendingUndo());
return undo;
}
@Override
public Collection<LostWand> getLostWands() {
Collection<LostWand> lostWands = new ArrayList<LostWand>();
lostWands.addAll(controller.getLostWands());
return lostWands;
}
@Override
public Collection<Automaton> getAutomata() {
Collection<Automaton> automata = new ArrayList<Automaton>();
automata.addAll(controller.getAutomata());
return automata;
}
@Override
public void removeLostWand(String id) {
controller.removeLostWand(id);
}
@Override
public com.elmakers.mine.bukkit.api.wand.Wand getWand(ItemStack itemStack) {
return new Wand(controller, itemStack);
}
@Override
public boolean isWand(ItemStack item) {
return Wand.isWand(item);
}
@Override
public String getSpell(ItemStack item) {
return Wand.getSpell(item);
}
@Override
public boolean isBrush(ItemStack item) {
return Wand.isBrush(item);
}
@Override
public boolean isSpell(ItemStack item) {
return Wand.isSpell(item);
}
@Override
public String getBrush(ItemStack item) {
return Wand.getBrush(item);
}
@Override
public boolean isUpgrade(ItemStack item) {
return Wand.isUpgrade(item);
}
@Override
public void giveItemToPlayer(Player player, ItemStack itemStack) {
controller.giveItemToPlayer(player, itemStack);
}
@Override
public void giveExperienceToPlayer(Player player, int xp) {
if (controller.isMage(player)) {
com.elmakers.mine.bukkit.api.magic.Mage mage = controller.getMage(player);
mage.giveExperience(xp);
} else {
player.giveExp(xp);
}
}
@Override
public com.elmakers.mine.bukkit.api.magic.Mage getMage(CommandSender sender) {
return controller.getMage(sender);
}
@Override
public com.elmakers.mine.bukkit.api.magic.Mage getMage(Entity entity, CommandSender sender) {
return controller.getMage(entity);
}
@Override
public String describeItem(ItemStack item) {
return controller.describeItem(item);
}
@Override
public ItemStack createItem(String magicKey) {
return createItem(magicKey, null);
}
@Override
public ItemStack createItem(String magicKey, com.elmakers.mine.bukkit.api.magic.Mage mage) {
ItemStack itemStack = null;
if (controller == null) {
getLogger().log(Level.WARNING, "Calling API before plugin is initialized");
return null;
}
// Handle : or | as delimiter
String magicItemKey = magicKey.replace("|", ":");
try {
if (magicItemKey.contains("skull:") || magicItemKey.contains("skull_item:")) {
magicItemKey = magicItemKey.replace("skull:", "skull_item:");
MaterialAndData skullData = new MaterialAndData(magicItemKey);
itemStack = skullData.getItemStack(1);
} else if (magicItemKey.contains("book:")) {
String bookCategory = magicItemKey.substring(5);
SpellCategory category = null;
if (!bookCategory.isEmpty() && !bookCategory.equalsIgnoreCase("all")) {
category = controller.getCategory(bookCategory);
if (category == null) {
return null;
}
}
itemStack = getSpellBook(category, 1);
} else if (magicItemKey.contains("spell:")) {
String spellKey = magicKey.substring(6);
itemStack = createSpellItem(spellKey);
} else if (magicItemKey.contains("skill:")) {
String spellKey = magicKey.substring(6);
itemStack = Wand.createSpellItem(spellKey, controller, mage, null, false);
InventoryUtils.setMeta(itemStack, "skill", "true");
} else if (magicItemKey.contains("wand:")) {
String wandKey = magicItemKey.substring(5);
com.elmakers.mine.bukkit.api.wand.Wand wand = createWand(wandKey);
if (wand != null) {
itemStack = wand.getItem();
}
} else if (magicItemKey.contains("upgrade:")) {
String wandKey = magicItemKey.substring(8);
com.elmakers.mine.bukkit.api.wand.Wand wand = createWand(wandKey);
if (wand != null) {
wand.makeUpgrade();
itemStack = wand.getItem();
}
} else if (magicItemKey.contains("brush:")) {
String brushKey = magicItemKey.substring(6);
itemStack = createBrushItem(brushKey);
} else if (magicItemKey.contains("item:")) {
String itemKey = magicItemKey.substring(5);
itemStack = createGenericItem(itemKey);
} else {
MaterialAndData item = new MaterialAndData(magicItemKey);
if (item.isValid()) {
return item.getItemStack(1);
}
com.elmakers.mine.bukkit.api.wand.Wand wand = createWand(magicKey);
if (wand != null) {
return wand.getItem();
}
itemStack = createSpellItem(magicKey);
if (itemStack != null) {
return itemStack;
}
itemStack = createBrushItem(magicItemKey);
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error creating item: " + magicItemKey, ex);
}
return itemStack;
}
@Override
public ItemStack createGenericItem(String itemKey) {
return controller.createItem(itemKey);
}
@Override
public com.elmakers.mine.bukkit.api.wand.Wand createWand(String wandKey) {
return Wand.createWand(controller, wandKey);
}
@Override
public com.elmakers.mine.bukkit.api.wand.Wand createUpgrade(String wandKey) {
Wand wand = Wand.createWand(controller, wandKey);
if (!wand.isUpgrade()) {
wand.makeUpgrade();
}
return wand;
}
@Override
public ItemStack createSpellItem(String spellKey) {
return Wand.createSpellItem(spellKey, controller, null, true);
}
@Override
public ItemStack createBrushItem(String brushKey) {
return Wand.createBrushItem(brushKey, controller, null, true);
}
@Override
public boolean cast(String spellName, String[] parameters) {
return cast(spellName, parameters, null, null);
}
@Override
public Collection<SpellTemplate> getSpellTemplates() {
return controller.getSpellTemplates();
}
@Override
public Collection<String> getWandKeys() {
return Wand.getWandKeys();
}
@Override
public boolean cast(String spellName, String[] parameters, CommandSender sender, Entity entity) {
ConfigurationSection config = null;
if (parameters != null && parameters.length > 0) {
config = new MemoryConfiguration();
ConfigurationUtils.addParameters(parameters, config);
}
return controller.cast(null, spellName, config, sender, entity);
}
@Override
public boolean cast(String spellName, ConfigurationSection parameters, CommandSender sender, Entity entity) {
return controller.cast(null, spellName, parameters, sender, entity);
}
@Override
public Collection<String> getPlayerNames() {
return controller.getPlayerNames();
}
@Override
public com.elmakers.mine.bukkit.api.wand.Wand createWand(Material iconMaterial, short iconData) {
return new Wand(controller, iconMaterial, iconData);
}
@Override
public com.elmakers.mine.bukkit.api.wand.Wand createWand(ItemStack item) {
return Wand.createWand(controller, item);
}
@Override
public SpellTemplate getSpellTemplate(String key) {
return controller.getSpellTemplate(key);
}
@Override
public Collection<String> getSchematicNames() {
return controller.getSchematicNames();
}
@Override
public Collection<String> getBrushes() {
return controller.getBrushKeys();
}
@Override
public MageController getController() {
return controller;
}
@Override
public ItemStack getSpellBook(SpellCategory category, int count) {
return controller.getSpellBook(category, count);
}
@Override
public Messages getMessages() {
return controller.getMessages();
}
public static MagicAPI getAPI() {
return instance;
}
}
|
package com.foodrater.verticles;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.mongo.MongoClient;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.core.logging.Logger;
import io.vertx.ext.web.handler.CorsHandler;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
public class RestServerVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(RestServerVerticle.class.getSimpleName());
private Map<String, JsonObject> products = new HashMap<>();
public static final String ADDRESS = "mongodb-persistor";
public static final String DEFAULT_MONGODB_CONFIG
= "{"
+ " \"address\": \"" + ADDRESS + "\","
+ " \"host\": \"localhost\","
+ " \"port\": 27017,"
+ " \"db_name\": \"bs\","
+ " \"useObjectId\" : true"
+ "}";
MongoClient mongo;
@Override
public void start() {
mongo = MongoClient.createShared(vertx, new JsonObject(DEFAULT_MONGODB_CONFIG));
LOGGER.info("MongoClient is started with this config: " + new JsonObject(DEFAULT_MONGODB_CONFIG).encodePrettily());
//setUpInitialData();
Router router = Router.router(vertx);
// Needs to be added if you want to access your frontend on the same server
CorsHandler corsHandler = CorsHandler.create("*");
corsHandler.allowedMethod(HttpMethod.GET);
corsHandler.allowedMethod(HttpMethod.POST);
corsHandler.allowedMethod(HttpMethod.PUT);
corsHandler.allowedMethod(HttpMethod.DELETE);
corsHandler.allowedHeader("Authorization");
corsHandler.allowedHeader("Content-Type");
corsHandler.allowedHeader("Access-Control-Allow-Origin");
corsHandler.allowedHeader("Access-Control-Allow-Headers");
router.route().handler(corsHandler);
router.route().handler(BodyHandler.create());
router.get("/products/:productID").handler(this::handleGetProduct);
router.get("/products/search/:word").handler(this::searchProduct);
router.put("/products/:productID").handler(this::handleAddProduct);
router.get("/products").handler(this::handleListProducts);
router.get("/initialize").handler(this::setUpInitialData);
router.get("/myproducts/:UUID").handler(this::getAllProductsForUser);
router.get("/users/:userID").handler(this::getUserInformation);
router.get("/user/login/:username/:pw").handler(this::getUserLogin);
router.put("/user/register").handler(this::handleAddUser);
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
private void getUserLogin(RoutingContext routingContext) {
String userName = routingContext.request().getParam("username");
String pw = routingContext.request().getParam("pw");
HttpServerResponse response = routingContext.response();
if (userName.equals(null) || pw.equals(null) || userName.length() < 1 || pw.length() < 1) {
sendError(400, response);
} else {
try {
if (findUserInMongoDB(userName, pw) != null) {
response.putHeader("content-type", "application/json").end((findUserInMongoDB(userName, pw)).encodePrettily());
} else {
sendError(400, response);
}
} catch (InterruptedException e) {
LOGGER.error("Couldn't find User.");
sendError(400, response);
}
}
}
private JsonObject findUserInMongoDB(String userName, String pw) throws InterruptedException {
JsonObject resultedUser = new JsonObject();
JsonObject query = new JsonObject();
query.put("userName", userName);
query.put("pw", pw);
CountDownLatch latch = new CountDownLatch(1);
mongo.find("users", query, res -> {
if (res.succeeded()) {
for (JsonObject json : res.result()) {
LOGGER.info("Found user:" + json.encodePrettily());
resultedUser.put(json.getString("uuid"), json);
LOGGER.info("Result Json:" + resultedUser.encodePrettily());
}
}
latch.countDown();
});
latch.await();
LOGGER.info("Final result Json:" + resultedUser.encodePrettily());
return resultedUser;
}
private void handleAddUser(RoutingContext routingContext) {
// add check, if user already exists
HttpServerResponse response = routingContext.response();
JsonObject user = null;
try {
user = routingContext.getBodyAsJson();
} catch (Exception e) {
sendError(400, response);
}
if (user == null) {
sendError(400, response);
} else {
UUID uuid = new UUID(10000L, 100L);
JsonObject newUser = new JsonObject();
newUser.put("UUID", uuid.toString());
newUser.put("user", user);
insertUserInMongo(newUser);
response.putHeader("content-type", "application/json").end(newUser.encodePrettily());
}
}
private void insertUserInMongo(JsonObject user) {
mongo.insert("users", user, stringAsyncResult -> {
if (stringAsyncResult.succeeded()) {
LOGGER.info("Inserted user into mongoDB: " + user.encodePrettily());
} else {
LOGGER.error("Could not insert user into mongoDB: " + user.encodePrettily());
}
});
}
private void getUserInformation(RoutingContext routingContext) {
String uuid = routingContext.request().getParam("uuid");
HttpServerResponse response = routingContext.response();
JsonObject query = new JsonObject();
query.put("UUID", uuid);
mongo.find("users", query, res -> {
if (res.succeeded()) {
for (JsonObject json : res.result()) {
LOGGER.info("Found user:" + json.encodePrettily());
response.putHeader("content-type", "application/json").end(json.encodePrettily());
}
} else {
sendError(400, response);
}
});
}
/**
* response all products for user as json -> {prodId:{productjson1}, {productjson2}, ... }
*
* @param routingContext incoming RotingContext with param UUID
*/
private void getAllProductsForUser(RoutingContext routingContext) {
String uuid = routingContext.request().getParam("UUID");
JsonObject query = new JsonObject().put("UUID", uuid);
HttpServerResponse response = routingContext.response();
JsonObject allProducts = new JsonObject();
mongo.find("users", query, res -> {
if (res.succeeded()) {
for (JsonObject userJson : res.result()) {
JsonObject query2 = new JsonObject().put("productID", userJson.getString("productID"));
mongo.find("products", query2, res2 -> {
if (res2.succeeded()) {
for (JsonObject product : res2.result()) {
allProducts.put(userJson.getString("productID"), product);
}
}
});
}
response.putHeader("content-type", "application/json").end(allProducts.encodePrettily());
} else {
sendError(400, response);
}
});
}
/**
* response all products with name inside as json
* { {product1}, {product2}, {product3}.. }
*
* @param routingContext incoming RotingContext with param search-word
*/
private void searchProduct(RoutingContext routingContext) {
String word = routingContext.request().getParam("word");
JsonObject query = new JsonObject().put("name", "/" + word + "/");
//LOGGER.info("Search in mongodb for this query: " + query.encodePrettily());
HttpServerResponse response = routingContext.response();
JsonObject fittingProducts = new JsonObject();
CountDownLatch latch = new CountDownLatch(1);
mongo.find("products", query, res -> {
if (res.succeeded()) {
for (JsonObject foundedProduct : res.result()) {
LOGGER.info("Found Product with search: " + foundedProduct.encodePrettily());
fittingProducts.put(foundedProduct.getJsonObject("product").getString("id"), foundedProduct);
latch.countDown();
}
try {
latch.await();
} catch (InterruptedException e) {
LOGGER.error("Couldn't find any with: " + word);
sendError(400, response);
}
LOGGER.info("Reached that point" + fittingProducts.encodePrettily());
response.putHeader("content-type", "application/json").end(fittingProducts.encodePrettily());
}
});
}
private void setUpInitialData(RoutingContext routingContext) {
addProduct(new JsonObject().put("id", "prod3568").put("name", "Egg Whisk").put("price", 3.99).put("weight", 150));
addProduct(new JsonObject().put("id", "prod7340").put("name", "Tea Cosy").put("price", 5.99).put("weight", 100));
addProduct(new JsonObject().put("id", "prod8643").put("name", "Spatula").put("price", 1.00).put("weight", 80));
insertUserInMongo(new JsonObject().put("uuid", (new UUID(10L, 1000L)).toString()).put("userName", "Sebastian").put("pw", "123abc"));
// + average rating and amount of ratings
HttpServerResponse response = routingContext.response();
response.putHeader("content-type", "application/json").end("initialized");
}
private void handleGetProduct(RoutingContext routingContext) {
String productID = routingContext.request().getParam("productID");
HttpServerResponse response = routingContext.response();
if (productID == null) {
sendError(400, response);
} else {
//JsonObject product = products.get(productID);
JsonObject product = findProductInMongoDB(productID);
if (product == null) {
sendError(404, response);
} else {
response.putHeader("content-type", "application/json").end(product.encode());
}
}
}
private JsonObject findProductInMongoDB(String productID) {
JsonObject query = new JsonObject();
query.put(productID + ".id", productID);
JsonObject result = new JsonObject();
CountDownLatch latch = new CountDownLatch(1);
LOGGER.info("Trying to find " + query.encodePrettily());
mongo.find("products", query, res -> {
if (res.succeeded()) {
for (JsonObject json : res.result()) {
LOGGER.info("Found product:" + json.encodePrettily());
result.put("product", json);
LOGGER.info("Result Json:" + result.encodePrettily());
}
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
LOGGER.error("latch error: " + e.getMessage());
}
LOGGER.info("Final result Json:" + result.encodePrettily());
return result;
}
private void handleAddProduct(RoutingContext routingContext) {
String productID = routingContext.request().getParam("productID");
HttpServerResponse response = routingContext.response();
try {
JsonObject voting = routingContext.getBodyAsJson();
if (productID == null) {
sendError(400, response);
} else {
JsonObject product = routingContext.getBodyAsJson(); // change product to user
if (product == null) {
sendError(400, response);
} else {
products.put(productID, product);
JsonObject productAsJson = new JsonObject();
productAsJson.put(productID, product);
insertInMongo(productAsJson);
response.end();
}
}
} catch (Exception e) {
sendError(400, response);
}
}
private void insertInMongo(JsonObject productAsJson) {
// calculate average rating + update product database averageRating + update user database add userproducts : {productId : , userRating : }
mongo.insert(("products"), productAsJson, res -> {
if (res.succeeded()) {
String id = res.result();
} else {
res.cause().printStackTrace();
}
});
}
private void handleListProducts(RoutingContext routingContext) {
JsonArray arr = new JsonArray();
products.forEach((k, v) -> arr.add(v));
routingContext.response().putHeader("content-type", "application/json").end(arr.encodePrettily());
}
private void sendError(int statusCode, HttpServerResponse response) {
response.setStatusCode(statusCode).end();
}
private void addProduct(JsonObject product) {
products.put(product.getString("id"), product);
JsonObject jsonObject = new JsonObject();
jsonObject.put(product.getString("id"), product);
LOGGER.info("JsonObject to insert: " + jsonObject.encodePrettily());
insertInMongo(jsonObject);
}
}
|
package com.frostwire.jlibtorrent;
import com.frostwire.jlibtorrent.swig.*;
import java.util.ArrayList;
import java.util.List;
/**
* The {@link AddTorrentParams} is a parameter pack for adding torrents to a
* session. The key fields when adding a torrent are:
* <ul>
* <li>ti - when you have a .torrent file</li>
* <li>url - when you have a magnet link or http URL to the .torrent file</li>
* <li>info_hash - when all you have is an info-hash (this is similar to a magnet link)</li>
* </ul>
* One of those fields need to be set. Another mandatory field is
* {@link #savePath()}. The {@link AddTorrentParams} object is passed into one of the
* {@link SessionHandle#addTorrent(AddTorrentParams, ErrorCode)} overloads or
* {@link SessionHandle#asyncAddTorrent(AddTorrentParams)}.
* <p>
* If you only specify the info-hash, the torrent file will be downloaded
* from peers, which requires them to support the metadata extension. It also
* takes an optional {@link #name()} argument. This may be left empty in case no
* name should be assigned to the torrent. In case it's not, the name is
* used for the torrent as long as it doesn't have metadata.
*
* @author gubatron
* @author aldenml
*/
public final class AddTorrentParams {
private final add_torrent_params p;
/**
* The native object
*
* @param p the native object
*/
public AddTorrentParams(add_torrent_params p) {
this.p = p;
}
/**
* Creates an empty parameters object with the default storage.
*/
public AddTorrentParams() {
this(add_torrent_params.create_instance());
}
/**
* @return the native object
*/
public add_torrent_params swig() {
return p;
}
/**
* Filled in by the constructor. It is used for forward binary compatibility.
*
* @return the version
*/
public int version() {
return p.getVersion();
}
/**
* {@link TorrentInfo} object with the torrent to add.
*
* @return the torrent info or null if not set
*/
public TorrentInfo torrentInfo() {
torrent_info ti = p.ti_ptr();
return ti != null && ti.is_valid() ? new TorrentInfo(ti) : null;
}
/**
* {@link TorrentInfo} object with the torrent to add.
*
* @param ti the torrent info
*/
public void torrentInfo(TorrentInfo ti) {
p.set_ti(ti.swig());
}
/**
* If the torrent doesn't have a tracker, but relies on the DHT to find
* peers, the {@link #trackers(List)} can specify tracker URLs for the torrent.
*
* @return the list of trackers
*/
public ArrayList<String> trackers() {
string_vector v = p.getTrackers();
int size = (int) v.size();
ArrayList<String> l = new ArrayList<>();
for (int i = 0; i < size; i++) {
l.add(v.get(i));
}
return l;
}
/**
* If the torrent doesn't have a tracker, but relies on the DHT to find
* peers, this method can specify tracker URLs for the torrent.
*
* @param value the list of trackers
*/
public void trackers(List<String> value) {
string_vector v = new string_vector();
for (String s : value) {
v.push_back(s);
}
p.setTrackers(v);
}
/**
* The tiers the URLs in {@link #trackers()} belong to. Trackers belonging to
* different tiers may be treated differently, as defined by the multi
* tracker extension. This is optional, if not specified trackers are
* assumed to be part of tier 0, or whichever the last tier was as
* iterating over the trackers.
*
* @return the list of trackers tiers
*/
public ArrayList<Integer> trackerTiers() {
int_vector v = p.getTracker_tiers();
int size = (int) v.size();
ArrayList<Integer> l = new ArrayList<>();
for (int i = 0; i < size; i++) {
l.add(v.get(i));
}
return l;
}
/**
* The tiers the URLs in {@link #trackers()} belong to. Trackers belonging to
* different tiers may be treated differently, as defined by the multi
* tracker extension. This is optional, if not specified trackers are
* assumed to be part of tier 0, or whichever the last tier was as
* iterating over the trackers.
*
* @param value the list of trackers tiers
*/
public void trackerTiers(List<Integer> value) {
int_vector v = new int_vector();
for (Integer t : value) {
v.push_back(t);
}
p.setTracker_tiers(v);
}
/**
* A list of hostname and port pairs, representing DHT nodes to be added
* to the session (if DHT is enabled). The hostname may be an IP address.
*
* @return the list of DHT nodes
*/
public ArrayList<Pair<String, Integer>> dhtNodes() {
string_int_pair_vector v = p.getDht_nodes();
int size = (int) v.size();
ArrayList<Pair<String, Integer>> l = new ArrayList<>();
for (int i = 0; i < size; i++) {
string_int_pair n = v.get(i);
l.add(new Pair<>(n.getFirst(), n.getSecond()));
}
return l;
}
/**
* A list of hostname and port pairs, representing DHT nodes to be added
* to the session (if DHT is enabled). The hostname may be an IP address.
*
* @param value the list of DHT nodes
*/
public void dhtNodes(List<Pair<String, Integer>> value) {
string_int_pair_vector v = new string_int_pair_vector();
for (Pair<String, Integer> p : value) {
v.push_back(p.to_string_int_pair());
}
p.setDht_nodes(v);
}
/**
* @return the name
*/
public String name() {
return p.getName();
}
/**
* @param value the name
*/
public void name(String value) {
p.setName(value);
}
/**
* The path where the torrent is or will be stored. Note that this may
* also be stored in resume data. If you want the save path saved in
* the resume data to be used, you need to set the
* flag_use_resume_save_path flag.
* <p>
* .. note::
* On windows this path (and other paths) are interpreted as UNC
* paths. This means they must use backslashes as directory separators
*
* @return the save path
*/
public String savePath() {
return p.getSave_path();
}
/**
* The path where the torrent is or will be stored. Note that this may
* also be stored in resume data. If you want the save path saved in
* the resume data to be used, you need to set the
* flag_use_resume_save_path flag.
* <p>
* .. note::
* On windows this path (and other paths) are interpreted as UNC
* paths. This means they must use backslashes as directory separators
*
* @param value the save path
*/
public void savePath(String value) {
p.setSave_path(value);
}
/**
* @return the storage mode
* @see StorageMode
*/
public StorageMode storageMode() {
return StorageMode.fromSwig(p.getStorage_mode().swigValue());
}
/**
* @param value the storage mode
* @see StorageMode
*/
public void storageMode(StorageMode value) {
p.setStorage_mode(storage_mode_t.swigToEnum(value.swig()));
}
/**
* The default tracker id to be used when announcing to trackers. By
* default this is empty, and no tracker ID is used, since this is an
* optional argument. If a tracker returns a tracker ID, that ID is used
* instead of this.
*
* @return the trackerid url parameter
*/
public String trackerId() {
return p.getTrackerid();
}
/**
* The default tracker id to be used when announcing to trackers. By
* default this is empty, and no tracker ID is used, since this is an
* optional argument. If a tracker returns a tracker ID, that ID is used
* instead of this.
*
* @param value the trackerid url parameter
*/
public void trackerId(String value) {
p.setTrackerid(value);
}
/**
* Set this to the info hash of the torrent to add in case the info-hash
* is the only known property of the torrent. i.e. you don't have a
* .torrent file nor a magnet link.
*
* @return the info-hash
*/
public Sha1Hash infoHash() {
return new Sha1Hash(p.getInfo_hash());
}
/**
* Set this to the info hash of the torrent to add in case the info-hash
* is the only known property of the torrent. i.e. you don't have a
* .torrent file nor a magnet link.
*
* @param value the info-hash
*/
public void infoHash(Sha1Hash value) {
p.setInfo_hash(value.swig());
}
/**
* @return max uploads limit
*/
public int maxUploads() {
return p.getMax_uploads();
}
/**
* @param value max uploads limit
*/
public void maxUploads(int value) {
p.setMax_uploads(value);
}
/**
* @return max connections limit
*/
public int maxConnections() {
return p.getMax_connections();
}
/**
* @param value max connections limit
*/
public void maxConnections(int value) {
p.setMax_connections(value);
}
/**
* @return upload limit
*/
public int uploadLimit() {
return p.getUpload_limit();
}
/**
* @param value upload limit
*/
public void uploadLimit(int value) {
p.setUpload_limit(value);
}
/**
* @return download limit
*/
public int downloadLimit() {
return p.getDownload_limit();
}
/**
* @param value download limit
*/
public void downloadLimit(int value) {
p.setDownload_limit(value);
}
/**
* Flags controlling aspects of this torrent and how it's added. See
* {@link com.frostwire.jlibtorrent.swig.add_torrent_params.flags_t} for details.
*
* @return the flags
*/
public long flags() {
return p.getFlags();
}
/**
* Flags controlling aspects of this torrent and how it's added. See
* {@link com.frostwire.jlibtorrent.swig.add_torrent_params.flags_t} for details.
*
* @param flags the flags
*/
public void flags(long flags) {
p.setFlags(flags);
}
/**
* Url seeds to be added to the torrent (`BEP 17`_).
*
* @return the url seeds
*/
public ArrayList<String> urlSeeds() {
string_vector v = p.getUrl_seeds();
int size = (int) v.size();
ArrayList<String> l = new ArrayList<>();
for (int i = 0; i < size; i++) {
l.add(v.get(i));
}
return l;
}
/**
* Url seeds to be added to the torrent (`BEP 17`_).
*
* @param value the url seeds
*/
public void urlSeeds(List<String> value) {
string_vector v = new string_vector();
for (String s : value) {
v.push_back(s);
}
p.setUrl_seeds(v);
}
/**
* Can be set to control the initial file priorities when adding a
* torrent. The semantics are the same as for
* {@link TorrentHandle#prioritizeFiles(Priority[])}.
*
* @param priorities the priorities
*/
public void filePriorities(Priority[] priorities) {
p.setFile_priorities(Priority.array2byte_vector(priorities));
}
/**
* This sets the priorities for each individual piece in the torrent. Each
* element in the vector represent the piece with the same index. If you
* set both file- and piece priorities, file priorities will take
* precedence.
*
* @param priorities the priorities
*/
public void piecePriorities(Priority[] priorities) {
p.setPiece_priorities(Priority.array2byte_vector(priorities));
}
/**
* Peers to add to the torrent, to be tried to be connected to as
* bittorrent peers.
*
* @return the peers list
*/
public ArrayList<TcpEndpoint> peers() {
tcp_endpoint_vector v = p.getPeers();
int size = (int) v.size();
ArrayList<TcpEndpoint> l = new ArrayList<>();
for (int i = 0; i < size; i++) {
l.add(new TcpEndpoint(v.get(i)));
}
return l;
}
/**
* Peers to add to the torrent, to be tried to be connected to as
* bittorrent peers.
*
* @param value the peers list
*/
public void peers(List<TcpEndpoint> value) {
tcp_endpoint_vector v = new tcp_endpoint_vector();
for (TcpEndpoint endp : value) {
v.push_back(endp.swig());
}
p.setPeers(v);
}
/**
* Peers banned from this torrent. The will not be connected to.
*
* @return the peers list
*/
public ArrayList<TcpEndpoint> bannedPeers() {
tcp_endpoint_vector v = p.getBanned_peers();
int size = (int) v.size();
ArrayList<TcpEndpoint> l = new ArrayList<>();
for (int i = 0; i < size; i++) {
l.add(new TcpEndpoint(v.get(i)));
}
return l;
}
/**
* Peers banned from this torrent. The will not be connected to.
*
* @param value the peers list
*/
public void bannedPeers(List<TcpEndpoint> value) {
tcp_endpoint_vector v = new tcp_endpoint_vector();
for (TcpEndpoint endp : value) {
v.push_back(endp.swig());
}
p.setBanned_peers(v);
}
/**
* @return an instance with the default storage
*/
public static AddTorrentParams createInstance() {
return new AddTorrentParams(add_torrent_params.create_instance());
}
/**
* @return an instance with a disabled storage
*/
public static AddTorrentParams createInstanceDisabledStorage() {
return new AddTorrentParams(add_torrent_params.create_instance_disabled_storage());
}
/**
* @return an instance with a zero storage
*/
public static AddTorrentParams createInstanceZeroStorage() {
return new AddTorrentParams(add_torrent_params.create_instance_zero_storage());
}
/**
* Helper function to parse a magnet uri and fill the parameters.
*
* @param uri the magnet uri
* @param params the parameters to fill
* @return the same object as params to allow for fluently style
*/
public static AddTorrentParams parseMagnetUri(String uri, AddTorrentParams params) {
error_code ec = new error_code();
add_torrent_params.parse_magnet_uri(uri, params.swig(), ec);
if (ec.value() != 0) {
throw new IllegalArgumentException("Invalid magnet uri: " + ec.message());
}
return params;
}
}
|
package com.github.dakusui.jcunit8.pipeline;
import com.github.dakusui.jcunit.core.tuples.Tuple;
import com.github.dakusui.jcunit8.factorspace.Constraint;
import com.github.dakusui.jcunit8.factorspace.Factor;
import com.github.dakusui.jcunit8.factorspace.FactorSpace;
import com.github.dakusui.jcunit8.factorspace.ParameterSpace;
import com.github.dakusui.jcunit8.pipeline.stages.Encoder;
import com.github.dakusui.jcunit8.pipeline.stages.Generator;
import com.github.dakusui.jcunit8.pipeline.stages.Joiner;
import com.github.dakusui.jcunit8.pipeline.stages.Partitioner;
import com.github.dakusui.jcunit8.testsuite.SchemafulTupleSet;
import java.util.List;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
public interface Config {
Requirement getRequirement();
/**
* Returns a function that encodes a parameter space into internal factor spaces.
*/
Function<ParameterSpace, FactorSpace> encoder();
Function<FactorSpace, List<FactorSpace>> partitioner();
Function<FactorSpace, SchemafulTupleSet> generator(Requirement requirement);
BinaryOperator<SchemafulTupleSet> joiner();
Function<? super FactorSpace, ? extends FactorSpace> optimizer();
class Builder {
private final Requirement requirement;
private Generator.Factory generatorFactory;
private Joiner joiner;
private Partitioner partitioner;
public static Builder forTuple(Requirement requirement) {
return new Builder(requirement);
}
public Builder(Requirement requirement) {
this.requirement = requirement;
this.generatorFactory = new Generator.Factory.Standard();
this.joiner = new Joiner.Standard(requirement);
this.partitioner = new Partitioner.Standard();
}
public Builder withGeneratorFactory(Generator.Factory generatorFactory) {
this.generatorFactory = generatorFactory;
return this;
}
public Builder withJoiner(Joiner joiner) {
this.joiner = joiner;
return this;
}
public Builder withPartitioner(Partitioner partitioner) {
this.partitioner = partitioner;
return this;
}
public Config build() {
return new Impl(requirement, generatorFactory, joiner, partitioner);
}
}
class Impl implements Config {
private final Generator.Factory generatorFactory;
private final Joiner joiner;
private final Partitioner partitioner;
private final Requirement requirement;
private final Encoder encoder;
public Impl(Requirement requirement, Generator.Factory generatorFactory, Joiner joiner, Partitioner partitioner) {
this.generatorFactory = requireNonNull(generatorFactory);
this.encoder = new Encoder.Standard();
this.joiner = requireNonNull(joiner);
this.partitioner = requireNonNull(partitioner);
this.requirement = requireNonNull(requirement);
}
@Override
public Function<ParameterSpace, FactorSpace> encoder() {
return this.encoder;
}
@Override
public Function<FactorSpace, List<FactorSpace>> partitioner() {
return partitioner;
}
@Override
public Function<FactorSpace, SchemafulTupleSet> generator(Requirement requirement) {
return (FactorSpace factorSpace) ->
new SchemafulTupleSet.Builder(factorSpace.getFactors().stream().map(Factor::getName).collect(toList()))
.addAll(generatorFactory.create(emptyList(), factorSpace, requirement).generate())
.build();
}
@Override
public BinaryOperator<SchemafulTupleSet> joiner() {
return joiner;
}
@Override
public Requirement getRequirement() {
return requirement;
}
/**
* Returns a function that removes levels that cannot be valid because single
* parameter constraints invalidate them.
*/
@Override
public Function<? super FactorSpace, ? extends FactorSpace> optimizer() {
return (FactorSpace factorSpace) -> FactorSpace.create(
factorSpace.getFactors().stream()
.map(
(Factor factor) -> Factor.create(
factor.getName(),
factor.getLevels()
.stream()
.filter(
(Object o) -> factorSpace.getConstraints()
.stream()
.filter((Constraint constraint) -> singletonList(factor.getName()).equals(constraint.involvedKeys()))
.allMatch((Constraint constraint) -> constraint.test(new Tuple.Builder().put(factor.getName(), o).build()))
)
.collect(toList()).toArray()
))
.collect(toList()),
factorSpace.getConstraints().stream()
.filter(
(Constraint constraint) -> constraint.involvedKeys().size() > 1
)
.collect(toList())
);
}
}
}
|
package com.github.niwaniwa.we.core.listener;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import javax.imageio.ImageIO;
import com.github.niwaniwa.we.core.util.lib.Title;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.server.ServerListPingEvent;
import org.bukkit.util.CachedServerIcon;
import com.github.niwaniwa.we.core.WhiteEggCore;
import com.github.niwaniwa.we.core.api.WhiteEggAPI;
import com.github.niwaniwa.we.core.command.abs.WhiteEggCommandExecutor;
import com.github.niwaniwa.we.core.event.WhiteEggPostTweetEvent;
import com.github.niwaniwa.we.core.event.WhiteEggPreTweetEvent;
import com.github.niwaniwa.we.core.player.WhitePlayer;
import com.github.niwaniwa.we.core.util.command.CommandFactory;
import com.github.niwaniwa.we.core.util.lib.clickable.Clickable;
import twitter4j.TwitterException;
public class Debug implements Listener {
private CachedServerIcon icon;
public Debug() {
URL imageUrl = null;
InputStream input = null;
try {
imageUrl = new URL("https://minotar.net/helm/KokekoKko_");
input = imageUrl.openConnection().getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
BufferedImage bufferedImage ;
CachedServerIcon icon = null;
try {
bufferedImage = ImageIO.read(input);
Image tmp = bufferedImage.getScaledInstance(64, 64, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
icon = Bukkit.getServer().loadServerIcon(dimg);
} catch (Exception e) {
e.printStackTrace();
}
if(icon != null){ this.icon = icon; }
icon = null;
}
@EventHandler
public void onPing(ServerListPingEvent event){
if(icon == null){ return; }
event.setServerIcon(icon);
}
@EventHandler(priority = EventPriority.LOW)
public void onJoin(PlayerJoinEvent event) {
final WhitePlayer player = WhiteEggAPI.getPlayer(event.getPlayer());
if(event.getPlayer().getUniqueId().toString()
.equalsIgnoreCase("f010845c-a9ac-4a04-bf27-61d92f8b03ff")){
WhiteEggCore.getInstance().getLogger().info(
"-- " + player.getPlayer().getName() + "Join the game. --");
}
Title title = new Title("§6>>Main Title<<", "§7sub title");
title.send(player.getPlayer());
Clickable clickable = new Clickable("test");
clickable.send(player.getPlayer());
CommandFactory commandFactory = new CommandFactory(WhiteEggCore.getInstance(), "debug");
commandFactory.setExecutor(new WhiteEggCommandExecutor() {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
sender.sendMessage("test");
return true;
}
@Override
public List<String> getUsing() { return null; }
@Override
public String getPermission() { return "whiteegg.core.command.debug"; }
@Override
public String getCommandName() { return "debug"; }
});
commandFactory.register();
}
@EventHandler
public void onTweet(WhiteEggPreTweetEvent event){
System.out.println(" : Event " + event.getEventName() + " : "
+ " Tweet " + event.getTweet() + " : Player " + event.getPlayer().getFullName());
}
@EventHandler
public void postTweetEvent(WhiteEggPostTweetEvent event) throws IllegalStateException, TwitterException{
System.out.println(" : Event " + event.getEventName() + " : "
+ " Tweet " + event.getStatus().getText()
+ " : Twitter ID " + event.getTwitter().getTwitter().getScreenName());
}
}
|
package com.isomorphic.maven.mojo;
import java.util.List;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.maven.model.building.ModelBuilder;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Server;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest;
import org.apache.maven.settings.crypto.SettingsDecrypter;
import org.apache.maven.settings.crypto.SettingsDecryptionRequest;
import org.apache.maven.settings.crypto.SettingsDecryptionResult;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.impl.ArtifactResolver;
import org.eclipse.aether.impl.RemoteRepositoryManager;
import org.eclipse.aether.repository.Authentication;
import org.eclipse.aether.util.repository.AuthenticationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractBaseMojo extends AbstractMojo {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractBaseMojo.class);
@Parameter(readonly = true, defaultValue = "${repositorySystemSession}")
protected RepositorySystemSession repositorySystemSession;
@Component
protected ModelBuilder modelBuilder;
@Component
protected MavenProject project;
@Component
protected RepositorySystem repositorySystem;
@Component
protected ArtifactResolver artifactResolver;
@Component
protected RemoteRepositoryManager remoteRepositoryManager;
@Component
protected Settings settings;
@Component
private SettingsDecrypter settingsDecrypter;
@Override
public abstract void execute() throws MojoExecutionException, MojoFailureException;
public UsernamePasswordCredentials getCredentials(String serverId) {
Server server = getDecryptedServer(serverId);
String username = null;
String password = null;
if (server != null) {
username = server.getUsername();
password = server.getPassword();
return new UsernamePasswordCredentials(username, password);
}
return null;
}
protected Authentication getAuthentication(String serverId) {
Authentication authentication = null;
Server server = getDecryptedServer(serverId);
if (server != null) {
authentication = new AuthenticationBuilder()
.addUsername(server.getUsername())
.addPassword(server.getPassword())
.addPrivateKey(server.getPrivateKey(), server.getPassphrase())
.build();
}
return authentication;
}
private Server getDecryptedServer(String id) {
final SettingsDecryptionRequest settingsDecryptionRequest = new DefaultSettingsDecryptionRequest();
settingsDecryptionRequest.setServers(settings.getServers());
final SettingsDecryptionResult decrypt = settingsDecrypter.decrypt(settingsDecryptionRequest);
List<Server> servers = decrypt.getServers();
for (Server server : servers) {
if (server.getId().equals(id)) {
return server;
}
}
return null;
}
}
|
package com.minespaceships.mod.spaceship;
import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
import java.util.Set;
import java.util.Vector;
import javax.vecmath.Vector3d;
import com.google.common.collect.ImmutableList;
import com.minespaceships.mod.blocks.NavigatorBlock;
import com.minespaceships.mod.overhead.ChatRegisterEntity;
import com.minespaceships.util.BlockCopier;
import com.minespaceships.util.Vec3Op;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoor;
import net.minecraft.block.BlockDoor.EnumDoorHalf;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.Vec3;
import net.minecraft.util.Vec3i;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
public class Spaceship implements Serializable{
private BlockPos origin;
private WorldServer worldS;
private BlockMap blockMap;
private SpaceshipAssembler assembler;
private boolean canBeRemoved = true;
public static final int maxShipSize = 27000;
@Deprecated
public Spaceship(final BlockPos minSpan, final BlockPos origin, final BlockPos maxSpan, WorldServer worldS){
this.origin = origin;
this.worldS = worldS;
setMeasurements(((BlockPos) minSpan).add(origin), ((BlockPos) maxSpan).add(origin));
initializeBase();
}
@Deprecated
public Spaceship(int[] originMeasurement){
worldS = (WorldServer)MinecraftServer.getServer().getEntityWorld();
readOriginMeasurementArray(originMeasurement);
initializeBase();
}
public Spaceship(BlockPos initial, WorldServer worldS) throws Exception{
blockMap = new BlockMap(initial);
blockMap = SpaceshipMath.getConnectedPositions(initial, Minecraft.getMinecraft().theWorld, maxShipSize);
if(blockMap == null){
throw new Exception("Ship is too huge or connected to the Ground");
}
this.origin = initial;
this.worldS = worldS;
initializeBase();
}
public Spaceship(BlockMap blocks, WorldServer worldS){
blockMap = blocks;
this.worldS = worldS;
initializeBase();
}
public Spaceship(String s, WorldServer worldS)throws Exception {
this.fromData(s);
this.worldS = worldS;
this.origin = blockMap.getOrigin();
initializeBase();
}
private void initializeBase(){
assembler = new SpaceshipAssembler(blockMap.getOrigin());
refreshParts();
Shipyard.getShipyard().addShip(this);
}
public BlockPos getOrigin(){
return origin;
}
public BlockPos getMaxPos(){
return blockMap.getMaxPos();
}
public BlockPos getMinPos(){
return blockMap.getMinPos();
}
public boolean canBeRemoved(){
return canBeRemoved;
}
public int getNavigatorCount(){
return assembler.getParts(NavigatorBlock.class).size();
}
public ArrayList<BlockPos> getPositions(){
return blockMap.getPositions();
}
public BlockMap getBlockMap(){
return blockMap;
}
@Deprecated
public int[] getOriginMeasurementArray(){
BlockPos minSpan = blockMap.getMinPos().subtract(origin);
BlockPos maxSpan = blockMap.getMaxPos().subtract(origin);
int[] a = {minSpan.getX(), minSpan.getY(), minSpan.getZ(),
origin.getX(), origin.getY(), origin.getZ(),
maxSpan.getX(), maxSpan.getY(), maxSpan.getZ()};
return a;
}
@Deprecated
public void readOriginMeasurementArray(int[] array){
try {
BlockPos minSpan = new BlockPos(array[0], array[1], array[2]);
BlockPos maxSpan = new BlockPos(array[6], array[7], array[8]);
origin = new BlockPos(array[3], array[4], array[5]);
setMeasurements(minSpan.add(origin), maxSpan.add(origin));
origin = new BlockPos(array[3], array[4], array[5]);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Could not read OriginMeasurementArray (probably an error with NBT). Try creating a new World.");
System.out.println("Printing Exception Stack:");
System.out.println(ex.getMessage());
}
}
@Deprecated
private void setMeasurements(final BlockPos minPos, final BlockPos maxPos){
blockMap = new BlockMap(minPos);
BlockPos span = ((BlockPos) maxPos).subtract(minPos);
for(int x = 0; x <= span.getX(); x++){
for(int y = 0; y <= span.getY(); y++){
for(int z = 0; z <= span.getZ(); z++){
//if(!worldS.isAirBlock(new BlockPos(x,y,z).add(minPos))){
blockMap.add(new BlockPos(x,y,z).add(minPos));
}
}
}
origin = Vec3Op.scale(span, 0.5);
}
public void setTarget(BlockPos position){
moveTo(position.subtract(origin), 0, worldS);
}
public void setTarget(BlockPos position, WorldServer world){
moveTo(position.subtract(origin), world);
}
public void moveTo(BlockPos addDirection) {
moveTo(addDirection, worldS, 0);
}
public void moveTo(BlockPos addDirection, WorldServer world) {
moveTo(addDirection, world, 0);
}
public void moveTo(BlockPos addDirection, int turn, WorldServer world) {
moveTo(addDirection, world, turn);
}
private void moveTo(BlockPos addDirection, World world, final int turn){
//prevent it from being removed from the shipyard
canBeRemoved = false;
//list of positions that need to be removed in revers order to prevent other blocks from cracking
Vector<BlockPos> removal = new Vector<BlockPos>();
//get all positions that can't be placed right now
BlockPos add = new BlockPos(addDirection);
ArrayList<BlockPos> positions = blockMap.getPositions();
int i = 3;
while(!positions.isEmpty() && i > 0){
Iterator<BlockPos> it = positions.iterator();
while(it.hasNext()){
BlockPos Pos = it.next();
IBlockState state = world.getBlockState(Pos);
Block block = state.getBlock();
BlockPos nextPos = Turn.getRotatedPos(Pos, this.origin, add, turn);
EnumFacing facing = Turn.getEnumFacing(state);
BlockPos neighbor = null;
IBlockState neighborState = null;
if(facing != null){
facing = (EnumFacing)Turn.getNextFacing(facing, turn);
neighbor = nextPos.offset(facing.getOpposite());
neighborState = world.getBlockState(neighbor);
}
if((facing == null || (facing != null && world.isSideSolid(neighbor, facing)))){
//build the buildable block
BlockCopier.copyBlock(world, Pos, nextPos, turn);
it.remove();
//remember to remove it
removal.add(Pos);
}
}
i
}
//if there are blocks left
if(!positions.isEmpty()){
for(BlockPos Pos : positions){
//force placement
BlockPos nextPos = Turn.getRotatedPos(Pos, this.origin, add, turn);
BlockCopier.copyBlock(world, Pos, nextPos, turn);
//again: remember to remove the Block. Now we need to append these at the front as they make problems when deleted last. This is cause of some deep Minecraft thingy
removal.insertElementAt(Pos, 0);
}
}
//remove the Blocks in reversed order, so that the most fragile ones are removed last.
ListIterator<BlockPos> reverseRemoval = removal.listIterator(removal.size());
while(reverseRemoval.hasPrevious()){
BlockCopier.removeBlock(world, reverseRemoval.previous());
}
//move the entities and move the ships measurements
moveEntities(addDirection, turn);
moveMeasurements(addDirection, turn);
canBeRemoved = true;
}
private void moveMeasurements(BlockPos addDirection, int turn){
if(turn != 0){blockMap.rotate(origin, turn);}
blockMap.setOrigin(blockMap.getOrigin().add(addDirection));
assembler.setOrigin(blockMap.getOrigin().add(addDirection));
origin = origin.add(addDirection);
}
@Deprecated
private void moveEntities(BlockPos addDirection, int turn){
List<Entity> entities = worldS.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(blockMap.getMinPos(), blockMap.getMaxPos().add(1,1,1)));
for(Entity ent : entities){
if(ent instanceof EntityPlayer){
((EntityPlayer)ent).addPotionEffect(new PotionEffect(Potion.blindness.getId(),10));
}
Vec3 addDir = new Vec3(addDirection.getX(), addDirection.getY(), addDirection.getZ());
Vec3 orig = new Vec3(origin.getX(), origin.getY(), origin.getZ());
Vec3 newPos = Turn.getRotatedPos(ent.getPositionVector(), orig, addDir, turn);
switch(turn){
case Turn.LEFT:
ent.setRotationYawHead((float) (ent.rotationYaw+Math.PI/2));
break;
case Turn.RIGHT:
ent.setRotationYawHead((float) (ent.rotationYaw-Math.PI/2));
break;
case Turn.AROUND:
ent.setRotationYawHead((float) (ent.rotationYaw+Math.PI));
break;
}
ent.setPositionAndUpdate(newPos.xCoord, newPos.yCoord, newPos.zCoord);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("minPosition: " + blockMap.getMinPos().toString());
sb.append("\nmaxPosition: " + blockMap.getMaxPos().toString());
sb.append("\norigin: " + origin.toString());
sb.append("\nworldServer: " + worldS == null ? "Not Known.\n" : "Known\n");
return sb.toString();
}
public WorldServer getWorld() {
return this.worldS;
}
public Boolean containsBlock(BlockPos pos) {
return this.blockMap.contains(pos);
}
public boolean removeBlock(BlockPos pos) {
this.blockMap.remove(pos, Minecraft.getMinecraft().theWorld);
removeSpaceshipPart(pos);
if(getNavigatorCount() <= 0){
return true;
}
return false;
}
private void removeSpaceshipPart(BlockPos pos){
IBlockState state = worldS.getBlockState(pos);
if(state.getBlock() instanceof ISpaceshipPart){
assembler.remove(state, pos);
}
}
public void addBlock(final BlockPos pos) {
this.blockMap.add(pos);
addSpaceshipPart(pos);
}
private void addSpaceshipPart(BlockPos pos){
IBlockState state = worldS.getBlockState(pos);
if(state.getBlock() instanceof ISpaceshipPart){
assembler.put(state, pos);
}
}
public void refreshParts(){
assembler.clear();
ArrayList<BlockPos> position = blockMap.getPositions();
for(BlockPos pos : position){
addSpaceshipPart(pos);
}
}
public boolean isNeighboringBlock(final BlockPos pos) {
return this.blockMap.isNeighbor(pos);
}
public String toData(){
String data = "";
ArrayList<BlockPos> positions = blockMap.getPositions();
data += blockMap.getOrigin().toLong()+"\n";
for(BlockPos pos : positions){
data += pos.toLong()+"\n";
}
return data;
}
public void fromData(String data) throws Exception{
String[] lines = data.split("\n");
blockMap = new BlockMap(BlockPos.fromLong(Long.parseLong(lines[0])));
for(int i = 1; i < lines.length; i++){
blockMap.add(BlockPos.fromLong(Long.parseLong(lines[i])));
}
}
public boolean measuresEquals(Spaceship ship){
return ship.blockMap.getMaxPos().equals(blockMap.getMaxPos()) &&
ship.blockMap.getMinPos().equals(blockMap.getMinPos()) &&
ship.getWorld() == worldS;
}
public void debugMap(){
blockMap.showDebug(worldS);
}
}
|
package com.mixpanel.android.util;
import android.graphics.Bitmap;
public class StackBlurManager {
public static void process(Bitmap source, int radius) {
if (radius < 1) {
return; // No work to do
}
final int width = source.getWidth();
final int height = source.getHeight();
final int[] currentPixels = new int[width * height];
source.getPixels(currentPixels, 0, width, 0, 0, width, height);
final int wm = width-1;
final int hm = height-1;
final int wh = width * height;
final int div = radius + radius + 1;
final int r[] = new int[wh];
final int g[] = new int[wh];
final int b[] = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp;
final int vmin[] = new int[Math.max(width, height)];
int divsum = (div+1)>>1;
divsum *= divsum;
final int dv[] = new int[256*divsum];
for (i = 0; i < 256 * divsum;i++){
dv[i] = i / divsum;
}
int yw = 0;
int yi = 0;
final int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
final int r1=radius+1;
int routsum,goutsum,boutsum;
int rinsum,ginsum,binsum;
for (y=0; y < height; y++){
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for(i = -radius; i <= radius; i++){
p = currentPixels[yi + Math.min(wm, Math.max(i,0))];
sir = stack[i+radius];
sir[0] = (p & 0xff0000)>>16;
sir[1] = (p & 0x00ff00)>>8;
sir[2] = (p & 0x0000ff);
rbs = r1-Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i>0){
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < width; x++){
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if(y==0){
vmin[x] = Math.min(x + radius + 1,wm);
}
p = currentPixels[yw + vmin[x]];
sir[0] = (p & 0xff0000)>>16;
sir[1] = (p & 0x00ff00)>>8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += width;
}
for (x=0; x < width; x++){
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * width;
for (i = -radius; i <= radius; i++){
yi = Math.max(0,yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rsum+=r[yi]*rbs;
gsum+=g[yi]*rbs;
bsum+=b[yi]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
if(i<hm){
yp += width;
}
}
yi=x;
stackpointer=radius;
for (y = 0; y < height; y++){
currentPixels[yi] = 0xff000000 | (dv[rsum]<<16) | (dv[gsum]<<8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if(x == 0){
vmin[y] = Math.min(y + r1, hm) * width;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += width;
}
}
source.setPixels(currentPixels, 0, width, 0, 0, width, height);
}// process()
}
|
// LegacyManager.java
package imagej.legacy;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import imagej.ImageJ;
import imagej.Manager;
import imagej.ManagerComponent;
import imagej.data.Dataset;
import imagej.display.Display;
import imagej.display.DisplayManager;
import imagej.display.event.DisplayActivatedEvent;
import imagej.display.event.key.KyPressedEvent;
import imagej.display.event.key.KyReleasedEvent;
import imagej.event.EventSubscriber;
import imagej.event.Events;
import imagej.event.OptionsChangedEvent;
import imagej.legacy.patches.FunctionsMethods;
import imagej.util.Log;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
/**
* Manager component for working with legacy ImageJ 1.x.
* <p>
* The legacy manager overrides the behavior of various IJ1 methods, inserting
* seams so that (e.g.) the modern UI is aware of IJ1 events as they occur.
* </p>
* <p>
* It also maintains an image map between IJ1 {@link ImagePlus} objects and IJ2
* {@link Dataset}s.
* </p>
* <p>
* In this fashion, when a legacy plugin is executed on a {@link Dataset}, the
* manager transparently translates it into an {@link ImagePlus}, and vice
* versa, enabling backward compatibility with legacy plugins.
* </p>
*
* @author Curtis Rueden
*/
@Manager(priority = Manager.HIGH_PRIORITY)
public final class LegacyManager implements ManagerComponent {
static {
// NB: Override class behavior before class loading gets too far along.
final CodeHacker hacker = new CodeHacker();
// override behavior of ij.ImageJ
hacker.insertMethod("ij.ImageJ",
"public java.awt.Point getLocationOnScreen()");
hacker.loadClass("ij.ImageJ");
// override behavior of ij.IJ
hacker.insertAfterMethod("ij.IJ",
"public static void showProgress(double progress)");
hacker.insertAfterMethod("ij.IJ",
"public static void showProgress(int currentIndex, int finalIndex)");
hacker.insertAfterMethod("ij.IJ",
"public static void showStatus(java.lang.String s)");
hacker.loadClass("ij.IJ");
// override behavior of ij.ImagePlus
hacker.insertAfterMethod("ij.ImagePlus", "public void updateAndDraw()");
hacker.insertAfterMethod("ij.ImagePlus", "public void repaintWindow()");
hacker.loadClass("ij.ImagePlus");
// override behavior of ij.gui.ImageWindow
hacker.insertMethod("ij.gui.ImageWindow",
"public void setVisible(boolean vis)");
hacker.insertMethod("ij.gui.ImageWindow", "public void show()");
hacker.insertBeforeMethod("ij.gui.ImageWindow", "public void close()");
hacker.loadClass("ij.gui.ImageWindow");
// override behavior of ij.macro.Functions
hacker
.insertBeforeMethod("ij.macro.Functions",
"void displayBatchModeImage(ij.ImagePlus imp2)",
"imagej.legacy.patches.FunctionsMethods.displayBatchModeImageBefore(imp2);");
hacker
.insertAfterMethod("ij.macro.Functions",
"void displayBatchModeImage(ij.ImagePlus imp2)",
"imagej.legacy.patches.FunctionsMethods.displayBatchModeImageAfter(imp2);");
hacker.loadClass("ij.macro.Functions");
// override behavior of MacAdapter
hacker.replaceMethod("MacAdapter",
"public void run(java.lang.String arg)", ";");
hacker.loadClass("MacAdapter");
}
/** Mapping between modern and legacy image data structures. */
private LegacyImageMap imageMap;
/** Method of synchronizing IJ2 & IJ1 options */
private OptionsSynchronizer optionsSynchronizer;
/** Maintain list of subscribers, to avoid garbage collection. */
private List<EventSubscriber<?>> subscribers;
// -- LegacyManager methods --
public LegacyImageMap getImageMap() {
return imageMap;
}
/**
* Indicates to the manager that the given {@link ImagePlus} has changed as
* part of a legacy plugin execution.
*/
public void legacyImageChanged(final ImagePlus imp) {
// CTR FIXME rework static InsideBatchDrawing logic?
if (FunctionsMethods.InsideBatchDrawing > 0) return;
// record resultant ImagePlus as a legacy plugin output
LegacyOutputTracker.getOutputImps().add(imp);
}
/**
* Ensures that the currently active {@link ImagePlus} matches the currently
* active {@link Display}. Does not perform any harmonization.
*/
public void syncActiveImage() {
final DisplayManager displayManager = ImageJ.get(DisplayManager.class);
final Display activeDisplay = displayManager.getActiveDisplay();
final ImagePlus activeImagePlus = imageMap.lookupImagePlus(activeDisplay);
WindowManager.setTempCurrentImage(activeImagePlus);
}
// -- ManagerComponent methods --
@Override
public void initialize() {
imageMap = new LegacyImageMap();
optionsSynchronizer = new OptionsSynchronizer();
// initialize legacy ImageJ application
try {
new ij.ImageJ(ij.ImageJ.NO_SHOW);
}
catch (final Throwable t) {
Log.warn("Failed to instantiate IJ1.", t);
}
// TODO - FIXME
// call optionsSynchronizer.update() here? Need to determine when the
// IJ2 settings file has been read/initialized and then call update() once.
subscribeToEvents();
}
// -- Helper methods --
@SuppressWarnings("synthetic-access")
private void subscribeToEvents() {
subscribers = new ArrayList<EventSubscriber<?>>();
// keep the active legacy ImagePlus in sync with the active modern Display
final EventSubscriber<DisplayActivatedEvent> displayActivatedSubscriber =
new EventSubscriber<DisplayActivatedEvent>() {
@Override
public void onEvent(final DisplayActivatedEvent event) {
syncActiveImage();
}
};
subscribers.add(displayActivatedSubscriber);
Events.subscribe(DisplayActivatedEvent.class, displayActivatedSubscriber);
final EventSubscriber<OptionsChangedEvent> optionSubscriber =
new EventSubscriber<OptionsChangedEvent>() {
@Override
public void onEvent(OptionsChangedEvent event) {
optionsSynchronizer.update();
}
};
subscribers.add(optionSubscriber);
Events.subscribe(OptionsChangedEvent.class, optionSubscriber);
// TODO - FIXME remove AWT dependency when we have implemented our own
// KyEvent constants
final EventSubscriber<KyPressedEvent> pressSubscriber =
new EventSubscriber<KyPressedEvent>() {
@Override
public void onEvent(KyPressedEvent event) {
int code = event.getCode();
if (code == KeyEvent.VK_SPACE)
IJ.setKeyDown(KeyEvent.VK_SPACE);
if (code == KeyEvent.VK_ALT)
IJ.setKeyDown(KeyEvent.VK_ALT);
if (code == KeyEvent.VK_SHIFT)
IJ.setKeyDown(KeyEvent.VK_SHIFT);
if (code == KeyEvent.VK_CONTROL)
IJ.setKeyDown(KeyEvent.VK_CONTROL);
if ((IJ.isMacintosh()) && (code == KeyEvent.VK_META))
IJ.setKeyDown(KeyEvent.VK_CONTROL);
}
};
subscribers.add(pressSubscriber);
Events.subscribe(KyPressedEvent.class, pressSubscriber);
// TODO - FIXME remove AWT dependency when we have implemented our own
// KyEvent constants
final EventSubscriber<KyReleasedEvent> releaseSubscriber =
new EventSubscriber<KyReleasedEvent>() {
@Override
public void onEvent(KyReleasedEvent event) {
int code = event.getCode();
if (code == KeyEvent.VK_SPACE)
IJ.setKeyUp(KeyEvent.VK_SPACE);
if (code == KeyEvent.VK_ALT)
IJ.setKeyUp(KeyEvent.VK_ALT);
if (code == KeyEvent.VK_SHIFT)
IJ.setKeyUp(KeyEvent.VK_SHIFT);
if (code == KeyEvent.VK_CONTROL)
IJ.setKeyUp(KeyEvent.VK_CONTROL);
if ((IJ.isMacintosh()) && (code == KeyEvent.VK_CONTROL))
IJ.setKeyUp(KeyEvent.VK_CONTROL);
}
};
subscribers.add(releaseSubscriber);
Events.subscribe(KyReleasedEvent.class, releaseSubscriber);
}
}
|
package com.pearson.statsagg.webui;
import com.pearson.statsagg.alerts.MetricAssociation;
import com.pearson.statsagg.database_objects.metric_group.MetricGroup;
import com.pearson.statsagg.database_objects.metric_group.MetricGroupsDao;
import com.pearson.statsagg.database_objects.output_blacklist.OutputBlacklistDao;
import com.pearson.statsagg.globals.GlobalVariables;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.pearson.statsagg.utilities.StackTrace;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jeffrey Schmidt
*/
@WebServlet(name = "OutputBlacklist", urlPatterns = {"/OutputBlacklist"})
public class OutputBlacklist extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(OutputBlacklist.class.getName());
public static final String PAGE_NAME = "Output Blacklist";
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
processGetRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
processPostRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return PAGE_NAME;
}
protected void processGetRequest(HttpServletRequest request, HttpServletResponse response) {
if ((request == null) || (response == null)) {
return;
}
try {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
PrintWriter out = null;
try {
StringBuilder htmlBuilder = new StringBuilder();
List<String> additionalJavascript = new ArrayList<>();
additionalJavascript.add("js/statsagg_output_blacklist.js");
StatsAggHtmlFramework statsAggHtmlFramework = new StatsAggHtmlFramework();
String htmlHeader = statsAggHtmlFramework.createHtmlHeader("StatsAgg - " + PAGE_NAME, "");
String htmlBodyContents = buildOutputBlacklistHtml();
String htmlBody = statsAggHtmlFramework.createHtmlBody(htmlBodyContents, additionalJavascript, false);
htmlBuilder.append("<!DOCTYPE html>\n<html>\n").append(htmlHeader).append(htmlBody).append("</html>");
Document htmlDocument = Jsoup.parse(htmlBuilder.toString());
String htmlFormatted = htmlDocument.toString();
out = response.getWriter();
out.println(htmlFormatted);
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
finally {
if (out != null) {
out.close();
}
}
}
protected void processPostRequest(HttpServletRequest request, HttpServletResponse response) {
if ((request == null) || (response == null)) {
return;
}
try {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
PrintWriter out = null;
String metricGroupName = request.getParameter("MetricGroupName");
boolean updateSuccess = updateOutputBlacklistMetricGroupId(metricGroupName);
if (updateSuccess) {
MetricAssociation.IsMetricGroupChangeOutputBlacklist.set(true);
GlobalVariables.metricAssociationOutputBlacklistInvokerThread.runMetricAssociationOutputBlacklistThread();
}
try {
String result;
if (updateSuccess) result = "Successfully updated the output blacklist's metric group association.";
else result = "Failed to update the output blacklist's metric group association.";
StringBuilder htmlBuilder = new StringBuilder();
StatsAggHtmlFramework statsAggHtmlFramework = new StatsAggHtmlFramework();
String htmlHeader = statsAggHtmlFramework.createHtmlHeader("StatsAgg - " + PAGE_NAME, "");
String htmlBodyContent = statsAggHtmlFramework.buildHtmlBodyForPostResult(PAGE_NAME + " Update ", StatsAggHtmlFramework.htmlEncode(result), "OutputBlacklist", PAGE_NAME);
String htmlBody = statsAggHtmlFramework.createHtmlBody(htmlBodyContent);
htmlBuilder.append("<!DOCTYPE html>\n<html>\n").append(htmlHeader).append(htmlBody).append("</html>");
Document htmlDocument = Jsoup.parse(htmlBuilder.toString());
String htmlFormatted = htmlDocument.toString();
out = response.getWriter();
out.println(htmlFormatted);
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
finally {
if (out != null) {
out.close();
}
}
}
private String buildOutputBlacklistHtml() {
StringBuilder htmlBody = new StringBuilder();
htmlBody.append(
"<div id=\"page-content-wrapper\">\n" +
" <!-- Keep all page content within the page-content inset div! -->\n" +
" <div class=\"page-content inset statsagg_page_content_font\">\n" +
" <div class=\"content-header\"> \n" +
" <div class=\"pull-left content-header-h2-min-width-statsagg\"> <h2> " + PAGE_NAME + " </h2> </div>\n" +
" </div> ");
String metricGroupName = getMetricGroupNameAssociatedWithOutputBlacklist();
String metricAssociationsLink = "";
com.pearson.statsagg.database_objects.output_blacklist.OutputBlacklist outputBlacklist = OutputBlacklistDao.getSingleOutputBlacklistRow();
if ((outputBlacklist != null) && (outputBlacklist.getMetricGroupId() != null) && (outputBlacklist.getMetricGroupId() >= 0)) {
Set<String> matchingMetricKeysAssociatedWithOutputBlacklistMetricGroup = GlobalVariables.matchingMetricKeysAssociatedWithOutputBlacklistMetricGroup.get(outputBlacklist.getMetricGroupId());
int matchingMetricKeysAssociatedWithOutputBlacklistMetricGroup_Count = 0;
if (matchingMetricKeysAssociatedWithOutputBlacklistMetricGroup != null) matchingMetricKeysAssociatedWithOutputBlacklistMetricGroup_Count = matchingMetricKeysAssociatedWithOutputBlacklistMetricGroup.size();
metricAssociationsLink = "<b>Current Output Blacklist Metric Associations: </b>" +
"<a class=\"iframe cboxElement\" href=\"MetricGroupMetricKeyAssociations?ExcludeNavbar=true&Name=" +
StatsAggHtmlFramework.urlEncode(metricGroupName) + "\">" +
StatsAggHtmlFramework.htmlEncode(Integer.toString(matchingMetricKeysAssociatedWithOutputBlacklistMetricGroup_Count)) + "</a>";
}
htmlBody.append(metricAssociationsLink);
if (!metricAssociationsLink.isEmpty()) htmlBody.append("<br><br>").append("\n");
htmlBody.append(
"<form action=\"OutputBlacklist\" method=\"POST\">\n" +
"<div class=\"form-group\" id=\"MetricGroupName_Lookup\">\n" +
" <label class=\"label_small_margin\">Metric group name</label>\n" +
" <input class=\"typeahead form-control-statsagg\" autocomplete=\"off\" name=\"MetricGroupName\" id=\"MetricGroupName\" ");
if ((metricGroupName != null)) htmlBody.append(" value=\"").append(StatsAggHtmlFramework.htmlEncode(metricGroupName, true)).append("\"");
htmlBody.append(">\n</div>\n");
htmlBody.append("<button type=\"submit\" class=\"btn btn-default statsagg_page_content_font\">Submit</button>\n");
htmlBody.append("</form>\n</div>\n</div>\n");
return htmlBody.toString();
}
private static String getMetricGroupNameAssociatedWithOutputBlacklist() {
OutputBlacklistDao outputBlacklistDao = new OutputBlacklistDao();
List<com.pearson.statsagg.database_objects.output_blacklist.OutputBlacklist> outputBlacklists = outputBlacklistDao.getAllDatabaseObjectsInTable();
if ((outputBlacklists != null) && !outputBlacklists.isEmpty()) {
Integer metricGroupId = null;
for (com.pearson.statsagg.database_objects.output_blacklist.OutputBlacklist outputBlacklist : outputBlacklists) {
if ((outputBlacklist != null) && (outputBlacklist.getMetricGroupId() != null) && outputBlacklist.getMetricGroupId() > -1) {
metricGroupId = outputBlacklist.getMetricGroupId();
break;
}
}
if (metricGroupId != null) {
MetricGroupsDao metricGroupsDao = new MetricGroupsDao();
MetricGroup metricGroup = metricGroupsDao.getMetricGroup(metricGroupId);
if ((metricGroup != null) && (metricGroup.getName() != null)) return metricGroup.getName();
}
}
return null;
}
private static boolean updateOutputBlacklistMetricGroupId(String metricGroupName) {
boolean upsertSuccess = false;
try {
MetricGroup metricGroup = null;
boolean wasMetricGroupNameSpecified = false;
if ((metricGroupName != null) && !metricGroupName.trim().isEmpty()) {
wasMetricGroupNameSpecified = true;
MetricGroupsDao metricGroupsDao = new MetricGroupsDao();
metricGroup = metricGroupsDao.getMetricGroupByName(metricGroupName);
}
com.pearson.statsagg.database_objects.output_blacklist.OutputBlacklist outputBlacklist = OutputBlacklistDao.getSingleOutputBlacklistRow();
if ((metricGroup != null) && (metricGroup.getId() != null)) {
if (outputBlacklist == null) outputBlacklist = new com.pearson.statsagg.database_objects.output_blacklist.OutputBlacklist(-1, metricGroup.getId());
else outputBlacklist.setMetricGroupId(metricGroup.getId());
OutputBlacklistDao outputBlacklistDao = new OutputBlacklistDao();
upsertSuccess = outputBlacklistDao.upsert(outputBlacklist);
}
else if (wasMetricGroupNameSpecified) {
return false;
}
else if (outputBlacklist != null) {
outputBlacklist.setMetricGroupId(null);
OutputBlacklistDao outputBlacklistDao = new OutputBlacklistDao();
upsertSuccess = outputBlacklistDao.upsert(outputBlacklist);
}
else {
outputBlacklist = new com.pearson.statsagg.database_objects.output_blacklist.OutputBlacklist(-1, null);
OutputBlacklistDao outputBlacklistDao = new OutputBlacklistDao();
upsertSuccess = outputBlacklistDao.upsert(outputBlacklist);
}
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
return upsertSuccess;
}
}
|
package com.rampatra.arrays.searching;
public class BinarySearch {
/**
* Searches an element {@param n} in a sorted array {@param a}
* and returns its index in O(log n) time. The Index may not
* correspond to the first occurrence of the element.
*
* @param a sorted array to be searched
* @param n number to be searched in the array
* @return index of {@param n} or {@code -1} if not present
*/
private static int binarySearch(int[] a, int n) {
return binarySearch(a, n, 0, a.length - 1);
}
public static int binarySearch(int[] a, int n, int low, int high) {
if (low <= high) {
int mid = (low + high) / 2;
if (n == a[mid]) {
return mid;
} else if (n < a[mid]) {
return binarySearch(a, n, 0, mid - 1);
} else {
return binarySearch(a, n, mid + 1, high);
}
} else {
return -1;
}
}
/**
* Non-recursive version of binary search.
*
* @param a sorted array to be searched
* @param n number to be searched in the array
* @return index of {@param n} or {@code -1} if not present
*/
private static int binarySearchNonRecursive(int[] a, int n) {
int low = 0, high = a.length, mid;
while (low <= high) {
mid = (low + high) / 2;
if (n == a[mid]) {
return mid;
} else if (n < a[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
/**
* Driver for testing.
*
* @param a
*/
public static void main(String[] a) {
System.out.println(binarySearch(new int[]{0, 2}, 2));
System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 2));
System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 3));
System.out.println(binarySearch(new int[]{0, 2}, 0));
System.out.println(binarySearch(new int[]{0, 1, 2, 2, 2, 3, 3}, 2)); // doesn't return index of first occurrence
System.out.println("
System.out.println(binarySearchNonRecursive(new int[]{0, 2}, 2));
System.out.println(binarySearchNonRecursive(new int[]{0, 1, 2, 3}, 2));
System.out.println(binarySearchNonRecursive(new int[]{0, 1, 2, 3}, 3));
System.out.println(binarySearchNonRecursive(new int[]{0, 2}, 0));
System.out.println(binarySearchNonRecursive(new int[]{0, 1, 2, 2, 2, 3, 3}, 2));
}
}
|
package com.alexaut.kroniax.game.scripts;
import com.alexaut.kroniax.game.Camera;
import com.alexaut.kroniax.game.Player;
import com.alexaut.kroniax.game.level.Level;
public abstract class TimedScript extends Script {
public float mDuration;
public float mElapsedTime;
public TimedScript(float duration) {
mDuration = duration;
mElapsedTime = 0;
}
@Override
public void update(float deltaTime, Level level, Player player, Camera camera) {
float interp = 0;
if (mDuration == 0)
interp = 1;
else if (mElapsedTime + deltaTime <= mDuration) {
interp = deltaTime / mDuration;
} else {
interp = (mDuration - mElapsedTime) / mDuration;
}
mElapsedTime += deltaTime;
updateWithInterp(interp, level, player, camera);
if (mElapsedTime >= mDuration)
stop();
}
@Override
public void reset() {
super.reset();();
mElapsedTime = 0;
}
protected abstract void updateWithInterp(float interp, Level level, Player player, Camera camera);
}
|
package com.royalrangers.controller;
import com.dropbox.core.DbxException;
import com.fasterxml.jackson.annotation.JsonView;
import com.royalrangers.dto.ResponseResult;
import com.royalrangers.dto.user.*;
import com.royalrangers.enums.ImageType;
import com.royalrangers.exception.UserRepositoryException;
import com.royalrangers.model.TempUser;
import com.royalrangers.model.Views;
import com.royalrangers.service.DropboxService;
import com.royalrangers.service.UserService;
import com.royalrangers.utils.ResponseBuilder;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
private final long FILE_MAX_SIZE = 1024*1024;
@Autowired
private UserService userService;
@Autowired
private DropboxService dropboxService;
@JsonView(Views.Profile.class)
@GetMapping
@ApiOperation(value = "Get current user info")
public ResponseResult getAuthenticatedUserDetail() {
String username = userService.getAuthenticatedUserEmail();
log.info("Get details for user " + username);
return ResponseBuilder.success(userService.getUserByEmail(username));
}
@JsonView(Views.Profile.class)
@GetMapping("/{userId}")
@PreAuthorize("hasRole('ADMIN')")
@ApiOperation(value = "Get user info (for admin)")
public ResponseResult getUserDetailById(@PathVariable("userId") Long id) {
try {
log.info("Get details for user id " + id);
return ResponseBuilder.success(userService.getUserById(id));
} catch (UserRepositoryException e){
return ResponseBuilder.fail(e.getMessage());
}
}
@JsonView(Views.Profile.class)
@GetMapping("/temp")
@ApiOperation(value = "Get current temp_user info")
public ResponseResult getAuthenticatedTempUserDetail(){
return ResponseBuilder.success(userService.getTempUser());
}
@JsonView(Views.Profile.class)
@GetMapping("/approve/update/{platoonId}")
@PreAuthorize("hasRole('ADMIN')")
@ApiOperation(value = "Get tempUsers for approve (for platoon admin)")
public ResponseResult getTempUsersToApprove(@PathVariable("platoonId") Long id) {
try {
return ResponseBuilder.success(userService.getTempUsersByPlatoon(id));
} catch (UserRepositoryException e) {
return ResponseBuilder.fail(e.getMessage());
}
}
@JsonView(Views.Profile.class)
@GetMapping("/approve/update")
@PreAuthorize("hasRole('SUPER_ADMIN')")
@ApiOperation(value = "Get tempUsers for approve (for super admin)")
public ResponseResult getTempUserToApprove(){
return ResponseBuilder.success(userService.getTempUsers());
}
@JsonView(Views.Profile.class)
@GetMapping("/approve/registration/{platoonId}")
@PreAuthorize("hasRole('ADMIN')")
@ApiOperation(value = "Get users for approve (for platoon admin)")
public ResponseResult getUserToApprove(@PathVariable("platoonId") Long id) {
try {
return ResponseBuilder.success(userService.getUsersForApprove(id));
} catch (UserRepositoryException e) {
return ResponseBuilder.fail(e.getMessage());
}
}
@JsonView(Views.Profile.class)
@GetMapping("/approve/registration/super")
@PreAuthorize("hasRole('SUPER_ADMIN')")
@ApiOperation(value = "Get users for approve (for super admin)")
public ResponseResult getUsersToApprove(){
return ResponseBuilder.success(userService.getUsersForApproveForSuperAdmin());
}
@PostMapping("/approve/registration/{userId}")
@PreAuthorize("hasAnyRole('ADMIN', 'SUPER_ADMIN')")
@ApiOperation(value = "Approve users after registration")
public ResponseResult approveUsers(@PathVariable("userId") Long id) {
try {
userService.approveUser(id);
return ResponseBuilder.success("User successfully approved.");
} catch (UserRepositoryException e) {
return ResponseBuilder.fail(e.getMessage());
}
}
@PostMapping("/reject/registration/{userId}")
@PreAuthorize("hasAnyRole('ADMIN', 'SUPER_ADMIN')")
@ApiOperation(value = "Reject user after registration (for platoon admin)")
public ResponseResult rejectUser(@PathVariable("userId") Long id) {
try {
userService.rejectUser(id);
return ResponseBuilder.success("User successfully rejected.");
} catch (UserRepositoryException e) {
return ResponseBuilder.fail(e.getMessage());
}
}
@PutMapping("/update/temp")
@ApiOperation(value = "Update user data (for current user)")
public ResponseResult updateTempUser(@RequestBody UserUpdateDto update) {
userService.updateTempUser(update);
log.info("Update temp_user " + userService.getAuthenticatedUser().getEmail());
return ResponseBuilder.success("User %s successfully updated, waiting for approve this update by admin", userService.getAuthenticatedUser().getEmail());
}
@PutMapping("/update/{temp_userId}")
@PreAuthorize("hasRole('ADMIN')")
@ApiOperation(value = "Confirm to update user data from temp_user data(for admin)")
public ResponseResult updateUser(@PathVariable("temp_userId") Long id, @RequestBody UserUpdateDto update) {
TempUser user = userService.getTempUserById(id);
try {
userService.updateUser(id, update);
log.info("Update temp_user " + user.getEmail());
return ResponseBuilder.success("User %s successfully updated", user.getEmail());
} catch (UserRepositoryException e) {
return ResponseBuilder.fail(e.getMessage());
}
}
@PutMapping(value = "/{userId}")
@PreAuthorize("hasRole('ADMIN')")
@ApiOperation(value = "Update user (for admin)")
public ResponseResult updateUserById(@PathVariable("userId") Long id, @RequestBody UserUpdateDto userUpdate) {
try {
userService.updateUserById(id, userUpdate);
log.info("Update user with id %d " + id);
return ResponseBuilder.success("User with id %d successfully updated", String.valueOf(id));
} catch (UserRepositoryException e){
return ResponseBuilder.fail(e.getMessage());
}
}
@PostMapping("/avatar/{file}")
@ApiOperation(value = "Upload and set avatar for current user")
public ResponseResult upload(@PathVariable("file") MultipartFile file) {
if (file.getSize() >= FILE_MAX_SIZE)
return ResponseBuilder.fail("File too large.");
try {
String avatarUrl = dropboxService.imageUpload(file, ImageType.USER_AVATAR);
log.info("Set user avatar public URL: " +avatarUrl);
userService.setUserAvatarUrl(avatarUrl);
return ResponseBuilder.success("avatarUrl", avatarUrl);
} catch (IOException | DbxException e) {
return ResponseBuilder.fail(e.getMessage());
}
}
}
|
package com.deftwun.zombiecopter.systems;
import com.artemis.BaseSystem;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.deftwun.zombiecopter.App;
import com.deftwun.zombiecopter.SpawnZone;
public class SpawnSystem extends BaseSystem {
private Rectangle camRect,
boundsRect = new Rectangle(App.engine.entityBounds),
tmpRect = new Rectangle();
private Vector2 cameraCenter = new Vector2(),
spawnPoint = new Vector2();
private Array<SpawnZone> points = new Array<SpawnZone>();
private Array<SpawnZone> deadPoints = new Array<SpawnZone>();
private final float units = App.engine.PIXELS_PER_METER;
private final int maxEntities = 25;
public void add(SpawnZone point){
points.add(point);
}
@Override
public void processSystem() {
if (App.engine.getEntityCount() > maxEntities) return;
camRect = App.engine.systems.camera.getCameraRect(1/units);
boundsRect.setCenter(camRect.getCenter(cameraCenter));
for (SpawnZone z : points){
z.time += world.delta;
//Spawn new entity
if (z.time > z.delay && z.count < z.maximum){
boolean withinBounds = Intersector.intersectRectangles(z.rectangle,boundsRect,tmpRect);
boolean outsideCamera = !camRect.overlaps(z.rectangle);
z.time = 0;
if (withinBounds && outsideCamera){
z.count++;
spawnPoint.x = MathUtils.random(tmpRect.x,tmpRect.x+tmpRect.width);
spawnPoint.y = MathUtils.random(tmpRect.y,tmpRect.y+tmpRect.height);
App.engine.factory.build(z.type,spawnPoint);
}
}
//Retire spawn point if it has reached max spawn count
if (z.maximum > 0 && z.count > z.maximum){
deadPoints.add(z);
}
}
//Remove the retired spawn points
for (SpawnZone p : deadPoints){
points.removeValue(p, true);
}
deadPoints.clear();
}
public Array<SpawnZone> getZones() {
return points;
}
}
|
package com.splicemachine.concurrent;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;
/**
* Convenient executor factory methods.
*
* On daemon property: For the splicemachine main product where we run as part of of HBase we probably want
* most thread pools to consist of daemons that do not not prevent HBase region server JVMs from shutting down.
* An thread pool that strictly must finish any in progress work before the jvm exists would be an exception to this
* rule. In this later case make the threads non-daemon and make sure ExecutorService.shutdown() is explicitly
* invoked as part of the splice shutdown process.
*/
public class MoreExecutors {
private MoreExecutors() {
}
/**
* Single thread ExecutorService with named threads.
*
* @param nameFormat name the thread. It's helpful to find in thread dumps, profiler, etc,
* if we name our threads "splice-[something]".
* @param isDaemon set the daemon property of the thread. <b>NOTE</b>: if setting your thread
* to non-daemon (isDaemon arg is false), you're taking over the responsibility
* of cleaning up any thread resources and shutting down your thread pool.
*/
public static ExecutorService namedSingleThreadExecutor(String nameFormat, boolean isDaemon) {
ThreadFactory factory = new ThreadFactoryBuilder()
.setNameFormat(nameFormat)
.setDaemon(isDaemon)
.build();
return Executors.newSingleThreadExecutor(factory);
}
/**
* Single thread ScheduledExecutorService with named threads. Thread daemon property is set
* to true.
* <p/>
* Returns an instance that will log any exception not caught by the scheduled task. Like
* ScheduledThreadPoolExecutor, returned instance stops scheduled task on exception.
*
* @param nameFormat name the thread. It's helpful to find in thread dumps, profiler, etc,
* if we name our threads "splice-[something]".
*/
public static ScheduledExecutorService namedSingleThreadScheduledExecutor(String nameFormat) {
ThreadFactory factory = new ThreadFactoryBuilder()
.setNameFormat(nameFormat)
.setDaemon(true)
.build();
return new LoggingScheduledThreadPoolExecutor(1, factory);
}
/**
* Factory for general purpose ThreadPoolExecutor.
*
* @param coreWorkers argument passed to {@link ThreadPoolExecutor}
* @param maxWorkers argument passed to {@link ThreadPoolExecutor}
* @param nameFormat name the thread. It's helpful to find in thread dumps, profiler, etc,
* if we name our threads "splice-[something]".
* @param keepAliveSeconds argument passed to {@link ThreadPoolExecutor}
* @param isDaemon set the daemon property of the thread. <b>NOTE</b>: if setting your thread
* to non-daemon (isDaemon arg is false), you're taking over the responsibility
* of cleaning up any thread resources and shutting down your thread pool.
*/
public static ThreadPoolExecutor namedThreadPool(int coreWorkers, int maxWorkers,
String nameFormat,
long keepAliveSeconds,
boolean isDaemon) {
ThreadFactory factory = new ThreadFactoryBuilder()
.setNameFormat(nameFormat)
.setDaemon(isDaemon)
.build();
return new ThreadPoolExecutor(coreWorkers, maxWorkers, keepAliveSeconds,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), factory);
}
}
|
// OOO GWT Utils - utilities for creating GWT applications
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.gwt.util;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasChangeHandlers;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.dom.client.HasKeyDownHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.ButtonBase;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Widget;
import com.threerings.gwt.ui.EnterClickAdapter;
import com.threerings.gwt.ui.SmartTable;
/**
* Provides a click handler that will first request an input string from the user using a popup
* and then perform a service call with the input string. The input widget is provided on
* construction and the normally anonymous subclass supplies the service handling.
*
* <p>NOTE: the input popup replaces the confirmation popup.</p>
*/
public abstract class InputClickCallback<T, W extends Widget & HasText & HasKeyDownHandlers & HasChangeHandlers>
extends ClickCallback<T>
{
/**
* Creates a new click handler for the given trigger. Upon clicking, text input will be
* requested from the user by popping up a confirmation with the given widget.
*/
public InputClickCallback (HasClickHandlers trigger, W textInputWidget)
{
super(trigger);
setConfirmText("");
_widget = textInputWidget;
}
/**
* Sets the text to be shown above the input explaining what the user should do. Note that this
* just calls {@link #setConfirmText(String)}, but is included here for clarity.
*/
InputClickCallback<T, W> setPromptText(String prompt)
{
setConfirmText(prompt);
return this;
}
/**
* Sets the html to be shown above the input explaining what the user should do. Note that this
* just calls {@link #setConfirmHTML(String)}, but is included here for clarity.
*/
InputClickCallback<T, W> setPromptHTML(String promptHTML)
{
setConfirmHTML(promptHTML);
return this;
}
@Override
protected boolean callService ()
{
return callService(_widget.getText());
}
/**
* Makes the asynchronous service call, returning true only if the call was actually made.
* @see #callService()
*/
abstract protected boolean callService (String input);
@Override
protected void onAborted ()
{
super.onAborted();
removeHandlerReg();
}
@Override
protected void onConfirmed ()
{
super.onConfirmed();
removeHandlerReg();
}
/**
* Removes the change handler registration that was added for the confirmation popup.
*/
protected void removeHandlerReg ()
{
_changeHandlerReg.removeHandler();
_changeHandlerReg = null;
}
@Override
protected int addConfirmPopupMessage (SmartTable contents, int row)
{
row = super.addConfirmPopupMessage(contents, row);
contents.setWidget(row, 0, _widget);
contents.getFlexCellFormatter().setColSpan(row, 0, 2);
row++;
contents.setWidget(row, 0, _widget);
contents.getFlexCellFormatter().setColSpan(row, 0, 2);
contents.getFlexCellFormatter().setWidth(row, 0, "100%");
row++;
return row;
}
@Override
protected ButtonBase createConfirmButton (String text, ClickHandler onClick)
{
final ButtonBase button = super.createConfirmButton(text, onClick);
EnterClickAdapter.bind(_widget, onClick);
_changeHandlerReg = _widget.addChangeHandler(new ChangeHandler() {
@Override
public void onChange (ChangeEvent event)
{
String text = _widget.getText();
button.setEnabled(text != null && text.length() > 0);
}
});
return button;
}
protected W _widget;
protected HandlerRegistration _changeHandlerReg;
}
|
package com.toomasr.sgf4j.parser;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Computes the visual depth for the game nodes. The visual
* depth designates as how deep in the tree should the line be
* shown if a GUI is being used. I should move this helper to
* sgf4j-gui project but haven't done it yet.
*/
public class VisualDepthHelper {
private List<List<Integer>> depthMatrix;
/*
* We'll start iterating over the nodes from last to first and
* calculate how "deep" should they be displayed in the tree. The
* mainline is on depth 0.
*
* @param variationDepth depth of the variation for the first level child
* of the line of play.
*/
public void calculateVisualDepth(GameNode lastNode, int variationDepth) {
// if there are no moves, for example we are just
// looking at a problem then we can skip calculating
// the visual depth
if (lastNode == null) {
return;
}
// a XyZ matrix that we'll fill with 1s and 0s based
// on whether a square is occupied or not
List<List<Integer>> depthMatrix = new ArrayList<>();
initializeMainLine(lastNode, depthMatrix);
GameNode activeNode = lastNode;
do {
if (activeNode.hasChildren()) {
for (Iterator<GameNode> ite = activeNode.getChildren().iterator(); ite.hasNext();) {
// the do/while iterates over the main line that has depth 0
// all other branches have to be at least depth 1
variationDepth = variationDepth + 1;
calculateVisualDepthFor(ite.next(), depthMatrix, 1, variationDepth);
}
}
}
while ((activeNode = activeNode.getPrevNode()) != null);
this.depthMatrix = depthMatrix;
}
private void calculateVisualDepthFor(GameNode node, List<List<Integer>> depthMatrix, int minDepth, int variationDepth) {
int depth = findVisualDepthForNode(node, depthMatrix, minDepth, variationDepth);
GameNode lastNodeInLine = setVisualDepthForLine(node, depth);
GameNode activeNode = lastNodeInLine;
do {
if (activeNode.hasChildren()) {
for (Iterator<GameNode> ite = activeNode.getChildren().iterator(); ite.hasNext();) {
calculateVisualDepthFor(ite.next(), depthMatrix, depth + 1, variationDepth);
}
}
if (activeNode.equals(node)) {
break;
}
}
while ((activeNode = activeNode.getPrevNode()) != null);
}
private void initializeMainLine(GameNode lastNode, List<List<Integer>> depthMatrix) {
// initialize the first line with 0s
List<Integer> firstLine = new ArrayList<>();
for (int i = 0; i <= lastNode.getMoveNo(); i++) {
firstLine.add(i, 0);
}
depthMatrix.add(0, firstLine);
// initialize the first line actual moves with 1s
GameNode node = lastNode;
do {
if (node.isMove()) {
firstLine.set(node.getMoveNo(), 1);
// main line will be at depth 0
node.setVisualDepth(0);
}
}
while ((node = node.getPrevNode()) != null);
}
protected GameNode setVisualDepthForLine(GameNode child, int depth) {
GameNode node = child;
GameNode rtrn = child;
do {
node.setVisualDepth(depth);
rtrn = node;
}
while ((node = node.getNextNode()) != null);
return rtrn;
}
protected int findVisualDepthForNode(GameNode node, List<List<Integer>> depthMatrix, int minDepth, int variationDepth) {
int length = findLengthOfLine(node);
int depthDelta = minDepth;
do {
// init the matrix at this depth if not yet done
if (depthMatrix.size() <= depthDelta) {
for (int i = depthMatrix.size(); i <= depthDelta; i++) {
depthMatrix.add(i, new ArrayList<Integer>());
}
}
boolean available = isAvailableForLineOfPlay(node, length, depthMatrix, depthDelta, variationDepth);
if (available) {
bookForLineOfPlay(node, length, depthMatrix, depthDelta, variationDepth);
break;
}
depthDelta++;
}
while (true);
return depthDelta;
}
/*
* Iterates over the depthMatrix and marks all the needed cells as booked (the number 1).
*/
protected void bookForLineOfPlay(GameNode node, int length, List<List<Integer>> depthMatrix, int listIndex, int variationDepth) {
List<Integer> levelList = depthMatrix.get(listIndex);
int start = 0;
if (node.getMoveNo() > 0) {
start = node.getMoveNo() - 1;
}
// book the line of play (horizontal line)
for (int i = start; i < (node.getMoveNo() + length); i++) {
levelList.set(i, 1);
}
// book the "glue" pieces (vertical lines for the connection lines)
for (int i = variationDepth; i < listIndex; i++) {
List<Integer> tmpLevelList = depthMatrix.get(i);
expandListIfNeeded(tmpLevelList, start);
tmpLevelList.set(start, 1);
}
}
private void expandListIfNeeded(List<Integer> tmpLevelList, int upperBound) {
if (tmpLevelList.size() > upperBound) {
return;
}
for (int i = tmpLevelList.size(); i <= upperBound; i++) {
tmpLevelList.add(i, 0);
}
}
/*
* Iterates over the depthMatrix and checks whether we can put the variation on this particular line.
*
* Each variation needs room for the actual moves and also one spot for the glue piece (the line designating
* the parent move). If the variation is quite deep then it will need a glue code piece for each row.
*
* This method will analyse the matrix for the availability for these. If found they can be "booked"
* with the bookForLineOfPlay(). If not found we can just look a level deeper.
*/
protected boolean isAvailableForLineOfPlay(GameNode node, int length, List<List<Integer>> depthMatrix, int listIndex, int variationDepth) {
// if the marker row is not initialized yet then lets fill with 0s
List<Integer> levelList = depthMatrix.get(listIndex);
if (levelList.size() <= node.getMoveNo()) {
for (int i = levelList.size(); i <= node.getMoveNo() + length; i++) {
levelList.add(i, 0);
}
}
// we'll start the search one move earlier as we also
// want to show to "glue stone"
Integer marker = 0;
if (node.getMoveNo() > 1) {
marker = levelList.get(node.getMoveNo() - 1);
}
// we'll look at the array and make sure nobody has booked anything yet
for (int i = marker; i < node.getMoveNo() + length; i++) {
Integer localMarker = levelList.get(i);
if (localMarker == 1) {
return false;
}
}
// now lets look at whether there is room for the glue piece
// the glue piece should run up to the depth of the
// variation it came from
for (int i = variationDepth; i < listIndex; i++) {
List<Integer> tmpLevelList = depthMatrix.get(i);
if (tmpLevelList.get(marker) == 1)
return false;
}
return true;
}
/*
* Helper to print out the matrix for debugging purposes.
*/
public void printDepthMatrix() {
for (Iterator<List<Integer>> ite = depthMatrix.iterator(); ite.hasNext();) {
List<Integer> list = ite.next();
System.out.println(list);
}
}
/**
* Returns the length of this game line. This is the length with
* no branch taken into account except the main line for this branch.
*
* @param node
* @return no of moves in the main line from this node
*/
protected int findLengthOfLine(final GameNode node) {
GameNode tmpNode = node;
int i = 0;
do {
i++;
}
while ((tmpNode = tmpNode.getNextNode()) != null);
return i;
}
}
|
package com.wizzardo.http.framework;
import com.wizzardo.epoll.IOThread;
import com.wizzardo.epoll.SslConfig;
import com.wizzardo.http.filter.AuthFilter;
import com.wizzardo.http.filter.BasicAuthFilter;
import com.wizzardo.http.filter.TokenFilter;
import com.wizzardo.http.request.Request;
import com.wizzardo.http.response.RangeResponseHelper;
import com.wizzardo.http.response.Response;
import com.wizzardo.tools.collections.CollectionTools;
import com.wizzardo.tools.collections.flow.Flow;
import com.wizzardo.tools.evaluation.Config;
import com.wizzardo.http.*;
import com.wizzardo.http.framework.di.DependencyFactory;
import com.wizzardo.http.framework.di.SingletonDependency;
import com.wizzardo.http.framework.message.MessageBundle;
import com.wizzardo.http.framework.message.MessageSource;
import com.wizzardo.http.framework.template.*;
import com.wizzardo.http.mapping.UrlMapping;
import com.wizzardo.tools.evaluation.EvalTools;
import com.wizzardo.tools.misc.Consumer;
import com.wizzardo.tools.misc.TextTools;
import com.wizzardo.tools.misc.Unchecked;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.jar.Manifest;
public class WebApplication extends HttpServer<HttpConnection> {
protected Environment environment;
protected Config config;
protected Map<String, String> cliArgs = Collections.emptyMap();
protected ResourceTools resourcesTools;
protected Consumer<WebApplication> onSetup;
protected Consumer<WebApplication> onLoadConfiguration;
protected Set<String> profiles;
public WebApplication() {
}
public WebApplication(String[] args) {
Map<String, String> map = parseCliArgs(args);
processArgs(map::get);
cliArgs = map;
}
public WebApplication setEnvironment(Environment environment) {
checkIfStarted();
this.environment = environment;
return this;
}
public Environment getEnvironment() {
return environment;
}
public Set<String> getProfiles() {
return profiles;
}
public WebApplication addProfile(String profile) {
checkIfStarted();
profiles.add(profile);
return this;
}
public WebApplication onSetup(Consumer<WebApplication> onSetup) {
this.onSetup = onSetup;
return this;
}
public WebApplication onLoadConfiguration(Consumer<WebApplication> onLoadConfiguration) {
this.onLoadConfiguration = onLoadConfiguration;
return this;
}
protected void onStart() {
resourcesTools = createResourceTools();
DependencyFactory.get().register(ResourceTools.class, new SingletonDependency<>(resourcesTools));
DependencyFactory.get().register(UrlMapping.class, new SingletonDependency<>(getUrlMapping()));
DependencyFactory.get().register(ControllerUrlMapping.class, new SingletonDependency<>(getUrlMapping()));
MessageBundle bundle = initMessageSource();
DependencyFactory.get().register(MessageSource.class, new SingletonDependency<>(bundle));
DependencyFactory.get().register(MessageBundle.class, new SingletonDependency<>(bundle));
loadConfig("Config.groovy");
processListener(onLoadConfiguration);
loadEnvironmentVariables(config);
loadSystemProperties(config);
cliArgs.forEach((key, value) -> putInto(config, key, value));
readProfiles(config);
setupApplication();
processListener(onSetup);
List<Class> classes = resourcesTools.getClasses();
DependencyFactory.get().setClasses(classes);
TagLib.findTags(classes);
DependencyFactory.get().register(DecoratorLib.class, new SingletonDependency<>(new DecoratorLib(classes)));
super.onStart();
System.out.println("application has started");
System.out.println("environment: " + environment);
System.out.println("profiles: " + profiles);
}
protected void readProfiles(Config config) {
if (config == null || config.isEmpty())
return;
Config environments = (Config) config.remove("environments");
if (environments != null) {
Config env = environments.config(environment.shortName);
if (env != null)
config.merge(env);
env = environments.config(environment.name().toLowerCase());
if (env != null)
config.merge(env);
}
Config profiles = (Config) config.remove("profiles");
if (profiles == null || profiles.isEmpty())
return;
for (String profile : this.profiles) {
Config subConfig = profiles.config(profile);
readProfiles(subConfig);
config.merge(subConfig);
}
if (this.config != config)
this.config.merge(config);
}
protected void setupApplication() {
ServerConfiguration server = DependencyFactory.get(ServerConfiguration.class);
super.setHostname(server.hostname);
super.setPort(server.port);
super.setDebugOutput(server.debugOutput);
super.setSessionTimeout(server.session.ttl);
setContext(server.context);
int workers = server.ioWorkersCount;
if (workers > 0)
super.setIoThreadsCount(workers);
workers = server.workersCount;
if (workers > 0)
super.setWorkersCount(workers);
long ttl = server.ttl;
if (ttl > 0)
super.setTTL(ttl);
loadSslConfiguration(server.ssl);
loadBasicAuthConfiguration(server.basicAuth);
loadResourcesConfiguration(server.resources);
}
protected void loadResourcesConfiguration(ServerConfiguration.Resources resources) {
if (resources == null)
return;
if (TextTools.isBlank(resources.mapping))
throw new IllegalArgumentException("server.resources.mapping cannot be null or empty");
String resourcesPath = resources.path;
File staticResources = resourcesTools.getResourceFile(resourcesPath);
if (staticResources != null && staticResources.exists()) {
FileTreeHandler<FileTreeHandler.HandlerContext> handler = new FileTreeHandler<>(staticResources, resources.mapping, "resources")
.setShowFolder(false)
.setRangeResponseHelper(new RangeResponseHelper(resources.cache));
DependencyFactory.get().register(FileTreeHandler.class, new SingletonDependency<>(handler));
|
package com.yiji.falcon.agent.falcon;
import com.yiji.falcon.agent.config.AgentConfiguration;
import com.yiji.falcon.agent.util.HttpUtil;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.HttpResult;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
/*
* :
* guqiu@yiji.com 2016-06-22 17:48
*/
/**
* @author guqiu@yiji.com
*/
public class ReportMetrics {
private static final Logger log = LoggerFactory.getLogger(ReportMetrics.class);
/**
* falcon
* @param falconReportObjectList
*/
public static void push(Collection<FalconReportObject> falconReportObjectList){
if(falconReportObjectList != null){
JSONArray jsonArray = new JSONArray();
for (FalconReportObject falconReportObject : falconReportObjectList) {
if(!isValidTag(falconReportObject)){
log.error("tag,metrics:{}",falconReportObject.toString());
continue;
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("endpoint",falconReportObject.getEndpoint());
jsonObject.put("metric",falconReportObject.getMetric());
jsonObject.put("timestamp",falconReportObject.getTimestamp());
jsonObject.put("step",falconReportObject.getStep());
jsonObject.put("value",falconReportObject.getValue());
jsonObject.put("counterType",falconReportObject.getCounterType());
jsonObject.put("tags",falconReportObject.getTags() == null ? "" : falconReportObject.getTags());
jsonArray.put(jsonObject);
}
log.debug("Falcon : [{}]",jsonArray.toString());
HttpResult result;
try {
result = HttpUtil.postJSON(AgentConfiguration.INSTANCE.getAgentPushUrl(),jsonArray.toString());
} catch (Exception e) {
log.error("metrics push,Falcon",e);
return;
}
log.info("push: {}" , result);
}else {
log.info("pushnull");
}
}
/**
* falcon
* @param falconReportObject
*/
public static void push(FalconReportObject falconReportObject){
if(!isValidTag(falconReportObject)){
log.error("tag,metrics:{}",falconReportObject.toString());
return;
}
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("endpoint",falconReportObject.getEndpoint());
jsonObject.put("metric",falconReportObject.getMetric());
jsonObject.put("timestamp",falconReportObject.getTimestamp());
jsonObject.put("step",falconReportObject.getStep());
jsonObject.put("value",falconReportObject.getValue());
jsonObject.put("counterType",falconReportObject.getCounterType());
jsonObject.put("tags",falconReportObject.getTags() == null ? "" : falconReportObject.getTags());
jsonArray.put(jsonObject);
log.debug("Falcon : [{}]",jsonArray.toString());
HttpResult result;
try {
result = HttpUtil.postJSON(AgentConfiguration.INSTANCE.getAgentPushUrl(),jsonArray.toString());
} catch (Exception e) {
log.error("metrics push,Falcon",e);
return;
}
log.info("push: {}" , result);
}
/**
* tag
* @param falconReportObject
* @return
*/
private static boolean isValidTag(FalconReportObject falconReportObject){
return falconReportObject != null && !StringUtils.isEmpty(falconReportObject.getTags());
}
}
|
package de.ehex.foss.rfcs.rfc2119;
import static java.util.Objects.nonNull;
public enum RequirementLevel {
MUST("MUST", "This word, or the terms \"REQUIRED\" or \"SHALL\", mean that the definition is an absolute requirement of the specification."),
REQUIRED("REQUIRED", MUST),
SHALL("SHALL", MUST),
MUST_NOT("MUST NOT", "This phrase, or the phrase \"SHALL NOT\", mean that the definition is an absolute prohibition of the specification."),
SHALL_NOT("SHALL NOT", MUST_NOT),
SHOULD("SHOULD", "This word, or the adjective \"RECOMMENDED\", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course."),
RECOMMENDED("RECOMMENDED", SHOULD),
SHOULD_NOT("SHOULD NOT", "This phrase, or the phrase \"NOT RECOMMENDED\" mean that there may exist valid reasons in particular circumstances when the particular behavior is acceptable or even useful, but the full implications should be understood and the case carefully weighed before implementing any behavior described with this label."),
NOT_RECOMMENDED("NOT RECOMMENDED", SHOULD_NOT),
MAY("MAY", "This word, or the adjective \"OPTIONAL\", mean that an item is truly optional. One vendor may choose to include the item because a particular marketplace requires it or because the vendor feels that it enhances the product while another vendor may omit the same item. An implementation which does not include a particular option MUST be prepared to interoperate with another implementation which does include the option, though perhaps with reduced functionality. In the same vein an implementation which does include a particular option MUST be prepared to interoperate with another implementation which does not include the option (except, of course, for the feature the option provides.)"),
OPTIONAL("OPTIONAL", MAY);
private RequirementLevel(final String phrase, final String definition) {
assert nonNull(phrase) : "There must be a non-null phrase!";
assert !phrase.isEmpty() : "There must be a non-empty phrase!";
assert nonNull(definition) : "There must be a non-null definition text!";
assert !definition.isEmpty() : "There must be a non-empty definition text!";
this.phrase = phrase;
this.definition = definition;
this.aliasOf = null;
}
private RequirementLevel(final String phrase, final RequirementLevel aliasOf) {
assert nonNull(phrase) : "There must be a non-null phrase!";
assert !phrase.isEmpty() : "There must be a non-empty phrase!";
assert nonNull(aliasOf) : "There must be a non-null alias reference!";
assert !phrase.equals(aliasOf.phrase) : "The phrase must differ from the alias' phrase!";
this.phrase = phrase;
this.definition = null;
this.aliasOf = aliasOf;
}
private final String phrase;
/**
* Returns the {@linkplain #phrase} of {@code this} requirement level.
*
* @return the phrase of {@code this} requirement level
*/
@Override
public String toString() {
assert nonNull(this.phrase) : "Class invariant violation!";
return this.phrase;
}
private final String definition;
/**
* Returns the definition text of this requirement level.
*
* @return the definition text of this requirement level
*/
public String getDefinition() {
final RequirementLevel proper = this.getProperRequirementLevel();
assert nonNull(proper) : "Class invariant violation!";
assert nonNull(proper.definition) : "Class invariant violation!";
return proper.definition;
}
private final RequirementLevel aliasOf;
/**
* Returns {@code true} if and only if {@code this} requirement level is an alias of another proper requirement
* level.
*
* @return {@code true} iff {@code this} requirement level is an alias of another proper requirement level
*/
public final boolean isAlias() {
return nonNull(this.aliasOf);
}
/**
* Returns the proper requirement level of {@code this} requirement level. For example, {@link #REQUIRED} and
* {@link #SHALL} aliases {@link #MUST}.
*
* @return the proper requirement level of {@code this} requirement level
*/
public final RequirementLevel getProperRequirementLevel() {
return nonNull(this.aliasOf) ? this.aliasOf : this;
}
}
|
package de.upb.fsmi.fsdroid.fragments;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.SyncInfo;
import android.content.SyncStatusObserver;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.res.StringRes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.upb.fsmi.fsdroid.BuildConfig;
import de.upb.fsmi.fsdroid.R;
import de.upb.fsmi.fsdroid.SingleNews_;
import de.upb.fsmi.fsdroid.sync.AccountCreator;
import de.upb.fsmi.fsdroid.sync.NewsItemContract;
@EFragment(R.layout.fragment_news)
@OptionsMenu(R.menu.menu_main)
public class NewsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>, SyncStatusObserver {
private static final int NEWS_LOADER = 0x01;
private SimpleCursorAdapter adapter;
private final Logger LOGGER = LoggerFactory.getLogger(NewsFragment.TAG);
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
if (BuildConfig.DEBUG) LOGGER.debug("");
String[] projection = NewsItemContract.NEWS_LIST_PROJECTION;
CursorLoader cursorLoader = new CursorLoader(getActivity(),
NewsItemContract.NEWS_URI, projection, null, null, null);
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
adapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
adapter.swapCursor(null);
}
private static final String TAG = NewsFragment.class.getSimpleName();
@Bean
AccountCreator mAccountCreator;
@StringRes
String news;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) LOGGER.debug("onCreate(..)");
super.onCreate(savedInstanceState);
String[] uiBindFrom = NewsItemContract.NEWS_LIST_PROJECTION;
int[] uiBindTo = {R.id.newsHeadline, R.id.newsText};
getLoaderManager().initLoader(NEWS_LOADER, null, this);
adapter = new SimpleCursorAdapter(
getActivity().getApplicationContext(), R.layout.card_news_item,
null, uiBindFrom, uiBindTo, 0);
setListAdapter(adapter);
if (BuildConfig.DEBUG) LOGGER.debug("onCreate(..) done");
}
@ItemClick(android.R.id.list)
void click(int position) {
if (BuildConfig.DEBUG) LOGGER.debug("click(..)");
long _id = adapter.getItemId(position);
SingleNews_.intent(getActivity()).news_id(_id).start();
if (BuildConfig.DEBUG) LOGGER.debug("click(..) done");
}
@OptionsItem(R.id.ab_refresh)
void refresh() {
if (BuildConfig.DEBUG) LOGGER.debug("refresh()");
Bundle settingsBundle = new Bundle();
settingsBundle.putBoolean(
ContentResolver.SYNC_EXTRAS_MANUAL, true);
settingsBundle.putBoolean(
ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
ContentResolver.requestSync(mAccountCreator.getAccountRegisterAccount(), AccountCreator.getAuthority(), settingsBundle);
if (BuildConfig.DEBUG) LOGGER.debug("refresh() done");
}
@Override
public void onResume() {
if (BuildConfig.DEBUG) LOGGER.debug("onResume()");
super.onResume();
int mask = ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE | ContentResolver.SYNC_OBSERVER_TYPE_PENDING | ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS;
ContentResolver.addStatusChangeListener(mask, this);
if (BuildConfig.DEBUG) LOGGER.debug("onResume() done");
}
@Override
public void onStatusChanged(int status) {
if (BuildConfig.DEBUG) LOGGER.debug("onStatusChanged({})", status);
boolean myAccountSyncing = getSyncStatus();
updateSyncStatus(myAccountSyncing);
if (BuildConfig.DEBUG) LOGGER.debug("onStatusChanged({}) done", status);
}
private boolean getSyncStatus() {
if (BuildConfig.DEBUG) LOGGER.debug("getSyncStatus()");
final String account = AccountCreator.getAccountName();
final String authority = AccountCreator.getAuthority();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
boolean result = isSyncActiveHoneycomb(account, authority);
if (BuildConfig.DEBUG) LOGGER.debug("getSyncStatus() -> {}", result);
return result;
} else {
SyncInfo currentSync = ContentResolver.getCurrentSync();
boolean result = currentSync != null && currentSync.account.equals(account) &&
currentSync.authority.equals(authority);
if (BuildConfig.DEBUG) LOGGER.debug("getSyncStatus() -> {}", result);
return result;
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private boolean isSyncActiveHoneycomb(String accountName, String authority) {
if (BuildConfig.DEBUG) LOGGER.debug("isSyncActiveHoneycomb({},{})", accountName, authority);
for (SyncInfo syncInfo : ContentResolver.getCurrentSyncs()) {
if (syncInfo.account.name.equals(accountName) &&
syncInfo.authority.equals(authority)) {
if (BuildConfig.DEBUG)
LOGGER.debug("isSyncActiveHoneycomb({},{}) done", accountName, authority);
return true;
}
}
if (BuildConfig.DEBUG)
LOGGER.debug("isSyncActiveHoneycomb({},{}) done", accountName, authority);
return false;
}
@UiThread
void updateSyncStatus(boolean myAccountSyncing) {
if (BuildConfig.DEBUG) LOGGER.debug("updateSyncStatus({})", myAccountSyncing);
ActionBarActivity activity = (ActionBarActivity) getActivity();
if (activity == null)
return;
activity.setProgressBarVisibility(myAccountSyncing);
activity.setProgressBarIndeterminateVisibility(myAccountSyncing);
if (BuildConfig.DEBUG) LOGGER.debug("updateSyncStatus({}) done", myAccountSyncing);
}
}
|
package edu.harvard.iq.dataverse;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.hibernate.validator.constraints.NotBlank;
/**
*
* @author xyang
*/
@ViewScoped
@Named("DataverseUserPage")
public class DataverseUserPage implements java.io.Serializable {
public enum EditMode {CREATE, INFO, EDIT, CHANGE, FORGOT};
@Inject DataverseSession session;
@Inject DataverseServiceBean dataverseService;
@Inject UserNotificationServiceBean userNotificationService;
@Inject DatasetServiceBean datasetService;
@Inject PermissionServiceBean permissionService;
@EJB
DataverseUserServiceBean dataverseUserService;
private DataverseUser dataverseUser;
private EditMode editMode;
@NotBlank(message = "Please enter a password for your account.")
private String inputPassword;
@NotBlank(message = "Please enter a password for your account.")
private String currentPassword;
private Long dataverseId;
private String permissionType;
private List dataIdList;
public DataverseUser getDataverseUser() {
if (dataverseUser == null) {
dataverseUser = new DataverseUser();
}
return dataverseUser;
}
public void setDataverseUser(DataverseUser dataverseUser) {
this.dataverseUser = dataverseUser;
}
public EditMode getEditMode() {
return editMode;
}
public void setEditMode(EditMode editMode) {
this.editMode = editMode;
}
public String getInputPassword() {
return inputPassword;
}
public void setInputPassword(String inputPassword) {
this.inputPassword = inputPassword;
}
public String getCurrentPassword() {
return currentPassword;
}
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
public Long getDataverseId() {
if (dataverseId == null) {
dataverseId = dataverseService.findRootDataverse().getId();
}
return dataverseId;
}
public void setDataverseId(Long dataverseId) {
this.dataverseId = dataverseId;
}
public String getPermissionType() {
return permissionType;
}
public void setPermissionType(String permissionType) {
this.permissionType = permissionType;
}
public List getDataIdList() {
return dataIdList;
}
public void setDataIdList(List dataIdList) {
this.dataIdList = dataIdList;
}
public List getNotifications() {
List notificationsList = userNotificationService.findByUser(dataverseUser.getId());
return notificationsList;
}
public void init() {
if (dataverseUser == null) {
dataverseUser = (session.getUser().isGuest() ? new DataverseUser() : session.getUser());
}
permissionType = "writeAccess";
dataIdList = new ArrayList();
}
public void edit(ActionEvent e) {
editMode = EditMode.EDIT;
}
public void create(ActionEvent e) {
editMode = EditMode.CREATE;
}
public void changePassword(ActionEvent e) {
editMode = EditMode.CHANGE;
}
public void forgotPassword(ActionEvent e) {
editMode = EditMode.FORGOT;
}
public void validateUserName(FacesContext context, UIComponent toValidate, Object value) {
String userName = (String) value;
boolean userNameFound = false;
DataverseUser user = dataverseUserService.findByUserName(userName);
if (editMode == EditMode.CREATE) {
if (user!=null) {
userNameFound = true;
}
} else {
if (user!=null && !user.getId().equals(dataverseUser.getId())) {
userNameFound = true;
}
}
if (userNameFound) {
((UIInput)toValidate).setValid(false);
FacesMessage message = new FacesMessage("This Username is already taken.");
context.addMessage(toValidate.getClientId(context), message);
}
}
public void validateUserNameEmail(FacesContext context, UIComponent toValidate, Object value) {
String userName = (String) value;
boolean userNameFound = false;
DataverseUser user = dataverseUserService.findByUserName(userName);
if (user!=null) {
userNameFound = true;
} else {
DataverseUser user2 = dataverseUserService.findByEmail(userName);
if (user2!=null) {
userNameFound = true;
}
}
if (!userNameFound) {
((UIInput)toValidate).setValid(false);
FacesMessage message = new FacesMessage("Username or Email is incorrect.");
context.addMessage(toValidate.getClientId(context), message);
}
}
public void validatePassword(FacesContext context, UIComponent toValidate, Object value) {
String password = (String) value;
String encryptedPassword = PasswordEncryption.getInstance().encrypt(password);
if (!encryptedPassword.equals(dataverseUser.getEncryptedPassword())) {
((UIInput)toValidate).setValid(false);
FacesMessage message = new FacesMessage("Password is incorrect.");
context.addMessage(toValidate.getClientId(context), message);
}
}
public void updatePassword(String userName){
String plainTextPassword = PasswordEncryption.generateRandomPassword();
DataverseUser user = dataverseUserService.findByUserName(userName);
if (user==null) {
user = dataverseUserService.findByEmail(userName);
}
user.setEncryptedPassword(PasswordEncryption.getInstance().encrypt(plainTextPassword));
dataverseUserService.save(user);
}
public String save() {
if (editMode == EditMode.CREATE|| editMode == EditMode.CHANGE) {
if (inputPassword!=null) {
dataverseUser.setEncryptedPassword(dataverseUserService.encryptPassword(inputPassword));
}
}
dataverseUser = dataverseUserService.save(dataverseUser);
if (editMode == EditMode.CREATE) {
session.setUser(dataverseUser);
return "/dataverse.xhtml?faces-redirect=true;";
}
editMode = EditMode.INFO;
return null;
}
public String cancel() {
if (editMode == EditMode.CREATE) {
return "/dataverse.xhtml?faces-redirect=true;";
}
editMode = EditMode.INFO;
return null;
}
public void submit(ActionEvent e) {
updatePassword(dataverseUser.getUserName());
editMode = EditMode.INFO;
}
}
|
package eu.over9000.skadi.ui.cells;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import eu.over9000.skadi.model.Channel;
import eu.over9000.skadi.ui.ChannelGrid;
import eu.over9000.skadi.ui.MainWindow;
import javafx.beans.binding.Bindings;
import javafx.beans.value.WeakChangeListener;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import org.controlsfx.control.GridCell;
public class ChannelGridCell extends GridCell<Channel> {
public static final String GRID_BOX = "grid-box";
private final Label name;
private final Label title;
private final Label viewer;
private final Label game;
private final ImageView imageView;
private final VBox vBox;
private final ChannelGrid grid;
private Channel lastItem;
private WeakChangeListener<Image> weakPreviewListener;
public ChannelGridCell(final ChannelGrid grid, final MainWindow mainWindow) {
this.grid = grid;
getStyleClass().add(GRID_BOX);
name = new Label();
name.setPadding(new Insets(5));
name.setFont(new Font(12));
title = new Label();
title.setStyle("-fx-font-weight: bold");
viewer = new Label();
game = new Label();
imageView = new ImageView();
imageView.fitWidthProperty().bind(mainWindow.scalingGridCellWidthProperty());
imageView.setPreserveRatio(true);
final VBox vBoxSub = new VBox(title, viewer, game);
vBoxSub.setPadding(new Insets(5));
vBox = new VBox(name, imageView, vBoxSub);
setOnMouseClicked(event -> {
if (isEmpty() || getItem() == null) {
return;
}
if (event.getButton() == MouseButton.MIDDLE) {
doSelectionUpdate(grid, mainWindow);
mainWindow.openStream(grid.getSelected());
}
if (event.getButton() == MouseButton.PRIMARY) {
if (event.getClickCount() == 1) {
doSelectionUpdate(grid, mainWindow);
} else {
mainWindow.openDetailPage(getItem());
}
}
});
}
private void doSelectionUpdate(final ChannelGrid grid, final MainWindow mainWindow) {
mainWindow.onSelection(getItem());
updateSelected(true);
grid.select(getItem());
grid.updateItems();
}
@Override
protected void updateItem(final Channel item, final boolean empty) {
super.updateItem(item, empty);
if (lastItem != null && !lastItem.equals(item)) {
lastItem.previewProperty().removeListener(weakPreviewListener);
}
lastItem = item;
if (empty || item == null) {
imageView.setImage(null);
setGraphic(null);
setText(null);
} else {
updateSelected(grid.isSelected(item));
if (item.isOnline() != null) {
if (item.isOnline()) {
name.setStyle("-fx-font-weight: bold;-fx-text-fill: green");
} else {
name.setStyle("-fx-font-weight: bold;-fx-text-fill: red");
}
}
name.textProperty().bind(item.nameProperty());
title.textProperty().bind(item.titleProperty());
viewer.textProperty().bind(Bindings.createStringBinding(() -> String.valueOf(item.getViewer()), item.viewerProperty()));
viewer.setGraphic(GlyphsDude.createIcon(FontAwesomeIcon.USER));
game.textProperty().bind(item.gameProperty());
game.setGraphic(GlyphsDude.createIcon(FontAwesomeIcon.GAMEPAD));
weakPreviewListener = new WeakChangeListener<>((observable, oldValue, newValue) -> imageView.setImage(newValue));
item.previewProperty().addListener(weakPreviewListener);
imageView.setImage(item.getPreview());
setGraphic(vBox);
setText(null);
}
}
}
|
package extrabiomes.lib.worldgen;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.biome.BiomeGenBase.Height;
import net.minecraft.world.gen.feature.WorldGenAbstractTree;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraftforge.common.BiomeDictionary.Type;
import extrabiomes.lib.settings.BiomeSettings;
public abstract class ExtrabiomeGenBase extends BiomeGenBase {
/*
* Vanilla provides the following height definitions, which we should use where appropriate
*
height_Default = new Height(0.1F, 0.2F);
height_ShallowWaters = new Height(-0.5F, 0.0F);
height_Oceans = new Height(-1.0F, 0.1F);
height_DeepOceans = new Height(-1.8F, 0.1F);
height_LowPlains = new Height(0.125F, 0.05F);
height_MidPlains = new Height(0.2F, 0.2F);
height_LowHills = new Height(0.45F, 0.3F);
height_HighPlateaus = new Height(1.5F, 0.025F);
height_MidHills = new Height(1.0F, 0.5F);
height_Shores = new Height(0.0F, 0.025F);
height_RockyWaters = new Height(0.1F, 0.8F);
height_LowIslands = new Height(0.2F, 0.3F);
height_PartiallySubmerged = new Height(-0.2F, 0.1F);
*/
protected final static Height height_FlatPlains = new Height(0.1F, 0.03125F); // between Shores and LowPlains
protected BiomeSettings settings;
protected Type[] typeFlags;
// TODO: make these lists weighted
private final List<WorldGenAbstractTree> treeGenerators = Lists.newArrayList();
private final List<WorldGenerator> miscGenerators = Lists.newArrayList();
protected ExtrabiomeGenBase(BiomeSettings settings, Type... typeFlags) {
super(settings.getID(), true);
this.settings = settings;
this.typeFlags = typeFlags;
}
public BiomeSettings getBiomeSettings() {
return settings;
}
public Type[] getTypeFlags() {
return typeFlags;
}
public void registerTreeGenerator(WorldGenAbstractTree gen) {
treeGenerators.add(gen);
}
public void registerMiscGenerator(WorldGenerator gen) {
miscGenerators.add(gen);
}
private WorldGenerator getRandomGenerator(List<?extends WorldGenerator> list, Random rng) {
if( list.isEmpty() ) return null;
final int idx = rng.nextInt(list.size());
return list.get(idx);
}
@Override
public WorldGenerator getRandomWorldGenForGrass(Random rand) {
final WorldGenerator gen = getRandomGenerator(miscGenerators, rand);
if( gen != null )
return gen;
return super.getRandomWorldGenForGrass(rand);
}
@Override
public WorldGenAbstractTree func_150567_a(Random rand) {
// public WorldGenerator getRandomWorldGenForTrees(Random rand)
final WorldGenAbstractTree gen = (WorldGenAbstractTree) getRandomGenerator(treeGenerators, rand);
if( gen != null )
return gen;
return super.func_150567_a(rand);
}
}
|
package fi.csc.microarray.client;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import org.apache.log4j.Logger;
import fi.csc.microarray.client.SwingClientApplication.SessionSavingMethod;
import fi.csc.microarray.client.dialog.ClipboardImportDialog;
import fi.csc.microarray.client.dialog.FeedbackDialog;
import fi.csc.microarray.client.selection.DataSelectionManager;
import fi.csc.microarray.client.selection.DatasetChoiceEvent;
import fi.csc.microarray.client.visualisation.VisualisationFrameManager.FrameType;
import fi.csc.microarray.client.visualisation.VisualisationMethod;
import fi.csc.microarray.client.visualisation.VisualisationMethodChangedEvent;
import fi.csc.microarray.client.visualisation.VisualisationToolBar;
import fi.csc.microarray.config.DirectoryLayout;
import fi.csc.microarray.constants.VisualConstants;
import fi.csc.microarray.databeans.DataBean;
import fi.csc.microarray.databeans.DataItem;
import fi.csc.microarray.filebroker.FileBrokerException;
import fi.csc.microarray.module.Module;
import fi.csc.microarray.module.basic.BasicModule;
import fi.csc.microarray.util.Files;
@SuppressWarnings("serial")
public class MicroarrayMenuBar extends JMenuBar implements PropertyChangeListener {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(MicroarrayMenuBar.class);
private SwingClientApplication application;
private JMenu fileMenu = null;
private JMenu importMenu = null;
private JMenuItem directImportMenuItem = null;
private JMenuItem importFromURLMenuItem = null;
private JMenuItem importFromURLToServerMenuItem = null;
private JMenuItem importFromClipboardMenuItem = null;
private JMenuItem openWorkflowsMenuItem = null;
private JMenuItem openWorkflowsForEachMenuItem = null;
private JMenu recentWorkflowMenu;
private JMenu recentWorkflowForEachMenu;
private JMenuItem addDirMenuItem = null;
private JMenuItem exportMenuItem = null;
private JMenuItem quitMenuItem = null;
private JMenu editMenu = null;
private JMenuItem renameMenuItem = null;
private JMenuItem deleteMenuItem = null;
private JMenu viewMenu = null;
private JMenuItem restoreViewMenuItem = null;
private JMenu fontSizeMenu = null;
private JMenu workflowsMenu = null;
private JMenu helpInfoMenu = null;
private JMenuItem aboutMenuItem = null;
private JMenuItem contentMenuItem;
private JMenuItem startedMenuItem;
private JMenuItem sendFeedbackMenuItem;
private JMenuItem saveWorkflowMenuItem;
private JMenuItem helpWorkflowMenuItem;
private JMenuItem archiveSessionMenuItem;
private JMenuItem saveSessionMenuItem;
private JMenuItem taskListMenuItem;
private JMenuItem clearSessionMenuItem;
private JMenu joinSessionMenu;
private JMenuItem selectAllMenuItem;
private JMenuItem historyMenuItem;
private JMenuItem maximiseVisualisationMenuItem;
private JMenuItem visualiseMenuItem;
private JMenuItem closeVisualisationMenuItem;
private JMenuItem detachMenuItem;
private JMenu visualisationMenu;
private JMenu openRepoWorkflowsMenu;
private boolean hasRepoWorkflows;
private JMenuItem manageSessionsMenuItem;
private JMenuItem openExampleSessionMenuItem;
public MicroarrayMenuBar(SwingClientApplication application) {
this.application = application;
add(getFileMenu());
add(getEditMenu());
add(getViewMenu());
add(getWorkflowsMenu());
add(getHelpInfoMenu());
application.addClientEventListener(this);
}
public void updateMenuStatus() {
logger.debug("updating menubar when selected is " + application.getSelectionManager().getSelectedItem());
DataSelectionManager selectionManager = application.getSelectionManager();
DataBean selectedDataBean = selectionManager.getSelectedDataBean();
boolean somethingSelected = selectionManager.getSelectedItem() != null;
boolean multipleDatasSelected = selectionManager.getSelectedDataBeans().size() > 1;
boolean workflowCompatibleDataSelected = false;
if (selectedDataBean != null) {
workflowCompatibleDataSelected = Session.getSession().getPrimaryModule().isWorkflowCompatible(selectedDataBean);
}
renameMenuItem.setEnabled(selectionManager.getSelectedDataBeans().size() == 1);
historyMenuItem.setEnabled(selectedDataBean != null && application.getSelectionManager().getSelectedDataBeans().size() == 1);
visualiseMenuItem.setEnabled(selectedDataBean != null);
VisualisationMethod method = application.getVisualisationFrameManager().getFrame(FrameType.MAIN).getMethod();
visualisationMenu.setEnabled(method != null);
closeVisualisationMenuItem.setEnabled(!VisualisationMethod.isDefault(method));
openWorkflowsMenuItem.setEnabled(workflowCompatibleDataSelected);
recentWorkflowMenu.setEnabled(workflowCompatibleDataSelected);
openRepoWorkflowsMenu.setEnabled(workflowCompatibleDataSelected && hasRepoWorkflows);
openWorkflowsForEachMenuItem.setEnabled(workflowCompatibleDataSelected && multipleDatasSelected);
recentWorkflowForEachMenu.setEnabled(workflowCompatibleDataSelected && multipleDatasSelected);
saveWorkflowMenuItem.setEnabled(workflowCompatibleDataSelected);
exportMenuItem.setEnabled(somethingSelected);
renameMenuItem.setEnabled(somethingSelected);
deleteMenuItem.setEnabled(somethingSelected);
}
/**
* This method initializes fileMenu
*
* @return javax.swing.JMenu
*/
private JMenu getFileMenu() {
if (fileMenu == null) {
fileMenu = new JMenu();
fileMenu.setText("File");
fileMenu.setMnemonic('F');
fileMenu.add(getDirectImportMenuItem());
fileMenu.add(getAddDirMenuItem());
fileMenu.add(getImportMenu());
fileMenu.addSeparator();
fileMenu.add(getExportMenuItem());
fileMenu.addSeparator();
fileMenu.add(getLoadLocalSessionMenuItem(true));
fileMenu.add(getSaveLocalSessionMenuItem());
fileMenu.addSeparator();
fileMenu.add(getOpenExampleSessionMenuItem());
if (application.getSessionManager().areCloudSessionsEnabled()) {
fileMenu.addSeparator();
fileMenu.add(getLoadSessionMenuItem(true));
fileMenu.add(getSaveSessionMenuItem());
fileMenu.add(getManageSessionsMenuItem());
}
fileMenu.addSeparator();
fileMenu.add(getMergeSessionMenu());
fileMenu.add(getClearSessionMenuItem());
fileMenu.addSeparator();
fileMenu.add(getQuitMenuItem());
}
return fileMenu;
}
private JMenuItem getMergeSessionMenu() {
if (joinSessionMenu == null) {
joinSessionMenu = new JMenu();
joinSessionMenu.setText("Merge session");
joinSessionMenu.add(getLoadLocalSessionMenuItem(false));
if (application.getSessionManager().areCloudSessionsEnabled()) {
joinSessionMenu.add(getLoadSessionMenuItem(false));
}
}
return joinSessionMenu;
}
private JMenu getImportMenu() {
if (importMenu == null) {
importMenu = new JMenu();
importMenu.setText("Import from");
if (!application.isStandalone()) {
Module primaryModule = Session.getSession().getPrimaryModule();
primaryModule.addImportMenuItems(importMenu);
}
importMenu.add(getImportFromURLMenuItem());
importMenu.add(getImportFromURLToServerMenuItem());
importMenu.add(getImportFromClipboardMenuItem());
}
return importMenu;
}
private JMenuItem getDirectImportMenuItem() {
if (directImportMenuItem == null) {
directImportMenuItem = new JMenuItem();
directImportMenuItem.setText("Import files...");
directImportMenuItem.setAccelerator(KeyStroke.getKeyStroke('I', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
directImportMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.openFileImport();
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return directImportMenuItem;
}
private JMenuItem getImportFromURLMenuItem() {
if (importFromURLMenuItem == null) {
importFromURLMenuItem = new JMenuItem();
importFromURLMenuItem.setText("URL to client...");
importFromURLMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.openURLImport();
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return importFromURLMenuItem;
}
private JMenuItem getImportFromURLToServerMenuItem() {
if (importFromURLToServerMenuItem == null) {
importFromURLToServerMenuItem = new JMenuItem();
importFromURLToServerMenuItem.setText("URL directly to server...");
importFromURLToServerMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
BasicModule.importFromUrlToServer();
}
});
}
return importFromURLToServerMenuItem;
}
private JMenuItem getHelpWorkflowMenuItem() {
if (helpWorkflowMenuItem == null) {
helpWorkflowMenuItem = new JMenuItem();
helpWorkflowMenuItem.setText("More information...");
helpWorkflowMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.viewHelp("workflows.html#ready");
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return helpWorkflowMenuItem;
}
private JMenuItem getOpenWorkflowMenuItem() {
if (openWorkflowsMenuItem == null) {
openWorkflowsMenuItem = new JMenuItem();
openWorkflowsMenuItem.setText("Run...");
openWorkflowsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
File workflow = application.openWorkflow(false);
if (workflow != null) {
addRecentWorkflow(workflow.getName(), Files.toUrl(workflow));
}
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return openWorkflowsMenuItem;
}
private JMenuItem getOpenWorkflowForEachMenuItem() {
if (openWorkflowsForEachMenuItem == null) {
openWorkflowsForEachMenuItem = new JMenuItem();
openWorkflowsForEachMenuItem.setText("Run for each...");
openWorkflowsForEachMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
File workflow = application.openWorkflow(true);
addRecentWorkflow(workflow.getName(), Files.toUrl(workflow));
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return openWorkflowsForEachMenuItem;
}
private JMenu getOpenRepositoryWorkflowMenu() {
if (openRepoWorkflowsMenu == null) {
// Load repository content
String[][] repoWorkflows = Session.getSession().getPrimaryModule().getRepositoryWorkflows();
this.hasRepoWorkflows = repoWorkflows.length > 0;
openRepoWorkflowsMenu = new JMenu();
openRepoWorkflowsMenu.setText("Run from Chipster repository");
// Add repository content
for (String[] flow : repoWorkflows) {
JMenuItem item = new JMenuItem(flow[0]);
item.addActionListener(new RepoWorkflowActionListener(flow[0], flow[1]));
openRepoWorkflowsMenu.add(item);
}
// Add help
openRepoWorkflowsMenu.addSeparator();
openRepoWorkflowsMenu.add(getHelpWorkflowMenuItem());
}
return openRepoWorkflowsMenu;
}
private class RepoWorkflowActionListener implements ActionListener {
private String resourceName;
private String name;
public RepoWorkflowActionListener(String name, String resourceName) {
this.name = name;
this.resourceName = resourceName;
}
public void actionPerformed(ActionEvent e) {
URL url = getClass().getResource(resourceName);
((SwingClientApplication) application).runWorkflow(url, false);
addRecentWorkflow(name, url);
}
}
public void addRecentWorkflow(String name, URL url) {
if (url != null) {
// Check if this exists already
for (int i = 0; i < recentWorkflowMenu.getItemCount(); i++) {
JMenuItem menuItem = recentWorkflowMenu.getItem(i);
if (menuItem.getText().equals(name)) {
recentWorkflowMenu.remove(menuItem);
}
}
// Update both recent lists (normal and for-each)
recentWorkflowMenu.add(createRunWorkflowMenuItem(name, url, false));
recentWorkflowForEachMenu.add(createRunWorkflowMenuItem(name, url, true));
}
}
private JMenuItem getImportFromClipboardMenuItem() {
if (importFromClipboardMenuItem == null) {
importFromClipboardMenuItem = new JMenuItem();
importFromClipboardMenuItem.setText("Clipboard...");
importFromClipboardMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
new ClipboardImportDialog(Session.getSession().getApplication());
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return importFromClipboardMenuItem;
}
private JMenuItem getExportMenuItem() {
if (exportMenuItem == null) {
exportMenuItem = new JMenuItem();
exportMenuItem.setText("Export dataset(s) or folder...");
exportMenuItem.setAccelerator(KeyStroke.getKeyStroke('E', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
exportMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.exportSelectedItems();
}
});
}
return exportMenuItem;
}
private JMenuItem getQuitMenuItem() {
if (quitMenuItem == null) {
quitMenuItem = new JMenuItem();
quitMenuItem.setText("Quit");
quitMenuItem.setAccelerator(KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
quitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.quit();
}
});
}
return quitMenuItem;
}
private JMenu getEditMenu() {
if (editMenu == null) {
editMenu = new JMenu();
editMenu.setText("Edit");
editMenu.setMnemonic('E');
editMenu.add(getRenameMenuItem());
editMenu.add(getDeleteMenuItem());
editMenu.add(getHistoryMenuItem());
editMenu.addSeparator();
editMenu.add(getSelectAllMenuItem());
}
return editMenu;
}
private JMenuItem getHistoryMenuItem() {
if (historyMenuItem == null) {
historyMenuItem = new JMenuItem();
historyMenuItem.setText("Show history...");
historyMenuItem.setIcon(VisualConstants.getIcon(VisualConstants.GENERATE_HISTORY_ICON));
historyMenuItem.setAccelerator(KeyStroke.getKeyStroke('H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
historyMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
DataBean data = application.getSelectionManager().getSelectedDataBean();
if (data != null) {
application.showHistoryScreenFor(data);
}
}
});
}
return historyMenuItem;
}
private JMenuItem getRenameMenuItem() {
if (renameMenuItem == null) {
renameMenuItem = new JMenuItem();
renameMenuItem.setText("Rename selected item...");
renameMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
renameMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.showRenameView();
}
});
}
return renameMenuItem;
}
private JMenuItem getDeleteMenuItem() {
if (deleteMenuItem == null) {
deleteMenuItem = new JMenuItem();
deleteMenuItem.setText("Delete selected item");
deleteMenuItem.setIcon(VisualConstants.getIcon(VisualConstants.DELETE_MENUICON));
deleteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
deleteMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.deleteDatas(application.getSelectionManager().getSelectedDataBeans().toArray(new DataItem[0]));
}
});
}
return deleteMenuItem;
}
private JMenuItem getSelectAllMenuItem() {
if (selectAllMenuItem == null) {
selectAllMenuItem = new JMenuItem();
selectAllMenuItem.setText("Select all");
selectAllMenuItem.setAccelerator(KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
selectAllMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.selectAllItems();
}
});
}
return selectAllMenuItem;
}
private JMenu getWorkflowsMenu() {
if (workflowsMenu == null) {
workflowsMenu = new JMenu();
workflowsMenu.setText("Workflow");
workflowsMenu.add(getOpenWorkflowMenuItem());
workflowsMenu.add(getRecentWorkflowMenu());
workflowsMenu.add(getOpenRepositoryWorkflowMenu());
workflowsMenu.addSeparator();
workflowsMenu.add(getOpenWorkflowForEachMenuItem());
workflowsMenu.add(getRecentWorkflowForEachMenu());
workflowsMenu.addSeparator();
workflowsMenu.add(getSaveWorkflowMenuItem());
if (application.isStandalone()) {
workflowsMenu.setEnabled(false);
} else {
// Populate both recent workflow lists
List<File> workflows = application.getWorkflows();
for (File workflow : workflows) {
addRecentWorkflow(workflow.getName(), Files.toUrl(workflow));
}
}
}
return workflowsMenu;
}
private JMenuItem getTaskListMenuItem() {
if (taskListMenuItem == null) {
taskListMenuItem = new JMenuItem();
taskListMenuItem.setText("View jobs...");
taskListMenuItem.setAccelerator(KeyStroke.getKeyStroke('T', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
taskListMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.viewTasks();
}
});
}
return taskListMenuItem;
}
private JMenuItem getSaveWorkflowMenuItem() {
if (saveWorkflowMenuItem == null) {
saveWorkflowMenuItem = new JMenuItem();
saveWorkflowMenuItem.setText("Save starting from selected...");
saveWorkflowMenuItem.setEnabled(false);
saveWorkflowMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
File workflow = application.saveWorkflow();
if (workflow != null) {
addRecentWorkflow(workflow.getName(), Files.toUrl(workflow));
}
}
});
}
return saveWorkflowMenuItem;
}
private JMenu getRecentWorkflowMenu() {
if (recentWorkflowMenu == null) {
recentWorkflowMenu = new JMenu();
recentWorkflowMenu.setText("Run recent");
}
return recentWorkflowMenu;
}
private JMenu getRecentWorkflowForEachMenu() {
if (recentWorkflowForEachMenu == null) {
recentWorkflowForEachMenu = new JMenu();
recentWorkflowForEachMenu.setText("Run recent for each");
}
return recentWorkflowForEachMenu;
}
private JMenuItem createRunWorkflowMenuItem(String name, final URL workflowScript, final boolean runForEach) {
JMenuItem runWorkflowMenuItem = new JMenuItem(name);
runWorkflowMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.runWorkflow(workflowScript, runForEach);
}
});
return runWorkflowMenuItem;
}
private JMenu getViewMenu() {
if (viewMenu == null) {
viewMenu = new JMenu();
viewMenu.setText("View");
viewMenu.add(getRestoreViewMenuItem());
viewMenu.addSeparator();
viewMenu.add(getVisualiseMenutItem());
viewMenu.add(getCloseVisualisationMenutItem());
viewMenu.add(getVisualisationwMenu());
viewMenu.addSeparator();
viewMenu.add(getFontSize());
viewMenu.addSeparator();
viewMenu.add(getTaskListMenuItem());
}
return viewMenu;
}
private JMenu getVisualisationwMenu() {
if (visualisationMenu == null) {
visualisationMenu = new JMenu();
visualisationMenu.setText("Visualisation");
visualisationMenu.add(getMaximiseVisualisationMenuItem());
visualisationMenu.add(getDetachMenuItem());
}
return visualisationMenu;
}
private JMenuItem getDetachMenuItem() {
if (detachMenuItem == null) {
detachMenuItem = new JMenuItem();
detachMenuItem.setText("Detach");
detachMenuItem.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
detachMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
VisualisationToolBar visToolBar = application.getVisualisationFrameManager().getVisualisationToolBar();
visToolBar.detach();
}
});
}
return detachMenuItem;
}
private JMenuItem getMaximiseVisualisationMenuItem() {
if (maximiseVisualisationMenuItem == null) {
maximiseVisualisationMenuItem = new JMenuItem();
maximiseVisualisationMenuItem.setText("Maximise/Restore");
maximiseVisualisationMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0));
maximiseVisualisationMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
VisualisationToolBar visToolBar = application.getVisualisationFrameManager().getVisualisationToolBar();
visToolBar.maximiseOrRestoreVisualisation();
}
});
}
return maximiseVisualisationMenuItem;
}
private JMenuItem getVisualiseMenutItem() {
if (visualiseMenuItem == null) {
visualiseMenuItem = new JMenuItem();
visualiseMenuItem.setText("Visualise selected");
visualiseMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
visualiseMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
application.visualiseWithBestMethod(FrameType.MAIN);
}
});
}
return visualiseMenuItem;
}
private JMenuItem getCloseVisualisationMenutItem() {
if (closeVisualisationMenuItem == null) {
closeVisualisationMenuItem = new JMenuItem();
closeVisualisationMenuItem.setText("Close visualisation");
closeVisualisationMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
closeVisualisationMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
application.setVisualisationMethodToDefault();
}
});
}
return closeVisualisationMenuItem;
}
private JMenuItem getRestoreViewMenuItem() {
if (restoreViewMenuItem == null) {
restoreViewMenuItem = new JMenuItem();
restoreViewMenuItem.setText("Restore default");
restoreViewMenuItem.setIcon(VisualConstants.getIcon(VisualConstants.DEFAULT_VIEW_MENUICON));
restoreViewMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.restoreDefaultView();
}
});
}
return restoreViewMenuItem;
}
/**
* This method initializes helpInfoMenu. Name was chosen because getHelpMenu() causes conflict.
*/
private JMenu getHelpInfoMenu() {
if (helpInfoMenu == null) {
helpInfoMenu = new JMenu();
helpInfoMenu.setText("Help");
helpInfoMenu.setMnemonic('H');
helpInfoMenu.add(getStartedMenuItem());
helpInfoMenu.add(getContentMenuItem());
if (DirectoryLayout.getInstance().getConfiguration().getBoolean("client", "enable-contact-support")) {
helpInfoMenu.add(getSendFeedbackMenuItem());
}
helpInfoMenu.add(getAboutMenuItem());
}
return helpInfoMenu;
}
private JMenuItem getContentMenuItem() {
if (contentMenuItem == null) {
contentMenuItem = new JMenuItem();
contentMenuItem.setText("User manual");
contentMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
contentMenuItem.setIcon(VisualConstants.getIcon(VisualConstants.HELP_MENUICON));
contentMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.viewHelp(Session.getSession().getPrimaryModule().getManualHome());
}
});
}
return contentMenuItem;
}
private JMenuItem getStartedMenuItem() {
if (startedMenuItem == null) {
startedMenuItem = new JMenuItem();
startedMenuItem.setText("Getting started");
startedMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.viewHelp(Session.getSession().getPrimaryModule().getManualHome() + "/basic-functionality.html");
}
});
}
return startedMenuItem;
}
private JMenuItem getSendFeedbackMenuItem() {
if (sendFeedbackMenuItem == null) {
sendFeedbackMenuItem = new JMenuItem();
sendFeedbackMenuItem.setText("Contact Support...");
sendFeedbackMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
FeedbackDialog feedback = new FeedbackDialog(application, "", false);
feedback.showDialog();
}
});
}
return sendFeedbackMenuItem;
}
private JMenuItem getAboutMenuItem() {
if (aboutMenuItem == null) {
aboutMenuItem = new JMenuItem();
aboutMenuItem.setText("About");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.viewHelp(Session.getSession().getPrimaryModule().getManualHome() + "/about.html");
}
});
}
return aboutMenuItem;
}
private JMenu getFontSize() {
if (fontSizeMenu == null) {
fontSizeMenu = new JMenu();
fontSizeMenu.setText("Text size");
// TODO fix: L&F Theme is lost when the font is changed
// fontSizeMenu.setEnabled(false);
JMenuItem norm = new JMenuItem("Normal");
JMenuItem inc = new JMenuItem("Increase");
JMenuItem dec = new JMenuItem("Decrease");
inc.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
dec.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
norm.setAccelerator(KeyStroke.getKeyStroke('0', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
fontSizeMenu.add(inc);
fontSizeMenu.add(dec);
fontSizeMenu.addSeparator();
fontSizeMenu.add(norm);
norm.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.setFontSize(VisualConstants.DEFAULT_FONT_SIZE);
}
});
dec.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.setFontSize(application.getFontSize() - 1);
}
});
inc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.setFontSize(application.getFontSize() + 1);
}
});
}
return fontSizeMenu;
}
private JMenuItem getOpenExampleSessionMenuItem() {
if (openExampleSessionMenuItem == null) {
openExampleSessionMenuItem = new JMenuItem();
openExampleSessionMenuItem.setText("Open example session");
openExampleSessionMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
application.loadSession(true, true, true);
}
});
}
return openExampleSessionMenuItem;
}
private JMenuItem getClearSessionMenuItem() {
if (clearSessionMenuItem == null) {
clearSessionMenuItem = new JMenuItem();
clearSessionMenuItem.setText("New session");
clearSessionMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
application.clearSession();
} catch (MalformedURLException | FileBrokerException e1) {
application.reportException(e1);
}
}
});
}
return clearSessionMenuItem;
}
private JMenuItem getLoadSessionMenuItem(final boolean clear) {
JMenuItem loadSessionMenuItem = new JMenuItem();
if (clear) {
loadSessionMenuItem.setText("Open cloud session... (BETA)");
} else {
loadSessionMenuItem.setText("Cloud session... (BETA)");
}
loadSessionMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.loadSession(true, false, clear);
} catch (Exception ioe) {
application.reportException(ioe);
}
}
});
return loadSessionMenuItem;
}
private JMenuItem getLoadLocalSessionMenuItem(final boolean clear) {
JMenuItem loadLocalSessionMenuItem = new JMenuItem();
loadLocalSessionMenuItem.setText("Open local session...");
if (clear) {
loadLocalSessionMenuItem.setText("Open local session...");
loadLocalSessionMenuItem.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
} else {
loadLocalSessionMenuItem.setText("Local session...");
}
loadLocalSessionMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.loadSession(false, false, clear);
} catch (Exception ioe) {
application.reportException(ioe);
}
}
});
return loadLocalSessionMenuItem;
}
private JMenuItem getSaveSessionMenuItem() {
if (saveSessionMenuItem == null) {
saveSessionMenuItem = new JMenuItem();
saveSessionMenuItem.setText("Save cloud session... (BETA)");
saveSessionMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.saveSession(SessionSavingMethod.UPLOAD_DATA_TO_SERVER);
}
});
}
return saveSessionMenuItem;
}
private JMenuItem getManageSessionsMenuItem() {
if (manageSessionsMenuItem == null) {
manageSessionsMenuItem = new JMenuItem();
manageSessionsMenuItem.setText("Manage cloud sessions... (BETA)");
manageSessionsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.manageRemoteSessions();
}
});
}
return manageSessionsMenuItem;
}
private JMenuItem getSaveLocalSessionMenuItem() {
if (archiveSessionMenuItem == null) {
archiveSessionMenuItem = new JMenuItem();
archiveSessionMenuItem.setText("Save local session...");
archiveSessionMenuItem.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
archiveSessionMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.saveSession(SessionSavingMethod.INCLUDE_DATA_INTO_ZIP);
}
});
}
return archiveSessionMenuItem;
}
private JMenuItem getAddDirMenuItem() {
if (addDirMenuItem == null) {
addDirMenuItem = new JMenuItem();
addDirMenuItem.setText("Import folder...");
addDirMenuItem.setAccelerator(KeyStroke.getKeyStroke('I', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | InputEvent.SHIFT_DOWN_MASK, false));
addDirMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.openDirectoryImportDialog();
}
});
}
return addDirMenuItem;
}
public void propertyChange(PropertyChangeEvent evt) {
if (evt instanceof DatasetChoiceEvent || evt instanceof VisualisationMethodChangedEvent) {
updateMenuStatus();
}
}
}
|
package giraudsa.marshall.serialisation;
import giraudsa.marshall.exception.MarshallExeption;
import giraudsa.marshall.exception.NotImplementedSerializeException;
import giraudsa.marshall.serialisation.ActionAbstrait.Comportement;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import utils.Constants;
import utils.champ.FieldInformations;
public abstract class Marshaller {
//////ATTRIBUT
protected boolean isCompleteSerialisation;
protected Set<Object> dejaTotalementSerialise = new HashSet<>();
private Set<Object> dejaVu = new HashSet<>();
@SuppressWarnings("rawtypes")
protected Deque<Comportement> aFaire = new ArrayDeque<>();
//////Constructeur
protected Marshaller(boolean isCompleteSerialisation){
this.isCompleteSerialisation = isCompleteSerialisation;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <T> ActionAbstrait getAction(T obj) throws NotImplementedSerializeException {
Map<Class<?>, ActionAbstrait<?>> dicoTypeToAction = getDicoTypeToAction();
ActionAbstrait action;
if (obj == null) {
action = dicoTypeToAction.get(void.class);
} else {
Class<T> type = (Class<T>) obj.getClass();
action = dicoTypeToAction.get(type);
if (action == null) {
action = choisiAction(type);
}
}
return action;
}
protected abstract Map<Class<?>, ActionAbstrait<?>> getDicoTypeToAction();
@SuppressWarnings("rawtypes")
private <T> ActionAbstrait choisiAction(Class<T> type) throws NotImplementedSerializeException {
Map<Class<?>, ActionAbstrait<?>> dicoTypeToAction = getDicoTypeToAction();
ActionAbstrait action;
Class<?> genericType = type;
if (type.isEnum())
genericType = Constants.enumType;
else if (Constants.dictionaryType.isAssignableFrom(type))
genericType = Constants.dictionaryType;
else if(Constants.dateType.isAssignableFrom(type))
genericType = Constants.dateType;
else if (Constants.collectionType.isAssignableFrom(type))
genericType = Constants.collectionType;
else if(type.isArray())
genericType = Constants.arrayType;
else if(Constants.inetAdress.isAssignableFrom(type))
genericType = Constants.inetAdress;
else if(Constants.calendarType.isAssignableFrom(type))
genericType = Constants.calendarType;
else if (type.getPackage() == null || ! type.getPackage().getName().startsWith("System"))
genericType = Constants.objectType;
action = dicoTypeToAction.get(genericType);
dicoTypeToAction.put(type, action);
if (action == null) {
throw new NotImplementedSerializeException("not implemented: " + type);
}
return action;
}
protected <T> boolean isDejaVu(T obj){
return dejaVu.contains(obj);
}
protected <T> void setDejaVu(T obj){
dejaVu.add(obj);
}
protected <T> boolean isDejaTotalementSerialise(T obj){
return dejaTotalementSerialise.contains(obj);
}
protected <T> void setDejaTotalementSerialise(T obj){
dejaTotalementSerialise.add(obj);
}
protected void deserialisePile() throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException, NotImplementedSerializeException, MarshallExeption{
aFaire.pop().evalue(this);
}
protected <T> void marshall(T value, FieldInformations fieldInformations) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException, NotImplementedSerializeException, MarshallExeption {
ActionAbstrait<?> action = getAction(value);
action.marshall(this, value, fieldInformations);
}
}
|
package im.yangqiang.android.unicorn.core;
import android.content.Context;
import org.json.JSONObject;
import java.util.Map;
import im.yangqiang.android.unicorn.data.http.HttpUtils;
import im.yangqiang.android.unicorn.data.http.server.inf.IResponse;
public class UinModel
{
private Context mContext;
public UinModel(Context context)
{
mContext = context;
}
public Context getContext()
{
return mContext;
}
/**
* POSTJson
*
* @param isCache
* @param tag
* @param url
* @param param
* @param response
*/
public void postJson(boolean isCache, Object tag, String url, Map<String, String> param, IResponse<JSONObject> response)
{
HttpUtils.postJson(isCache, mContext, tag, url, param, response);
}
/**
* POSTJson
*
* @param tag
* @param url
* @param param
* @param response
*/
public void postJson(Object tag, String url, Map<String, String> param, IResponse<JSONObject> response)
{
postJson(true, tag, url, param, response);
}
/**
* POSTString
*
* @param isCache
* @param tag
* @param url
* @param param
* @param response
*/
public void postString(boolean isCache, Object tag, String url, Map<String, String> param, IResponse<String> response)
{
HttpUtils.postString(isCache, mContext, tag, url, param, response);
}
/**
* POSTString,
*
* @param tag
* @param url
* @param param
* @param response
*/
public void postString(Object tag, String url, Map<String, String> param, IResponse<String> response)
{
postString(true, tag, url, param, response);
}
/**
* GETString
*
* @param isCache
* @param tag
* @param url
* @param param
* @param response
*/
public void requestString(boolean isCache, Object tag, String url, Map<String, String> param, IResponse<String> response)
{
HttpUtils.requestString(isCache, mContext, tag, url, param, response);
}
/**
* GETString
*
* @param tag
* @param url
* @param param
* @param response
*/
public void requestString(Object tag, String url, Map<String, String> param, IResponse<String> response)
{
requestString(true, tag, url, param, response);
}
}
|
npackage innovimax.mixthem.operation;
interface ILineOperation extends IOperation {
String process(String line1, String line2);
}
|
package io.github.classgraph;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import nonapi.io.github.classgraph.scanspec.ScanSpec;
import nonapi.io.github.classgraph.utils.JarUtils;
/** {@link ClassLoader} for classes found by ClassGraph during scanning. */
class ClassGraphClassLoader extends ClassLoader {
/** The scan result. */
private final ScanResult scanResult;
/** Whether or not to initialize loaded classes. */
private final boolean initializeLoadedClasses;
/** The ordered set of environment classloaders to try delegating to. */
private final Set<ClassLoader> environmentClassLoaderDelegationOrder;
/** The ordered set of overridden or added classloaders to try delegating to. */
private final Set<ClassLoader> overriddenOrAddedClassLoaderDelegationOrder;
/**
* Constructor.
*
* @param scanResult
* The ScanResult.
*/
ClassGraphClassLoader(final ScanResult scanResult) {
super(null);
registerAsParallelCapable();
this.scanResult = scanResult;
final ScanSpec scanSpec = scanResult.scanSpec;
initializeLoadedClasses = scanSpec.initializeLoadedClasses;
final boolean classpathOverridden = scanSpec.overrideClasspath != null
&& !scanSpec.overrideClasspath.isEmpty();
final boolean classloadersOverridden = scanSpec.overrideClassLoaders != null
&& !scanSpec.overrideClassLoaders.isEmpty();
final boolean clasloadersAdded = scanSpec.addedClassLoaders != null
&& !scanSpec.addedClassLoaders.isEmpty();
// Uniquified order of classloaders to delegate to
environmentClassLoaderDelegationOrder = new LinkedHashSet<>();
// Only try environment classloaders if classpath and/or classloaders are not overridden
if (!classpathOverridden && !classloadersOverridden) {
// Try the null classloader first (this will default to the context classloader of the class
// that called ClassGraph)
environmentClassLoaderDelegationOrder.add(null);
// Try environment classloaders
final ClassLoader[] envClassLoaderOrder = scanResult.getClassLoaderOrderRespectingParentDelegation();
if (envClassLoaderOrder != null) {
// Try environment classloaders
for (final ClassLoader envClassLoader : envClassLoaderOrder) {
environmentClassLoaderDelegationOrder.add(envClassLoader);
}
}
}
// If the classpath is overridden, try loading class from the classpath URLs (this is done before
// checking classloader overrides, since classpath override takes precedence over classloader
// overrides in the ClasspathFinder class). Some of these URLs might be invalid if the ScanResult
// has been closed (e.g. in the rare case that an inner jar had to be extracted to a temporary file
// on disk).
final URLClassLoader classpathClassLoader = new URLClassLoader(
scanResult.getClasspathURLs().toArray(new URL[0]));
if (classpathOverridden) {
environmentClassLoaderDelegationOrder.add(classpathClassLoader);
}
// If classloaders are overridden or added, try loading through those classloaders
overriddenOrAddedClassLoaderDelegationOrder = new LinkedHashSet<>();
if (classloadersOverridden) {
overriddenOrAddedClassLoaderDelegationOrder.addAll(scanSpec.overrideClassLoaders);
}
if (clasloadersAdded) {
overriddenOrAddedClassLoaderDelegationOrder.addAll(scanSpec.addedClassLoaders);
}
if (!classpathOverridden) {
// If the classpath was not overridden, now that override classloaders have been attempted and failed,
// try to load the class from the classpath URLs before attempting direct classloading from resources
overriddenOrAddedClassLoaderDelegationOrder.add(classpathClassLoader);
}
}
/* (non-Javadoc)
* @see java.lang.ClassLoader#findClass(java.lang.String)
*/
@Override
protected Class<?> findClass(final String className)
throws ClassNotFoundException, LinkageError, SecurityException {
// Use cached class, if it is already loaded
final Class<?> loadedClass = findLoadedClass(className);
if (loadedClass != null) {
return loadedClass;
}
// Try environment classloader(s)
if (!environmentClassLoaderDelegationOrder.isEmpty()) {
for (final ClassLoader envClassLoader : environmentClassLoaderDelegationOrder) {
try {
return Class.forName(className, initializeLoadedClasses, envClassLoader);
} catch (ClassNotFoundException | LinkageError e) {
// Ignore
}
}
}
// Try getting the ClassInfo for the named class, then the ClassLoader from the ClassInfo.
// This should still be valid if the ScanResult was closed, since ScanResult#close() leaves
// the classNameToClassInfo map intact, but still, this is only attempted if all the above
// efforts failed, to avoid accessing ClassInfo objects after the ScanResult is closed (#399).
final ClassInfo classInfo = scanResult.classNameToClassInfo == null ? null
: scanResult.classNameToClassInfo.get(className);
if (classInfo != null) {
// Try specific classloader for the classpath element that the classfile was obtained from,
// as long as it wasn't already tried
if (classInfo.classLoader != null
&& !environmentClassLoaderDelegationOrder.contains(classInfo.classLoader)) {
try {
return Class.forName(className, initializeLoadedClasses, classInfo.classLoader);
} catch (ClassNotFoundException | LinkageError e) {
// Ignore
}
}
// If class came from a module, and it was not able to be loaded by the environment classloader,
// then it is probable it was a non-public class, and ClassGraph found it by ignoring class visibility
// when reading the resources in exported packages directly. Force ClassGraph to respect JPMS
// encapsulation rules by refusing to load modular classes that the context/system classloaders
// could not load. (A SecurityException should be thrown above, but this is here for completeness.)
if (classInfo.classpathElement instanceof ClasspathElementModule && !classInfo.isPublic()) {
throw new ClassNotFoundException("Classfile for class " + className + " was found in a module, "
+ "but the context and system classloaders could not load the class, probably because "
+ "the class is not public.");
}
}
// Try overridden or added classloader(s)
if (!overriddenOrAddedClassLoaderDelegationOrder.isEmpty()) {
for (final ClassLoader additionalClassLoader : overriddenOrAddedClassLoaderDelegationOrder) {
try {
return Class.forName(className, initializeLoadedClasses, additionalClassLoader);
} catch (ClassNotFoundException | LinkageError e) {
// Ignore
}
}
}
// As a last-ditch attempt, if the above efforts all failed, try obtaining the classfile as a
// resource, and define the class from the resource content. This should be performed after
// environment classloading is attempted, so that classes are not loaded by a mix of environment
// classloaders and direct manual classloading, otherwise class compatibility issues can arise.
// The ScanResult should only be accessed (to fetch resources) as a last resort, so that wherever
// possible, linked classes can be loaded after the ScanResult is closed. Otherwise if you load
// classes before a ScanResult is closed, then you close the ScanResult, then you try to access
// fields of the ScanResult that have a type that has not yet been loaded, this can trigger an
// exception that the ScanResult was accessed after it was closed (#399).
final ResourceList classfileResources = scanResult
.getResourcesWithPath(JarUtils.classNameToClassfilePath(className));
if (classfileResources != null) {
for (final Resource resource : classfileResources) {
// Iterate through resources (only loading of first resource in the list will be attempted)
try {
// Load the content of the resource, and define a class from it
final ByteBuffer resourceByteBuffer = resource.read();
return defineClass(className, resourceByteBuffer, null);
} catch (final IOException e) {
throw new ClassNotFoundException("Could not load classfile for class " + className + " : " + e);
} finally {
resource.close();
}
}
}
throw new ClassNotFoundException("Could not load classfile for class " + className);
}
/* (non-Javadoc)
* @see java.lang.ClassLoader#getResource(java.lang.String)
*/
@Override
public URL getResource(final String path) {
// This order should match the order in findClass(String)
// Try loading resource from environment classloader(s)
if (!environmentClassLoaderDelegationOrder.isEmpty()) {
for (final ClassLoader envClassLoader : environmentClassLoaderDelegationOrder) {
final URL resource = envClassLoader.getResource(path);
if (resource != null) {
return resource;
}
}
}
// Try loading resource from overridden or added classloader(s)
if (!overriddenOrAddedClassLoaderDelegationOrder.isEmpty()) {
for (final ClassLoader additionalClassLoader : overriddenOrAddedClassLoaderDelegationOrder) {
final URL resource = additionalClassLoader.getResource(path);
if (resource != null) {
return resource;
}
}
}
// Finally if the above attempts fail, try retrieving resource from ScanResult.
// This will throw an exception if ScanResult has already been closed (#399).
final ResourceList resourceList = scanResult.getResourcesWithPath(path);
if (resourceList == null || resourceList.isEmpty()) {
return super.getResource(path);
} else {
return resourceList.get(0).getURL();
}
}
/* (non-Javadoc)
* @see java.lang.ClassLoader#getResources(java.lang.String)
*/
@Override
public Enumeration<URL> getResources(final String path) throws IOException {
// This order should match the order in findClass(String)
// Try loading resources from environment classloader(s)
if (!environmentClassLoaderDelegationOrder.isEmpty()) {
for (final ClassLoader envClassLoader : environmentClassLoaderDelegationOrder) {
final Enumeration<URL> resources = envClassLoader.getResources(path);
if (resources != null && resources.hasMoreElements()) {
return resources;
}
}
}
// Try loading resources from overridden or added classloader(s)
if (!overriddenOrAddedClassLoaderDelegationOrder.isEmpty()) {
for (final ClassLoader additionalClassLoader : overriddenOrAddedClassLoaderDelegationOrder) {
final Enumeration<URL> resources = additionalClassLoader.getResources(path);
if (resources != null && resources.hasMoreElements()) {
return resources;
}
}
}
// Finally if the above attempts fail, try retrieving resource from ScanResult.
// This will throw an exception if ScanResult has already been closed (#399).
final ResourceList resourceList = scanResult.getResourcesWithPath(path);
if (resourceList == null || resourceList.isEmpty()) {
return Collections.<URL> emptyEnumeration();
} else {
return new Enumeration<URL>() {
/** The idx. */
int idx;
@Override
public boolean hasMoreElements() {
return idx < resourceList.size();
}
@Override
public URL nextElement() {
return resourceList.get(idx++).getURL();
}
};
}
}
/* (non-Javadoc)
* @see java.lang.ClassLoader#getResourceAsStream(java.lang.String)
*/
@Override
public InputStream getResourceAsStream(final String path) {
// This order should match the order in findClass(String)
// Try opening resource from environment classloader(s)
if (!environmentClassLoaderDelegationOrder.isEmpty()) {
for (final ClassLoader envClassLoader : environmentClassLoaderDelegationOrder) {
final InputStream inputStream = envClassLoader.getResourceAsStream(path);
if (inputStream != null) {
return inputStream;
}
}
}
// Try opening resource from overridden or added classloader(s)
if (!overriddenOrAddedClassLoaderDelegationOrder.isEmpty()) {
for (final ClassLoader additionalClassLoader : overriddenOrAddedClassLoaderDelegationOrder) {
final InputStream inputStream = additionalClassLoader.getResourceAsStream(path);
if (inputStream != null) {
return inputStream;
}
}
}
// Finally if the above attempts fail, try opening resource from ScanResult.
// This will throw an exception if ScanResult has already been closed (#399).
final ResourceList resourceList = scanResult.getResourcesWithPath(path);
if (resourceList == null || resourceList.isEmpty()) {
return super.getResourceAsStream(path);
} else {
try {
return resourceList.get(0).open();
} catch (final IOException e) {
return null;
}
}
}
}
|
package io.github.classgraph;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import io.github.classgraph.utils.Parser;
import io.github.classgraph.utils.Parser.ParseException;
import io.github.classgraph.utils.TypeUtils;
/** A class reference type signature (called "ClassTypeSignature" in the classfile documentation). */
public class ClassRefTypeSignature extends ClassRefOrTypeVariableSignature {
/** The class name. */
final String className;
/** The class name and suffixes, without type arguments. */
private String fullyQualifiedClassName;
/** The class type arguments. */
private final List<TypeArgument> typeArguments;
/** The class type signature suffix(es), or the empty list if no suffixes. */
private final List<String> suffixes;
/**
* The suffix type arguments, one per suffix, or the empty list if no suffixes. The element value will be the
* empty list if there is no type argument for a given suffix.
*/
private final List<List<TypeArgument>> suffixTypeArguments;
/**
* @param className
* The class name.
* @param typeArguments
* The class type arguments.
* @param suffixes
* The class suffixes (for inner classes)
* @param suffixTypeArguments
* The suffix type arguments.
*/
private ClassRefTypeSignature(final String className, final List<TypeArgument> typeArguments,
final List<String> suffixes, final List<List<TypeArgument>> suffixTypeArguments) {
this.className = className;
this.typeArguments = typeArguments;
this.suffixes = suffixes;
this.suffixTypeArguments = suffixTypeArguments;
}
/**
* Get the name of the base class.
*
* @return The name of the base class.
*/
public String getBaseClassName() {
return className;
}
/**
* Get the name of the class, formed from the base name and any suffixes (suffixes are for inner class nesting,
* and are separated by '$'), but without any type arguments. For example,
* {@code "xyz.Cls<String>.InnerCls<Integer>"} is returned as {@code "xyz.Cls$InnerCls"}. The intent of this
* method is that if you replace '.' with '/', and then add the suffix ".class", you end up with the path of the
* classfile relative to the package root.
*
* <p>
* For comparison, {@link #toString()} uses '.' to separate suffixes, and includes type parameters, whereas this
* method uses '$' to separate suffixes, and does not include type parameters.
*
* @return The fully-qualified name of the class, including suffixes but without type arguments.
*/
public String getFullyQualifiedClassName() {
if (fullyQualifiedClassName == null) {
final StringBuilder buf = new StringBuilder();
buf.append(className);
for (String suffixe : suffixes) {
buf.append('$');
buf.append(suffixe);
}
fullyQualifiedClassName = buf.toString();
}
return fullyQualifiedClassName;
}
/**
* Get any type arguments of the base class.
*
* @return The type arguments for the base class.
*/
public List<TypeArgument> getTypeArguments() {
return typeArguments;
}
/**
* Get any suffixes of the class (typically nested inner class names).
*
* @return The class suffixes (for inner classes).
*/
public List<String> getSuffixes() {
return suffixes;
}
/**
* Get any type arguments for any suffixes of the class, one list per suffix.
*
* @return The type arguments for the inner classes, one list per suffix.
*/
public List<List<TypeArgument>> getSuffixTypeArguments() {
return suffixTypeArguments;
}
@Override
public Class<?> loadClass(final boolean ignoreExceptions) {
return super.loadClass(ignoreExceptions);
}
@Override
public Class<?> loadClass() {
return super.loadClass();
}
/**
* Get the fully qualified class name (used by {@link #getClassInfo()} and {@link #loadClass()}.
*
* @return The fully qualified name of the class.
*/
@Override
protected String getClassName() {
return getFullyQualifiedClassName();
}
/**
* @return The {@link ClassInfo} object for the referenced class, or null if the referenced class was not
* encountered during scanning (i.e. if no ClassInfo object was created for the class during scanning).
* N.B. even if this method returns null, {@link #loadClass()} may be able to load the referenced class
* by name.
*/
@Override
public ClassInfo getClassInfo() {
return super.getClassInfo();
}
@Override
void setScanResult(final ScanResult scanResult) {
super.setScanResult(scanResult);
if (typeArguments != null) {
for (final TypeArgument typeArgument : typeArguments) {
typeArgument.setScanResult(scanResult);
}
}
if (suffixTypeArguments != null) {
for (final List<TypeArgument> list : suffixTypeArguments) {
for (final TypeArgument typeArgument : list) {
typeArgument.setScanResult(scanResult);
}
}
}
}
@Override
void getClassNamesFromTypeDescriptors(final Set<String> classNameListOut) {
classNameListOut.add(className);
classNameListOut.add(getFullyQualifiedClassName());
for (final TypeArgument typeArgument : typeArguments) {
typeArgument.getClassNamesFromTypeDescriptors(classNameListOut);
}
}
@Override
public int hashCode() {
return className.hashCode() + 7 * typeArguments.hashCode() + 15 * suffixes.hashCode();
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof ClassRefTypeSignature)) {
return false;
}
final ClassRefTypeSignature o = (ClassRefTypeSignature) obj;
return o.className.equals(this.className) && o.typeArguments.equals(this.typeArguments)
&& o.suffixes.equals(this.suffixes);
}
@Override
public boolean equalsIgnoringTypeParams(final TypeSignature other) {
if (other instanceof TypeVariableSignature) {
// Compare class type signature to type variable -- the logic for this
// is implemented in TypeVariableSignature, and is not duplicated here
return other.equalsIgnoringTypeParams(this);
}
if (!(other instanceof ClassRefTypeSignature)) {
return false;
}
final ClassRefTypeSignature o = (ClassRefTypeSignature) other;
if (o.suffixes.equals(this.suffixes)) {
return o.className.equals(this.className);
} else {
return o.getFullyQualifiedClassName().equals(this.getFullyQualifiedClassName());
}
}
/**
* Return the class type as a string.
*
* <p>
* For comparison, {@link #getFullyQualifiedClassName()} uses '$' to separate suffixes, and does not include
* type parameters, whereas this method uses '.' to separate suffixes, and does include type parameters.
*/
@Override
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append(className);
if (!typeArguments.isEmpty()) {
buf.append('<');
for (int i = 0; i < typeArguments.size(); i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(typeArguments.get(i).toString());
}
buf.append('>');
}
for (int i = 0; i < suffixes.size(); i++) {
// Use '.' before each suffix in the toString() representation, since that is
// how the class name will be shown in Java, e.g. OuterClass<T>.InnerClass
buf.append('.');
buf.append(suffixes.get(i));
final List<TypeArgument> suffixTypeArgs = suffixTypeArguments.get(i);
if (!suffixTypeArgs.isEmpty()) {
buf.append('<');
for (int j = 0; j < suffixTypeArgs.size(); j++) {
if (j > 0) {
buf.append(", ");
}
buf.append(suffixTypeArgs.get(j).toString());
}
buf.append('>');
}
}
return buf.toString();
}
/**
* Parse a class type signature.
*
* @param parser
* The parser.
* @param definingClassName
* The name of the defining class (for resolving type variables).
* @return The class type signature.
* @throws ParseException
* If the type signature could not be parsed.
*/
static ClassRefTypeSignature parse(final Parser parser, final String definingClassName) throws ParseException {
if (parser.peek() == 'L') {
parser.next();
if (!TypeUtils.getIdentifierToken(parser, /* separator = */ '/', /* separatorReplace = */ '.')) {
throw new ParseException(parser, "Could not parse identifier token");
}
final String className = parser.currToken();
final List<TypeArgument> typeArguments = TypeArgument.parseList(parser, definingClassName);
List<String> suffixes;
List<List<TypeArgument>> suffixTypeArguments;
if (parser.peek() == '.') {
suffixes = new ArrayList<>();
suffixTypeArguments = new ArrayList<>();
while (parser.peek() == '.') {
parser.expect('.');
if (!TypeUtils.getIdentifierToken(parser, /* separator = */ '/',
/* separatorReplace = */ '.')) {
throw new ParseException(parser, "Could not parse identifier token");
}
suffixes.add(parser.currToken());
suffixTypeArguments.add(TypeArgument.parseList(parser, definingClassName));
}
} else {
suffixes = Collections.emptyList();
suffixTypeArguments = Collections.emptyList();
}
parser.expect(';');
return new ClassRefTypeSignature(className, typeArguments, suffixes, suffixTypeArguments);
} else {
return null;
}
}
}
|
package linenux.view;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ListChangeListener;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import linenux.control.ControlUnit;
import linenux.model.Reminder;
import linenux.model.Task;
import linenux.util.ArrayListUtil;
import linenux.util.RemindersListUtil;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.ArrayList;
//@@author A0144915A
public class ExpandableResultBoxController {
public enum UserAction {
SHOW, HIDE
}
@FXML
Button button;
@FXML
TextArea textArea;
private BooleanProperty expanded = new SimpleBooleanProperty(false);
private ControlUnit controlUnit;
private boolean isShowingReminders = true;
private UserAction lastUserAction = UserAction.HIDE;
private Clock clock = Clock.systemDefaultZone();
public void setControlUnit(ControlUnit controlUnit) {
this.controlUnit = controlUnit;
this.controlUnit.getLastCommandResultProperty().addListener((change) -> {
this.setText(this.controlUnit.getLastCommandResultProperty().get().getFeedback());
});
this.renderInitialReminders();
this.controlUnit.getSchedule().getFilteredTaskList().addListener((ListChangeListener<? super ArrayList<Task>>) (change) -> {
this.onFilteredTaskListChange();
});
}
@FXML
private void initialize() {
this.expanded.addListener(change -> {
this.render();
});
}
@FXML
private void toggleExpandedState() {
if (this.expanded.get()) {
this.lastUserAction = UserAction.HIDE;
this.expanded.set(false);
} else {
this.lastUserAction = UserAction.SHOW;
this.expanded.set(true);
}
}
private void render() {
if (this.expanded.get()) {
this.button.setText("Hide");
this.textArea.setPrefHeight(200);
} else {
this.button.setText("Show");
this.textArea.setPrefHeight(0);
}
}
private void setText(String text) {
if (text.trim().contains("\n")) {
this.isShowingReminders = false;
this.expanded.set(true);
this.textArea.setText(text.trim());
} else {
if (this.lastUserAction == UserAction.HIDE) {
this.expanded.set(false);
}
this.isShowingReminders = true;
this.renderReminders();
}
}
private void onFilteredTaskListChange() {
if (this.isShowingReminders) {
this.renderReminders();
}
}
private void renderInitialReminders() {
String formattedReminders = this.formatReminders();
if (!formattedReminders.isEmpty()) {
this.lastUserAction = UserAction.SHOW;
this.isShowingReminders = true;
this.expanded.set(true);
this.renderReminders();
}
}
private String formatReminders() {
LocalDateTime now = LocalDateTime.now(this.clock);
LocalDateTime today = now.withHour(0).withMinute(0).withSecond(0);
ArrayList<Reminder> reminders = new ArrayListUtil.ChainableArrayListUtil<>(this.controlUnit.getSchedule().getFilteredTasks())
.map(Task::getReminders)
.foldr((x, xs) -> {
xs.addAll(x);
return xs;
}, new ArrayList<Reminder>())
.filter(reminder -> today.compareTo(reminder.getTimeOfReminder()) <= 0)
.sortBy(Reminder::getTimeOfReminder)
.value();
return RemindersListUtil.display(reminders);
}
private void renderReminders() {
this.textArea.setText(formatReminders());
}
}
|
package main.java.com.bag.server;
import bftsmart.reconfiguration.util.RSAKeyLoader;
import bftsmart.tom.MessageContext;
import bftsmart.tom.ServiceProxy;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.util.TOMUtil;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoPool;
import main.java.com.bag.instrumentations.ServerInstrumentation;
import main.java.com.bag.operations.IOperation;
import main.java.com.bag.util.Constants;
import main.java.com.bag.util.Log;
import main.java.com.bag.util.storage.NodeStorage;
import main.java.com.bag.util.storage.RelationshipStorage;
import main.java.com.bag.util.storage.SignatureStorage;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public class LocalClusterSlave extends AbstractRecoverable
{
/**
* Name of the location of the global config.
*/
private static final String GLOBAL_CONFIG_LOCATION = "global/config";
/**
* The place the local config file lays. This + the cluster id will contain the concrete cluster config location.
*/
private static final String LOCAL_CONFIG_LOCATION = "local%d/config";
/**
* The wrapper class instance. Used to access the global cluster if possible.
*/
private final ServerWrapper wrapper;
/**
* Checks if this replica is primary in his cluster.
*/
private boolean isPrimary = false;
/**
* The id of the local cluster.
*/
private final int id;
/**
* The id of the primary of this slave.
*/
private int primaryGlobalClusterId = -1;
/**
* The id of the primary of this slave in the local cluster.
*/
private int primaryId = -1;
/**
* The serviceProxy to establish communication with the other replicas.
*/
private final ServiceProxy proxy;
/**
* Queue to catch messages out of order.
*/
private final Map<Long, List<IOperation>> buffer = new TreeMap<>();
/**
* Public constructor used to create a local cluster slave.
*
* @param id its unique id in the local cluster.
* @param wrapper its ordering wrapper.
* @param localClusterId the id of the cluster (the id of the starting primary in the global cluster).
*/
public LocalClusterSlave(final int id, @NotNull final ServerWrapper wrapper, final int localClusterId, final ServerInstrumentation instrumentation)
{
super(id, String.format(LOCAL_CONFIG_LOCATION, localClusterId), wrapper, instrumentation);
this.id = id;
this.wrapper = wrapper;
this.proxy = new ServiceProxy(1000 + id, String.format(LOCAL_CONFIG_LOCATION, localClusterId));
Log.getLogger().info("Turned on local cluster with id: " + id);
}
/**
* Set the local cluster instance to primary.
*
* @param isPrimary true if so.
*/
void setPrimary(final boolean isPrimary)
{
if (isPrimary)
{
primaryId = id;
}
this.isPrimary = isPrimary;
}
/**
* Set the id of the primary global cluster.
*
* @param primaryGlobalClusterId the id.
*/
void setPrimaryGlobalClusterId(final int primaryGlobalClusterId)
{
this.primaryGlobalClusterId = primaryGlobalClusterId;
}
/**
* Check if the local cluster slave is a primary.
*
* @return true if so.
*/
boolean isPrimary()
{
return isPrimary;
}
@Override
public byte[][] appExecuteBatch(final byte[][] bytes, final MessageContext[] messageContexts, final boolean bim)
{
final byte[][] allResults = new byte[bytes.length][];
for (int i = 0; i < bytes.length; ++i)
{
if (messageContexts != null && messageContexts[i] != null)
{
final KryoPool pool = new KryoPool.Builder(super.getFactory()).softReferences().build();
final Kryo kryo = pool.borrow();
final Input input = new Input(bytes[i]);
final String type = kryo.readObject(input, String.class);
if (Constants.COMMIT_MESSAGE.equals(type))
{
final byte[] result = handleReadOnlyCommit(input, kryo);
pool.release(kryo);
allResults[i] = result;
}
else if (Constants.UPDATE_SLAVE.equals(type))
{
final Output output;
Log.getLogger().error("Received update slave message ordered");
output = handleSlaveUpdateMessage(input, new Output(0, 1024), kryo);
Log.getLogger().error("Leaving update slave message ordered");
allResults[i] = output.getBuffer();
output.close();
input.close();
}
else
{
Log.getLogger().error("Return empty bytes for message type: " + type);
allResults[i] = makeEmptyAbortResult();
updateCounts(0, 0, 0, 1);
}
}
else
{
Log.getLogger().error("Received message with empty context!");
allResults[i] = makeEmptyAbortResult();
updateCounts(0, 0, 0, 1);
}
}
return allResults;
}
@Override
public byte[] appExecuteUnordered(final byte[] bytes, final MessageContext messageContext)
{
final KryoPool pool;
final Kryo kryo;
final Input input;
final byte[] returnValue;
try (Output output = new Output(0, 400240))
{
Log.getLogger().info("Received unordered message");
pool = new KryoPool.Builder(getFactory()).softReferences().build();
kryo = pool.borrow();
input = new Input(bytes);
final String reason = kryo.readObject(input, String.class);
switch (reason)
{
case Constants.READ_MESSAGE:
Log.getLogger().info("Received Node read message");
kryo.writeObject(output, Constants.READ_MESSAGE);
handleNodeRead(input, kryo, output, messageContext.getSender());
break;
case Constants.RELATIONSHIP_READ_MESSAGE:
Log.getLogger().info("Received Relationship read message");
kryo.writeObject(output, Constants.READ_MESSAGE);
handleRelationshipRead(input, kryo, output, messageContext.getSender());
break;
case Constants.GET_PRIMARY:
Log.getLogger().info("Received GetPrimary message");
kryo.writeObject(output, Constants.GET_PRIMARY);
handleGetPrimaryMessage(messageContext, output, kryo);
break;
case Constants.COMMIT:
Log.getLogger().info("Received commit message: " + input.getBuffer().length);
final byte[] result = handleReadOnlyCommit(input, kryo);
input.close();
pool.release(kryo);
Log.getLogger().info("Return it to client: " + input.getBuffer().length + ", size: " + result.length);
return result;
case Constants.REGISTER_GLOBALLY_MESSAGE:
Log.getLogger().info("Received register globally message");
handleRegisterGloballyMessage(input, output, messageContext, kryo);
break;
case Constants.UPDATE_SLAVE:
Log.getLogger().info("Received update slave message");
handleSlaveUpdateMessage(input, output, kryo);
input.close();
return new byte[0];
default:
Log.getLogger().error("Incorrect operation sent unordered to the server");
input.close();
return new byte[0];
}
returnValue = output.getBuffer();
Log.getLogger().info("Return it to sender, size: " + returnValue.length);
}
input.close();
pool.release(kryo);
return returnValue;
}
private byte[] handleReadOnlyCommit(final Input input, final Kryo kryo)
{
final Long timeStamp = kryo.readObject(input, Long.class);
return executeReadOnlyCommit(kryo, input, timeStamp);
}
/**
* Check for conflicts and unpack things for conflict handle check.
*
* @param kryo the kryo instance.
* @param input the input.
* @return the response.
*/
public byte[] executeReadOnlyCommit(final Kryo kryo, final Input input, final long timeStamp)
{
//Read the inputStream.
final List readsSetNodeX = kryo.readObject(input, ArrayList.class);
final List readsSetRelationshipX = kryo.readObject(input, ArrayList.class);
final List writeSetX = kryo.readObject(input, ArrayList.class);
//Create placeHolders.
final ArrayList<NodeStorage> readSetNode;
final ArrayList<RelationshipStorage> readsSetRelationship;
final ArrayList<IOperation> localWriteSet;
input.close();
final Output output = new Output(128);
kryo.writeObject(output, Constants.COMMIT_RESPONSE);
try
{
readSetNode = (ArrayList<NodeStorage>) readsSetNodeX;
readsSetRelationship = (ArrayList<RelationshipStorage>) readsSetRelationshipX;
localWriteSet = (ArrayList<IOperation>) writeSetX;
}
catch (final Exception e)
{
Log.getLogger().error("Couldn't convert received data to sets. Returning abort", e);
kryo.writeObject(output, Constants.ABORT);
kryo.writeObject(output, getGlobalSnapshotId());
//Send abort to client and abort
final byte[] returnBytes = output.getBuffer();
output.close();
return returnBytes;
}
if (!ConflictHandler.checkForConflict(super.getGlobalWriteSet(),
super.getLatestWritesSet(),
localWriteSet,
readSetNode,
readsSetRelationship,
timeStamp,
wrapper.getDataBaseAccess(), wrapper.isMultiVersion()))
{
updateCounts(0, 0, 0, 1);
Log.getLogger()
.info("Found conflict, returning abort with timestamp: " + timeStamp + " globalSnapshot at: " + getGlobalSnapshotId() + " and writes: "
+ localWriteSet.size()
+ " and reads: " + readSetNode.size() + " + " + readsSetRelationship.size());
kryo.writeObject(output, Constants.ABORT);
kryo.writeObject(output, getGlobalSnapshotId());
//Send abort to client and abort
final byte[] returnBytes = output.getBuffer();
output.close();
return returnBytes;
}
updateCounts(0, 0, 1, 0);
kryo.writeObject(output, Constants.COMMIT);
kryo.writeObject(output, getGlobalSnapshotId());
final byte[] returnBytes = output.getBuffer();
output.close();
Log.getLogger().info("No conflict found, returning commit with snapShot id: " + getGlobalSnapshotId() + " size: " + returnBytes.length);
return returnBytes;
}
/**
* Check if the primary is correct.
*
* @param input the input.
* @param output the presumed output.
* @param messageContext the message context.
* @param kryo the kryo object.
* @return output obejct with decision.
*/
private Output handleRegisterGloballyMessage(final Input input, final Output output, final MessageContext messageContext, final Kryo kryo)
{
final int oldPrimary = kryo.readObject(input, Integer.class);
final int newPrimary = kryo.readObject(input, Integer.class);
kryo.writeObject(output, Constants.REGISTER_GLOBALLY_REPLY);
if (messageContext.getLeader() == newPrimary)
{
kryo.writeObject(output, true);
}
else
{
kryo.writeObject(output, false);
}
if (messageContext.getLeader() == oldPrimary)
{
Log.getLogger().error("Slave: " + newPrimary + "tried to register as new primary.");
}
return output;
}
/**
* Handles a get primary message.
*
* @param messageContext the message context.
* @param output write info to.
* @param kryo the kryo instance.
* @return sends the primary to the people.
*/
private Output handleGetPrimaryMessage(final MessageContext messageContext, final Output output, final Kryo kryo)
{
if (isPrimary())
{
kryo.writeObject(output, id);
}
if (isPrimary())
{
kryo.writeObject(output, primaryId);
}
return output;
}
@NotNull
private synchronized Output handleSlaveUpdateMessage(final Input input, @NotNull final Output output, final Kryo kryo)
{
//Not required. Is primary already dealt with it.
if (wrapper.getGlobalCluster() != null)
{
kryo.writeObject(output, true);
return output;
}
final String decision = kryo.readObject(input, String.class);
final long snapShotId = kryo.readObject(input, Long.class);
final long lastKey = getGlobalSnapshotId();
Log.getLogger().info("Received update slave message with decision: " + decision);
if (lastKey > snapShotId)
{
Log.getLogger().warn("Throwing away, incoming snapshotId: " + snapShotId + " smaller than existing: " + lastKey);
//Received a message which has been committed in the past already.
kryo.writeObject(output, true);
return output;
}
else if (lastKey == snapShotId)
{
Log.getLogger().warn("Received already committed transaction.");
kryo.writeObject(output, true);
return output;
}
final SignatureStorage storage;
try
{
storage = kryo.readObject(input, SignatureStorage.class);
}
catch (final ClassCastException exp)
{
Log.getLogger().error("Unable to cast to SignatureStorage, something went wrong badly.", exp);
kryo.writeObject(output, false);
return output;
}
final int consensusId = kryo.readObject(input, Integer.class);
final Input messageInput = new Input(storage.getMessage());
kryo.readObject(messageInput, String.class);
kryo.readObject(messageInput, String.class);
kryo.readObject(messageInput, Long.class);
final List writeSet = kryo.readObject(messageInput, ArrayList.class);
List readsSetNodeX = new ArrayList<>();
List readsSetRelationshipX = new ArrayList<>();
if (wrapper.isGloballyVerified())
{
readsSetNodeX = kryo.readObject(messageInput, ArrayList.class);
readsSetRelationshipX = kryo.readObject(messageInput, ArrayList.class);
}
final ArrayList<IOperation> localWriteSet;
ArrayList<NodeStorage> readSetNode = new ArrayList<>();
ArrayList<RelationshipStorage> readsSetRelationship = new ArrayList<>();
messageInput.close();
try
{
localWriteSet = (ArrayList<IOperation>) writeSet;
if (wrapper.isGloballyVerified() && !readsSetNodeX.isEmpty() && !readsSetRelationshipX.isEmpty())
{
readSetNode = (ArrayList<NodeStorage>) readsSetNodeX;
readsSetRelationship = (ArrayList<RelationshipStorage>) readsSetRelationshipX;
}
}
catch (final ClassCastException e)
{
Log.getLogger().error("Couldn't convert received signature message.", e);
kryo.writeObject(output, false);
return output;
}
if (!wrapper.isGloballyVerified())
{
int matchingSignatures = 0;
for (final Map.Entry<Integer, byte[]> entry : storage.getSignatures().entrySet())
{
final RSAKeyLoader rsaLoader = new RSAKeyLoader(entry.getKey(), GLOBAL_CONFIG_LOCATION, false);
try
{
if (!TOMUtil.verifySignature(rsaLoader.loadPublicKey(), storage.getMessage(), entry.getValue()))
{
Log.getLogger().error("Signature of server: " + entry.getKey() + " doesn't match");
Log.getLogger().error(Arrays.toString(storage.getMessage()) + " : " + Arrays.toString(entry.getValue()));
}
else
{
Log.getLogger().info("Signature matches of server: " + entry.getKey());
matchingSignatures++;
}
}
catch (final Exception e)
{
Log.getLogger().error("Unable to load public key on server " + id + " of server: " + entry.getKey(), e);
kryo.writeObject(output, false);
return output;
}
}
if (matchingSignatures < 2)
{
Log.getLogger().error("Something went incredibly wrong. Transaction came without correct signatures from the primary at localCluster: "
+ wrapper.getLocalClusterSlaveId());
kryo.writeObject(output, false);
return output;
}
Log.getLogger().info("All: " + matchingSignatures + " signatures are correct, started to commit now!");
}
//Code to dynamically reconfigure the local cluster!
/*if (getGlobalSnapshotId() == 1000 && id == 2 && localClusterId == 0)
{
Log.getLogger().error("Instantiating new global cluster");
final Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
final Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
wrapper.initNewGlobalClusterInstance();
}
});
t.start();
Thread.sleep(100);
VMServices.main(new String[] {"4", "172.16.52.8", "11340"});
}
catch (final InterruptedException e)
{
Log.getLogger().error("Error instantiating new Replica", e);
}
}
});
t.start();
}*/
if (lastKey + 1 == snapShotId && Constants.COMMIT.equals(decision))
{
if (wrapper.isGloballyVerified() && !ConflictHandler.checkForConflict(super.getGlobalWriteSet(),
super.getLatestWritesSet(),
new ArrayList<>(localWriteSet),
readSetNode,
readsSetRelationship,
snapShotId,
wrapper.getDataBaseAccess(), wrapper.isMultiVersion()))
{
Log.getLogger()
.error("Found conflict, returning abort with timestamp: " + snapShotId + " globalSnapshot at: " + getGlobalSnapshotId() + " and writes: "
+ localWriteSet.size()
+ " and reads: " + readSetNode.size() + " + " + readsSetRelationship.size());
kryo.writeObject(output, false);
return output;
}
final RSAKeyLoader rsaLoader = new RSAKeyLoader(id, GLOBAL_CONFIG_LOCATION, false);
executeCommit(localWriteSet, rsaLoader, id, snapShotId, consensusId);
long requiredKey = lastKey + 1;
while (buffer.containsKey(requiredKey))
{
executeCommit(buffer.remove(requiredKey), rsaLoader, id, snapShotId, consensusId);
requiredKey++;
}
kryo.writeObject(output, true);
return output;
}
buffer.put(snapShotId, localWriteSet);
Log.getLogger().info("Something went wrong, missing a message: " + snapShotId + " with decision: " + decision + " lastKey: " + lastKey + " adding to buffer");
if(buffer.size() % 200 == 0)
{
Log.getLogger().error("Missing more than: " + buffer.size() + " messages, something is broken!" + lastKey);
}
kryo.writeObject(output, true);
return output;
}
@Override
public void putIntoWriteSet(final long currentSnapshot, final List<IOperation> localWriteSet)
{
super.putIntoWriteSet(currentSnapshot, localWriteSet);
setGlobalSnapshotId(currentSnapshot);
}
@Override
void readSpecificData(final Input input, final Kryo kryo)
{
isPrimary = false;
primaryGlobalClusterId = kryo.readObject(input, Integer.class);
}
@Override
public Output writeSpecificData(final Output output, final Kryo kryo)
{
kryo.writeObject(output, primaryGlobalClusterId);
return output;
}
/**
* Send this update to all other replicas.
* @param message the message.
*/
public void propagateUpdate(final byte[] message)
{
proxy.sendMessageToTargets(message, 0, 0, proxy.getViewManager().getCurrentViewProcesses(), TOMMessageType.UNORDERED_REQUEST);
/*while(proxy.invokeUnordered(message) == null)
{
Log.getLogger().error("Slave update failed, no response, trying again!");
}*/
}
}
|
package me.coley.recaf.decompile.cfr;
import me.coley.recaf.config.ConfDecompile;
import me.coley.recaf.control.Controller;
import me.coley.recaf.decompile.Decompiler;
import me.coley.recaf.util.AccessFlag;
import org.benf.cfr.reader.api.CfrDriver;
import org.benf.cfr.reader.util.getopt.OptionDecoderParam;
import org.benf.cfr.reader.util.getopt.OptionsImpl;
import org.benf.cfr.reader.util.getopt.PermittedOptionProvider;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* CFR decompiler implementation.
*
* @author Matt
*/
public class CfrDecompiler extends Decompiler<String> {
/**
* Initialize the decompiler wrapper.
*
* @param controller
* Controller with configuration to pull from and the workspace to pull classes from.
*/
public CfrDecompiler(Controller controller) {
super(controller);
}
@Override
protected Map<String, String> generateDefaultOptions() {
Map<String, String> map = new HashMap<>();
for(PermittedOptionProvider.ArgumentParam<?, ?> param : OptionsImpl.getFactory()
.getArguments()) {
String defaultValue = getOptValue(param);
// Value is conditional based on version, just take the first given default.
if (defaultValue != null && defaultValue.contains("if class"))
defaultValue = defaultValue.substring(0, defaultValue.indexOf(" "));
map.put(param.getName(), defaultValue);
}
ConfDecompile config = getController().config().decompile();
if (config.showSynthetic) {
// CFR doesn't have options against intentional marking of ACC_SYNTHETIC by obfuscators :/
// This will only show ACC_BRIDGE but not ACC_SYNTHETIC
map.put("hidebridgemethods", "false");
// And this, will only show ACC_SYNTHETIC in certain cases so it isn't that useful
// map.put("removeinnerclasssynthetics", "true");
}
return map;
}
@Override
public String decompile(String name) {
ClassSource source = new ClassSource(getController());
SinkFactoryImpl sink = new SinkFactoryImpl();
CfrDriver driver = new CfrDriver.Builder()
.withClassFileSource(source)
.withOutputSink(sink)
.withOptions(getOptions())
.build();
driver.analyse(Collections.singletonList(name));
String decompile = sink.getDecompilation();
if (decompile == null)
return "// ERROR: Failed to decompile '" + name + "'";
return clean(decompile, name);
}
/**
* Remove watermark & oddities from decompilation output.
*
* @param decompilationText
* Decompilation text.
* @param className
* Class name.
*
* @return Decompilation without watermark.
*/
private String clean(String decompilationText, String className) {
// Get rid of header comment
if(decompilationText.startsWith("/*\n * Decompiled with CFR"))
decompilationText = decompilationText.substring(decompilationText.indexOf("*/") + 3);
// JavaParser does NOT like inline comments like this.
decompilationText = decompilationText.replace("/* synthetic */ ", "");
decompilationText = decompilationText.replace("/* bridge */ ", "");
decompilationText = decompilationText.replace("/* enum */ ", "");
decompilationText = decompilationText.replace(" - consider using --renameillegalidents true",
" - recommend switching to table mode");
// Fix inner class names being busted in decompilation text, needs to be "Inner$1"
// instead of "Inner.1", as generated by CFR
String classSimpleName = className.contains("/") ? className.substring(className.lastIndexOf('/') + 1) : className;
if(classSimpleName.contains("$")) {
String incorrectlyDecompiledClassSimpleName = classSimpleName.replace('$', '.');
int indexOfincorrectlyDecompiledClassSimpleName = decompilationText.indexOf(incorrectlyDecompiledClassSimpleName);
if (indexOfincorrectlyDecompiledClassSimpleName == -1) {
// Generated CFR output does not match expectations.
// Don't attempt to fix up matters and lets this pass through
// with an indication that we encountered this challenge.
// with (true) class com.google.gson.internal.$Gson$Types$GenericArrayTypeImpl
// being decompiled by CFR to com.google.gson.internal.$Gson$Types.GenericArrayTypeImpl
// Note that singular dot in there generated by CFR.
decompilationText = "// ERROR: Unable to apply inner class name fixup" + System.lineSeparator() + decompilationText;
return decompilationText;
}
decompilationText = decompilationText.replace(incorrectlyDecompiledClassSimpleName, classSimpleName);
String startText = decompilationText.substring(0, decompilationText.indexOf(classSimpleName));
String startTextCopy = startText;
Set<AccessFlag> allowed = AccessFlag.getApplicableFlags(AccessFlag.Type.CLASS);
for (AccessFlag acc : AccessFlag.values()) {
if (allowed.contains(acc))
continue;
if (startText.contains(acc.getName() + " ")) {
startText = startText.replace(startText,
startText.replace(acc.getCodeFriendlyName() + " ", ""));
}
}
decompilationText = decompilationText.replace(startTextCopy, startText);
}
return decompilationText;
}
/**
* Fetch default value from configuration parameter.
*
* @param param
* Parameter.
*
* @return Default value as string, may be {@code null}.
*/
private String getOptValue(PermittedOptionProvider.ArgumentParam<?, ?> param) {
try {
Field fn = PermittedOptionProvider.ArgumentParam.class.getDeclaredField("fn");
fn.setAccessible(true);
OptionDecoderParam<?, ?> decoder = (OptionDecoderParam<?, ?>) fn.get(param);
return decoder.getDefaultValue();
} catch(ReflectiveOperationException ex) {
throw new IllegalStateException("Failed to fetch default value from Cfr parameter, did" +
" the backend change?");
}
}
}
|
package me.coley.recaf.parse.bytecode;
import me.coley.recaf.parse.bytecode.ast.*;
import me.coley.recaf.parse.bytecode.parser.HandleParser;
import me.coley.recaf.util.*;
import org.objectweb.asm.*;
import org.objectweb.asm.tree.*;
import java.util.*;
import java.util.stream.Collectors;
import static org.objectweb.asm.tree.AbstractInsnNode.*;
/**
* Method instruction disassembler.
*
* @author Matt
*/
public class Disassembler {
private Map<LabelNode, String> labelToName = new HashMap<>();
private List<String> out = new ArrayList<>();
private Set<Integer> paramVariables = new HashSet<>();
private MethodNode method;
private boolean useIndyAlias = true;
private boolean doInsertIndyAlias;
/**
* @param method
* Method to disassemble.
*
* @return Text of method instructions.
*/
public String disassemble(MethodNode method) {
setup(method);
visit(method);
return String.join("\n", out);
}
/**
* @param field
* Field to disassemble.
*
* @return Text of field definition.
*/
public String disassemble(FieldNode field) {
visit(field);
return String.join("\n", out);
}
/**
* @param useIndyAlias
* Flag to determine if lambda handles should be simplified where possible.
*/
public void setUseIndyAlias(boolean useIndyAlias) {
this.useIndyAlias = useIndyAlias;
}
private void setup(MethodNode value) {
this.method = value;
// Validate variable names are unique
splitSameNamedVariables(value);
// Input validation
if (value.instructions == null)
throw new IllegalArgumentException("Method instructions list is null!");
// Generate initial names for the labels
int i = 0;
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(AbstractInsnNode insn : value.instructions.toArray())
if(insn instanceof LabelNode) {
LabelNode lbl = (LabelNode) insn;
labelToName.put(lbl, StringUtil.generateName(alphabet, i++));
} else if (insn instanceof InvokeDynamicInsnNode) {
InvokeDynamicInsnNode indy = (InvokeDynamicInsnNode) insn;
if(useIndyAlias && HandleParser.DEFAULT_HANDLE.equals(indy.bsm))
doInsertIndyAlias = true;
}
// Generate variable names
if(!AccessFlag.isStatic(value.access))
paramVariables.add(0);
// Rename labels for catch ranges
if (value.tryCatchBlocks == null)
return;
i = 1;
int blocks = value.tryCatchBlocks.size();
for (TryCatchBlockNode block : value.tryCatchBlocks)
if (blocks > 1) {
labelToName.put(block.start, "EX_START_" + i);
labelToName.put(block.end, "EX_END_" + i);
labelToName.put(block.handler, "EX_HANDLER_" + i);
i++;
} else {
labelToName.put(block.start, "EX_START");
labelToName.put(block.end, "EX_END");
labelToName.put(block.handler, "EX_HANDLER");
}
}
private void visit(MethodNode value) {
// Visit definition
MethodDefinitionAST def = new MethodDefinitionAST(0, 0,
new NameAST(0, 0, value.name),
new DescAST(0, 0, Type.getMethodType(value.desc).getReturnType().getDescriptor()));
for (AccessFlag flag : AccessFlag.values())
if (flag.getTypes().contains(AccessFlag.Type.METHOD) && (value.access & flag.getMask()) == flag.getMask())
def.getModifiers().add(new DefinitionModifierAST(0, 0, flag.getName().toUpperCase()));
Type[] argTypes = Type.getMethodType(value.desc).getArgumentTypes();
int paramVar = AccessFlag.isStatic(value.access) ? 0 : 1;
for (Type arg : argTypes) {
String name = firstVarByIndex(paramVar);
if (name == null)
name = String.valueOf(paramVar);
def.addArgument(new DefinitionArgAST(0, 0,
new DescAST(0,0,arg.getDescriptor()),
new NameAST(0,0,name)));
paramVar += arg.getSize();
}
out.add(def.print());
// Visit signature
if (value.signature != null)
out.add("SIGNATURE " + value.signature);
// Visit aliases
if(doInsertIndyAlias) {
StringBuilder line = new StringBuilder("ALIAS H_META \"");
visitHandle(line, HandleParser.DEFAULT_HANDLE, true);
line.append('"');
out.add(line.toString());
}
// Visit exceptions
if(value.exceptions != null)
for(String type : value.exceptions)
out.add("THROWS " + type);
// Visit try-catches
if (value.tryCatchBlocks != null)
for (TryCatchBlockNode block : value.tryCatchBlocks) {
String start = labelToName.get(block.start);
String end = labelToName.get(block.end);
String handler = labelToName.get(block.handler);
out.add(String.format("TRY %s %s CATCH(%s) %s", start, end, block.type, handler));
}
// Visit instructions
for(AbstractInsnNode insn : value.instructions.toArray())
appendLine(insn);
}
private void visit(FieldNode value) {
// Visit definition
FieldDefinitionAST def = new FieldDefinitionAST(0, 0,
new NameAST(0, 0, value.name),
new DescAST(0, 0, value.desc));
for (AccessFlag flag : AccessFlag.values())
if (flag.getTypes().contains(AccessFlag.Type.FIELD) && (value.access & flag.getMask()) == flag.getMask())
def.getModifiers().add(new DefinitionModifierAST(0, 0, flag.getName().toUpperCase()));
out.add(def.print());
// Visit signature
if (value.signature != null)
out.add("SIGNATURE " + value.signature);
// Visit default-value
if(value.value != null) {
StringBuilder line = new StringBuilder("VALUE ");
Object o = value.value;
if(o instanceof String) {
String str = o.toString();
str = str.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
line.append('"').append(str).append('"');
} else if(o instanceof Long)
line.append(o).append('L');
else if(o instanceof Double)
line.append(o).append('D');
else if(o instanceof Float)
line.append(o).append('F');
else
line.append(o);
out.add(line.toString());
}
}
private void appendLine(AbstractInsnNode insn) {
StringBuilder line = new StringBuilder(OpcodeUtil.opcodeToName(insn.getOpcode()));
switch(insn.getType()) {
case INSN:
break;
case INT_INSN:
visitIntInsn(line, (IntInsnNode) insn);
break;
case VAR_INSN:
visitVarInsn(line, (VarInsnNode) insn);
break;
case TYPE_INSN:
visitTypeInsn(line, (TypeInsnNode) insn);
break;
case FIELD_INSN:
visitFieldInsn(line, (FieldInsnNode) insn);
break;
case METHOD_INSN:
visitMethodInsn(line, (MethodInsnNode) insn);
break;
case JUMP_INSN:
visitJumpInsn(line, (JumpInsnNode) insn);
break;
case LABEL:
visitLabel(line, (LabelNode) insn);
break;
case LDC_INSN:
visitLdcInsn(line, (LdcInsnNode) insn);
break;
case IINC_INSN:
visitIincInsn(line, (IincInsnNode) insn);
break;
case TABLESWITCH_INSN:
visitTableSwitchInsn(line, (TableSwitchInsnNode) insn);
break;
case LOOKUPSWITCH_INSN:
visitLookupSwitchInsn(line, (LookupSwitchInsnNode) insn);
break;
case MULTIANEWARRAY_INSN:
visitMultiANewArrayInsn(line, (MultiANewArrayInsnNode) insn);
break;
case LINE:
visitLine(line, (LineNumberNode) insn);
break;
case INVOKE_DYNAMIC_INSN:
visitIndyInsn(line, (InvokeDynamicInsnNode) insn);
break;
case FRAME:
// Do nothing
break;
default:
throw new IllegalStateException("Unknown instruction type: " + insn.getType());
}
out.add(line.toString());
}
private void visitIntInsn(StringBuilder line, IntInsnNode insn) {
line.append(' ').append(insn.operand);
}
private void visitVarInsn(StringBuilder line, VarInsnNode insn) {
String name = varInsnToName(insn);
line.append(' ').append(name);
}
private void visitTypeInsn(StringBuilder line, TypeInsnNode insn) {
line.append(' ').append(insn.desc);
}
private void visitFieldInsn(StringBuilder line, FieldInsnNode insn) {
line.append(' ').append(insn.owner).append('.').append(insn.name).append(' ').append(insn.desc);
}
private void visitMethodInsn(StringBuilder line, MethodInsnNode insn) {
line.append(' ').append(insn.owner).append('.').append(insn.name).append(insn.desc);
}
private void visitJumpInsn(StringBuilder line, JumpInsnNode insn) {
String name = name(insn.label);
line.append(' ').append(name);
}
private void visitLabel(StringBuilder line, LabelNode insn) {
// insert modified opcode
line.delete(0, line.length());
// append name
String name = name(insn);
line.append(name).append(":");
}
private void visitLdcInsn(StringBuilder line, LdcInsnNode insn) {
line.append(' ');
if(insn.cst instanceof String) {
String str = insn.cst.toString();
str = str.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
line.append('"').append(str).append('"');
} else if (insn.cst instanceof Long)
line.append(insn.cst).append('L');
else if (insn.cst instanceof Double)
line.append(insn.cst).append('D');
else if (insn.cst instanceof Float)
line.append(insn.cst).append('F');
else
line.append(insn.cst);
}
private void visitIincInsn(StringBuilder line, IincInsnNode insn) {
String name = varInsnToName(insn);
line.append(' ').append(name).append(' ').append(insn.incr);
}
private void visitTableSwitchInsn(StringBuilder line, TableSwitchInsnNode insn) {
line.append(" range[").append(insn.min).append('-').append(insn.max).append(']');
line.append(" labels[");
for(int i = 0; i < insn.labels.size(); i++) {
String name = name(insn.labels.get(i));
line.append(name);
if(i < insn.labels.size() - 1)
line.append(", ");
}
String name = name(insn.dflt);
line.append("] default[").append(name).append(']');
}
private void visitLookupSwitchInsn(StringBuilder line, LookupSwitchInsnNode insn) {
line.append(" mapping[");
for(int i = 0; i < insn.keys.size(); i++) {
String name = name(insn.labels.get(i));
line.append(insn.keys.get(i)).append('=').append(name);
if(i < insn.keys.size() - 1)
line.append(", ");
}
String name = name(insn.dflt);
line.append("] default[").append(name).append(']');
}
private void visitMultiANewArrayInsn(StringBuilder line, MultiANewArrayInsnNode insn) {
line.append(' ').append(insn.desc).append(' ').append(insn.dims);
}
private void visitLine(StringBuilder line, LineNumberNode insn) {
// insert modified opcode
line.delete(0, line.length());
line.append("LINE ");
// append line info
String name = name(insn.start);
line.append(name).append(' ').append(insn.line);
}
private void visitIndyInsn(StringBuilder line, InvokeDynamicInsnNode insn) {
// append nsmr & desc
line.append(' ').append(insn.name).append(' ').append(insn.desc).append(' ');
// append handle
visitHandle(line, insn.bsm, false);
// append args
line.append(" args[");
for(int i = 0; i < insn.bsmArgs.length; i++) {
Object arg = insn.bsmArgs[i];
// int
if (arg instanceof Integer)
line.append(arg);
else if (arg instanceof Float)
line.append(arg).append('F');
else if (arg instanceof Long)
line.append(arg).append('L');
else if (arg instanceof Double)
line.append(arg).append('D');
else if (arg instanceof Type)
line.append(arg);
else if (arg instanceof Handle)
visitHandle(line, (Handle) arg, false);
if(i < insn.bsmArgs.length - 1)
line.append(", ");
}
line.append(']');
}
private void visitHandle(StringBuilder line, Handle handle, boolean dontAlias) {
if(!dontAlias && useIndyAlias && HandleParser.DEFAULT_HANDLE.equals(handle)) {
line.append("${" + HandleParser.DEFAULT_HANDLE_ALIAS + "}");
return;
}
line.append("handle[");
line.append(OpcodeUtil.tagToName(handle.getTag()));
line.append(' ').append(handle.getOwner());
line.append('.').append(handle.getName());
if (handle.getTag() >= Opcodes.H_GETFIELD && handle.getTag() <= Opcodes.H_PUTSTATIC)
line.append(' ');
line.append(handle.getDesc());
line.append(']');
}
/**
* @param insn
* Instruction to disassemble.
*
* @return Text of instruction.
*/
public static String insn(AbstractInsnNode insn) {
Disassembler d = new Disassembler();
// Populate label names if necessary for the given instruction type
int type = insn.getType();
boolean dbg = type == LABEL || type == LINE;
boolean ref = type == JUMP_INSN || type == LOOKUPSWITCH_INSN || type == TABLESWITCH_INSN;
if (dbg || ref) {
int i = 0;
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
AbstractInsnNode tmp = InsnUtil.getFirst(insn);
while(tmp != null) {
if(insn instanceof LabelNode) {
LabelNode lbl = (LabelNode) insn;
d.labelToName.put(lbl, StringUtil.generateName(alphabet, i++));
}
tmp = tmp.getNext();
}
}
// Disassemble the single insn
d.appendLine(insn);
return d.out.get(0);
}
/**
* @param insn
* Variable instruction.
*
* @return {@code null} if no variable with the index exists. Otherwise, the variable's name.
*/
private String varInsnToName(AbstractInsnNode insn) {
int varIndex = ((insn instanceof VarInsnNode) ?
((VarInsnNode) insn).var : ((IincInsnNode) insn).var);
if (method != null && method.localVariables != null) {
int insnPos = InsnUtil.index(insn);
List<LocalVariableNode> list = method.localVariables.stream()
.filter(v -> varIndex == v.index)
.collect(Collectors.toList());
String name = list.stream()
.filter(v -> insnPos >= InsnUtil.index(v.start) - 1 && insnPos <= InsnUtil.index(v.end) + 1)
.map(v -> v.name)
.findFirst().orElse(String.valueOf(varIndex));
// Override slot-0 for non-static methods to ALWAYS be 'this' just in case
// an obfuscator has renamed the variable
if (!AccessFlag.isStatic(method.access) && varIndex == 0)
name = "this";
return name;
}
return String.valueOf(varIndex);
}
private String firstVarByIndex(int index) {
if (method != null && method.localVariables != null) {
return method.localVariables.stream()
.filter(v -> v.index == index)
.min(Comparator.comparingInt(a -> InsnUtil.index(a.start)))
.map(v -> v.name)
.orElse(String.valueOf(index));
}
return String.valueOf(index);
}
private static void splitSameNamedVariables(MethodNode node) {
Map<Integer, LocalVariableNode> indexToVar = new HashMap<>();
Map<Integer, String> indexToName = new HashMap<>();
Map<String, Integer> nameToIndex = new HashMap<>();
boolean changed = false;
for(LocalVariableNode lvn : node.localVariables) {
int index = lvn.index;
String name = lvn.name;
if(indexToName.containsValue(name)) {
// The variable name is NOT unique.
// Set both variables names to <NAME + INDEX>
// Even with 3+ duplicates, this method will give each a unique index-based name.
int otherIndex = nameToIndex.get(name);
LocalVariableNode otherLvn = indexToVar.get(otherIndex);
if (index != otherIndex) {
// Different indices are used
lvn.name = name + index;
otherLvn.name = name + otherIndex;
changed = true;
} else if (!lvn.desc.equals(otherLvn.desc)) {
// Same index but other type?
// Just give it a random name.
// TODO: Naming instead off of types would be better.
lvn.name = name + new Object().hashCode();
changed = true;
}
// Update maps
indexToVar.put(index, lvn);
indexToName.put(index, lvn.name);
nameToIndex.put(lvn.name, index);
} else {
// The variable name is unique.
// Update maps
indexToVar.put(index, lvn);
indexToName.put(index, name);
nameToIndex.put(name, index);
}
}
// Logging
if (changed) {
Log.warn("Automatically updated confusing variable names in method: " + node.name + node.desc);
}
}
private String name(LabelNode label) {
return labelToName.getOrDefault(label, "?");
}
}
|
package microsoft.exchange.webservices.data;
/**
* Represents a base 64 class.
*/
class Base64 {
/** The data. */
static byte[] dataArry;
/** The char set. */
static String strSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZab" +
"cdefghijklmnopqrstuvwxyz0123456789+/";
static {
dataArry = new byte[64];
for (int i = 0; i < 64; i++) {
byte s = (byte)strSet.charAt(i);
dataArry[i] = s;
}
}
/**
* Encodes String.
*
* @param data
* The String to be encoded
* @return String
* encoded value of String
*/
public static String encode(String data) {
return encode(data.getBytes());
}
/**
* Encodes byte array.
*
* @param byteArry
* The value
* @return String
* encoded result of byte array
*/
public static String encode(byte[] byteArry) {
return encode(byteArry, 0, byteArry.length);
}
/**
* Encodes byte array.
*
* @param byteArry The byte array to encode
* @param startIndex The starting index of array
* @param length Length of byte array
* @return String, encoded result of byte array
*/
public static String encode(byte[] byteArry, int startIndex, int length) {
byte[] resArry = new byte[(length + 2) / 3 * 4 + length / 72];
int curState = 0; // Current state
int prev = 0; // previous byte
int presLength = 0; // Current length of bytes decoded
int max = length + startIndex;
int resIndex = 0;
for (int i = startIndex; i < max; i++) {
int x = byteArry[i];
switch (++curState) {
case 1:
resArry[resIndex++] = dataArry[(x >> 2) & 0x3f];
break;
case 2:
resArry[resIndex++] = dataArry[((prev << 4) & 0x30) |
((x >> 4) & 0xf)];
break;
case 3:
resArry[resIndex++] = dataArry[((prev << 2) & 0x3C) |
((x >> 6) & 0x3)];
resArry[resIndex++] = dataArry[x & 0x3F];
curState = 0;
break;
}
prev = x;
if (++presLength >= 72) {
resArry[resIndex++] = (byte)'\n';
presLength = 0;
}
}
switch (curState) {
case 1:
resArry[resIndex++] = dataArry[(prev << 4) & 0x30];
resArry[resIndex++] = (byte)'=';
resArry[resIndex] = (byte)'=';
break;
case 2:
resArry[resIndex++] = dataArry[(prev << 2) & 0x3c];
resArry[resIndex] = (byte)'=';
break;
}
return new String(resArry);
}
/**
* Decodes String value.
*
* @param data Encoded value
* @return The byte array of decoded value
*/
public static byte[] decode(String data) {
int last = 0; // end state
if (data.endsWith("=")) {
last++;
}
if (data.endsWith("==")) {
last++;
}
int decodeLen = (data.length() + 3) / 4 * 3 - last;
byte[] byteArry = new byte[decodeLen];
int index = 0;
try {
for (int i = 0; i < data.length(); i++) {
int valueAt = strSet.indexOf(data.charAt(i));
if (valueAt == -1) {
break;
}
switch (i % 4) {
case 0:
byteArry[index] = (byte)(valueAt << 2);
break;
case 1:
byteArry[index++] |= (byte)((valueAt >> 4) & 0x3);
byteArry[index] = (byte)(valueAt << 4);
break;
case 2:
byteArry[index++] |= (byte)((valueAt >> 2) & 0xf);
byteArry[index] = (byte)(valueAt << 6);
break;
case 3:
byteArry[index++] |= (byte)(valueAt & 0x3f);
break;
}
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
return byteArry;
}
}
|
package net.finmath.marketdata.model;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.finmath.marketdata.calibration.ParameterObjectInterface;
import net.finmath.marketdata.model.curves.CurveInterface;
import net.finmath.marketdata.model.curves.DiscountCurveInterface;
import net.finmath.marketdata.model.curves.ForwardCurveInterface;
import net.finmath.marketdata.model.volatilities.AbstractVolatilitySurface;
import net.finmath.marketdata.model.volatilities.VolatilitySurfaceInterface;
import net.finmath.modelling.DescribedModel;
import net.finmath.modelling.DescribedProduct;
import net.finmath.modelling.InterestRateProductDescriptor;
import net.finmath.modelling.ProductDescriptor;
import net.finmath.modelling.ProductFactory;
import net.finmath.modelling.descriptor.AnalyticModelDescriptor;
import net.finmath.modelling.productfactory.InterestRateAnalyticProductFactory;
/**
* Implements a collection of market data objects (e.g., discount curves, forward curve)
* which provide interpolation of market data or other derived quantities
* ("calibrated curves"). This can be seen as a model to be used in analytic pricing
* formulas - hence this class is termed <code>AnalyticModel</code>.
*
* @author Christian Fries
*/
public class AnalyticModel implements AnalyticModelInterface, Serializable, Cloneable, DescribedModel<AnalyticModelDescriptor> {
private static final long serialVersionUID = 6906386712907555046L;
private final Map<String, CurveInterface> curvesMap = new HashMap<>();
private final Map<String, VolatilitySurfaceInterface> volatilitySurfaceMap = new HashMap<>();
/**
* Create an empty analytic model.
*/
public AnalyticModel() {
}
/**
* Create an analytic model with the given curves.
*
* @param curves The vector of curves.
*/
public AnalyticModel(CurveInterface[] curves) {
for (CurveInterface curve : curves) {
curvesMap.put(curve.getName(), curve);
}
}
/**
* Create an analytic model with the given curves.
*
* @param curves A collection of curves.
*/
public AnalyticModel(Collection<CurveInterface> curves) {
for(CurveInterface curve : curves) {
curvesMap.put(curve.getName(), curve);
}
}
@Override
public CurveInterface getCurve(String name)
{
return curvesMap.get(name);
}
@Override
public Map<String, CurveInterface> getCurves()
{
return Collections.unmodifiableMap(curvesMap);
}
public AnalyticModelInterface addCurve(String name, CurveInterface curve) {
AnalyticModel newModel = clone();
newModel.curvesMap.put(name, curve);
return newModel;
}
public AnalyticModelInterface addCurve(CurveInterface curve) {
AnalyticModel newModel = clone();
newModel.curvesMap.put(curve.getName(), curve);
return newModel;
}
@Override
public AnalyticModelInterface addCurves(CurveInterface... curves) {
AnalyticModel newModel = clone();
for(CurveInterface curve : curves) {
newModel.curvesMap.put(curve.getName(), curve);
}
return newModel;
}
@Override
public AnalyticModelInterface addCurves(Set<CurveInterface> curves) {
AnalyticModel newModel = clone();
for(CurveInterface curve : curves) {
newModel.curvesMap.put(curve.getName(), curve);
}
return newModel;
}
/**
* @deprecated This class will become immutable. Use addCurve instead.
*/
@Override
@Deprecated
public void setCurve(CurveInterface curve)
{
curvesMap.put(curve.getName(), curve);
}
/**
* Set some curves.
*
* @param curves Array of curves to set.
* @deprecated This class will become immutable. Use addCurve instead.
*/
@Deprecated
public void setCurves(CurveInterface[] curves) {
for(CurveInterface curve : curves) {
setCurve(curve);
}
}
@Override
public DiscountCurveInterface getDiscountCurve(String discountCurveName) {
DiscountCurveInterface discountCurve = null;
CurveInterface curve = getCurve(discountCurveName);
if(DiscountCurveInterface.class.isInstance(curve)) {
discountCurve = (DiscountCurveInterface)curve;
}
return discountCurve;
}
@Override
public ForwardCurveInterface getForwardCurve(String forwardCurveName) {
ForwardCurveInterface forwardCurve = null;
CurveInterface curve = getCurve(forwardCurveName);
if(ForwardCurveInterface.class.isInstance(curve)) {
forwardCurve = (ForwardCurveInterface)curve;
}
return forwardCurve;
}
@Override
public VolatilitySurfaceInterface getVolatilitySurface(String name) {
return volatilitySurfaceMap.get(name);
}
public AnalyticModelInterface addVolatilitySurface(VolatilitySurfaceInterface volatilitySurface)
{
AnalyticModel newModel = clone();
newModel.volatilitySurfaceMap.put(volatilitySurface.getName(), volatilitySurface);
return newModel;
}
@Override
public AnalyticModelInterface addVolatilitySurfaces(VolatilitySurfaceInterface... volatilitySurfaces)
{
AnalyticModel newModel = clone();
for(VolatilitySurfaceInterface volatilitySurface : volatilitySurfaces) {
newModel.volatilitySurfaceMap.put(volatilitySurface.getName(), volatilitySurface);
}
return newModel;
}
@Override
public AnalyticModelInterface addVolatilitySurfaces(Set<AbstractVolatilitySurface> volatilitySurfaces) {
AnalyticModel newModel = clone();
for(VolatilitySurfaceInterface volatilitySurface : volatilitySurfaces) {
newModel.volatilitySurfaceMap.put(volatilitySurface.getName(), volatilitySurface);
}
return newModel;
}
/**
* @deprecated This class will become immutable. Use addVolatilitySurface instead.
*/
@Override
@Deprecated
public void setVolatilitySurface(VolatilitySurfaceInterface volatilitySurface)
{
volatilitySurfaceMap.put(volatilitySurface.getName(), volatilitySurface);
}
private void set(Object marketDataObject) {
if(marketDataObject instanceof CurveInterface) {
setCurve((CurveInterface)marketDataObject);
} else if(marketDataObject instanceof VolatilitySurfaceInterface) {
setVolatilitySurface((VolatilitySurfaceInterface)marketDataObject);
} else {
throw new IllegalArgumentException("Provided object is not of supported type.");
}
}
@Override
public AnalyticModel clone()
{
AnalyticModel newModel = new AnalyticModel();
newModel.curvesMap.putAll(curvesMap);
newModel.volatilitySurfaceMap.putAll(volatilitySurfaceMap);
return newModel;
}
@Override
public AnalyticModelInterface getCloneForParameter(Map<ParameterObjectInterface, double[]> curveParameterPairs) throws CloneNotSupportedException {
// Build the modified clone of this model
AnalyticModel modelClone = clone();
// Add modified clones of curves to model clone
if(curveParameterPairs != null) {
for(Entry<ParameterObjectInterface,double[]> curveParameterPair : curveParameterPairs.entrySet()) {
ParameterObjectInterface newCurve = curveParameterPair.getKey().getCloneForParameter(curveParameterPair.getValue());
modelClone.set(newCurve);
}
}
return modelClone;
}
@Override
public String toString() {
return "AnalyticModel: curves=" + curvesMap.keySet() + ", volatilitySurfaces=" + volatilitySurfaceMap.keySet();
}
@Override
public AnalyticModelDescriptor getDescriptor() {
return new AnalyticModelDescriptor(getCurves(), Collections.unmodifiableMap(volatilitySurfaceMap));
}
@Override
public DescribedProduct<? extends ProductDescriptor> getProductFromDescriptor(ProductDescriptor productDescriptor) {
return new InterestRateAnalyticProductFactory().getProductFromDescriptor(productDescriptor);
}
}
|
package net.java.jless.smartcard;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ChainingSmartcard implements Smartcard {
private static final Log log = LogFactory.getLog(ChainingSmartcard.class);
private Smartcard card;
public ChainingSmartcard(Smartcard card) {
this.card = card;
}
public static APDURes transmitChain(Smartcard card, byte[] apdu) throws SmartcardException {
List<byte[]> pieces = chain(apdu, 255);
// log full apdu if chaining
if (pieces.size() > 1 && log.isDebugEnabled()) {
log.debug("chaining (" + apdu.length + " bytes, " + pieces.size() + " pieces) > " + Hex.b2s(apdu));
}
APDURes res = null;
for (byte[] piece : pieces) {
StringBuilder sb = new StringBuilder("apdu (" + piece.length + ") >\n");
Hex.dump(sb, piece, 0, piece.length, " ", 32, false);
log.debug(sb.toString());
long start = System.nanoTime();
res = card.transmit(piece);
long end = System.nanoTime();
long timeTaken = (end - start) / 1000000;
sb = new StringBuilder(timeTaken + " ms - apdu (" + res.getBytes().length + ") <\n");
Hex.dump(sb, res.getBytes(), 0, res.getBytes().length, " ", 32, false);
log.debug(sb.toString());
// if we don't get 0x9000 or 0x61?? then this is error so quit early
if (res.getSW() != 0x9000 && res.getSW1() != 0x61) {
return res;
}
}
return res;
}
/**
* Split apdu into chain pieces with data size 255 or less.
* <pre>
* case 1: |CLA|INS|P1 |P2 | len = 4
* case 2s: |CLA|INS|P1 |P2 |LE | len = 5
* case 3s: |CLA|INS|P1 |P2 |LC |...BODY...| len = 6..260
* case 4s: |CLA|INS|P1 |P2 |LC |...BODY...|LE | len = 7..261
* case 2e: |CLA|INS|P1 |P2 |00 |LE1|LE2| len = 7
* case 3e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...| len = 8..65542
* case 4e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...|LE1|LE2| len =10..65544
* </pre>
* @param apdu apdu
* @param maxDataLen max len of data (usually 255)
* @return list of chained apdus
*/
public static List<byte[]> chain(byte[] apdu, int maxDataLen) {
// shortcut for single apdu (1, 2s, 3s, 4s)
if (apdu.length <= 6 // 1, 2s, 4s
|| apdu[4] != 0) { // 3s, 4s
return Collections.singletonList(apdu);
}
// apdu is extended (2e, 3e, 4e)
int offset = 7; // start of body
// check for 2e
// we can only use last byte of le
if (apdu.length == 7) {
return Collections.singletonList(Buf.cat(Buf.substring(apdu, 0, 4), Buf.substring(apdu, -1, 1)));
}
// must be 3e or 4e
int lc = ((apdu[5] & 0xff) << 8) | (apdu[6] & 0xff);
boolean leIncluded = apdu.length > 7 + lc;
// always at least 1 piece
int chainPieces = lc == 0 ? 1 : (lc + maxDataLen - 1) / maxDataLen;
int pieceLen = maxDataLen;
List<byte[]> result = new ArrayList<byte[]>(chainPieces);
for (int i = 0; i < chainPieces; i++) {
byte[] apduPart;
// all except last
if (i < chainPieces - 1) {
apduPart = new byte[5 + maxDataLen];
apduPart[0] = (byte) (apdu[0] | 0x10);
// last
} else {
pieceLen = lc - (maxDataLen * (chainPieces - 1));
apduPart = new byte[5 + pieceLen + (leIncluded ? 1 : 0)];
apduPart[0] = apdu[0];
apduPart[apduPart.length - 1] = apdu[apdu.length - 1]; // takes care of le
}
apduPart[1] = apdu[1];
apduPart[2] = apdu[2];
apduPart[3] = apdu[3];
apduPart[4] = (byte) pieceLen;
System.arraycopy(apdu, offset, apduPart, 5, pieceLen);
offset += maxDataLen;
result.add(apduPart);
}
return result;
}
/** {@inheritDoc} */
public String getIFDName() { return card.getIFDName(); }
/** {@inheritDoc} */
public APDURes transmit(byte[] apdu) throws SmartcardException {
return transmitChain(card, apdu);
}
/** {@inheritDoc} */
public String transmith(String hexApdu) throws SmartcardException {
return transmit(Hex.s2b(hexApdu)).toString();
}
/** {@inheritDoc} */
public APDURes transmit(int cla, int ins, int p1, int p2, byte[] data, Integer le) throws SmartcardException {
return transmit(SmartcardUtil.formatAPDU(cla, ins, p1, p2, data, le));
}
/** {@inheritDoc} */
public void disconnect(boolean reset) throws SmartcardException {
card.disconnect(reset);
}
}
|
package net.malisis.core.renderer.font;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import net.malisis.core.MalisisCore;
import net.malisis.core.client.gui.GuiRenderer;
import net.malisis.core.renderer.MalisisRenderer;
import net.malisis.core.renderer.element.Face;
import net.malisis.core.renderer.element.Shape;
import net.malisis.core.renderer.element.Vertex;
import net.malisis.core.renderer.element.face.SouthFace;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.opengl.GL11;
import com.google.common.io.Files;
/**
* @author Ordinastie
*
*/
public class MalisisFont
{
public static MalisisFont minecraftFont = new MinecraftFont();
private static Pattern pattern = Pattern.compile("\\{(.*?)}");
/** AWT font used **/
protected Font font;
/** Font render context **/
protected FontRenderContext frc;
/** Options for the font **/
protected FontGeneratorOptions options = FontGeneratorOptions.DEFAULT;
/** Data for each character **/
protected CharData[] charData = new CharData[256];
/** ResourceLocation for the texture **/
protected ResourceLocation textureRl;
/** Size of the texture (width and height) **/
protected int size;
/** Whether the currently drawn text is the shadow part **/
protected boolean drawingShadow = false;
public MalisisFont(File fontFile)
{
this(load(fontFile, FontGeneratorOptions.DEFAULT), null);
}
public MalisisFont(File fontFile, FontGeneratorOptions options)
{
this(load(fontFile, options), options);
}
public MalisisFont(ResourceLocation fontFile)
{
this(load(fontFile, FontGeneratorOptions.DEFAULT), null);
}
public MalisisFont(ResourceLocation fontFile, FontGeneratorOptions options)
{
this(load(fontFile, options), options);
}
public MalisisFont(Font font)
{
this(font, null);
}
public MalisisFont(Font font, FontGeneratorOptions options)
{
this.font = font;
if (font == null)
return;
if (options != null)
this.options = options;
loadCharacterData();
loadTexture(false);
}
public ResourceLocation getResourceLocation()
{
return textureRl;
}
public void generateTexture(boolean debug)
{
this.options.debug = debug;
loadCharacterData();
loadTexture(true);
}
public CharData getCharData(char c)
{
if (c < 0 || c > charData.length)
c = '?';
return charData[c];
}
public Shape getShape(String text, float fontSize)
{
text = processString(text, null);
List<Face> faces = new ArrayList<>();
float offset = 0;
float factor = options.fontSize / fontSize;
for (int i = 0; i < text.length(); i++)
{
CharData cd = getCharData(text.charAt(i));
if (cd.getChar() != ' ')
{
Face f = new SouthFace();
f.factor(cd.getFullWidth(options) / factor, cd.getFullHeight(options) / factor, 0);
f.translate((offset - options.mx) / factor, -options.my / factor, 0);
f.setTexture(cd.getIcon());
faces.add(f);
}
offset += cd.getCharWidth();
}
return new Shape(faces).storeState();
}
//#region Prepare/Clean
protected void prepare(MalisisRenderer renderer, float x, float y, float z, FontRenderOptions fro)
{
boolean isGui = renderer instanceof GuiRenderer;
renderer.next(GL11.GL_QUADS);
Minecraft.getMinecraft().getTextureManager().bindTexture(textureRl);
GL11.glPushMatrix();
GL11.glTranslatef(x, y + (isGui ? 0 : fro.fontScale), z);
if (!isGui)
GL11.glScalef(1 / 9F, -1 / 9F, 1 / 9F);
}
protected void clean(MalisisRenderer renderer, boolean isDrawing)
{
if (isDrawing)
renderer.next();
else
renderer.draw();
if (renderer instanceof GuiRenderer)
Minecraft.getMinecraft().getTextureManager().bindTexture(((GuiRenderer) renderer).getDefaultTexture().getResourceLocation());
GL11.glPopMatrix();
}
protected void prepareShadow(MalisisRenderer renderer)
{
drawingShadow = true;
if (renderer instanceof GuiRenderer)
return;
renderer.next();
GL11.glPolygonOffset(3.0F, 3.0F);
GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
}
protected void cleanShadow(MalisisRenderer renderer)
{
drawingShadow = false;
if (renderer instanceof GuiRenderer)
return;
renderer.next();
GL11.glPolygonOffset(0.0F, 0.0F);
GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
}
protected void prepareLines(MalisisRenderer renderer, FontRenderOptions fro)
{
renderer.next();
renderer.disableTextures();
}
protected void cleanLines(MalisisRenderer renderer)
{
renderer.next();
renderer.enableTextures();
}
//#end Prepare/Clean
public void render(MalisisRenderer renderer, String text, float x, float y, float z, FontRenderOptions fro)
{
if (StringUtils.isEmpty(text))
return;
boolean isDrawing = renderer.isDrawing();
prepare(renderer, x, y, z, fro);
text = processString(text, fro);
if (fro.shadow)
{
prepareShadow(renderer);
drawString(text, fro);
cleanShadow(renderer);
}
drawString(text, fro);
if (hasLines(text, fro))
{
prepareLines(renderer, fro);
if (fro.shadow)
{
prepareShadow(renderer);
drawLines(text, fro);
cleanShadow(renderer);
}
drawLines(text, fro);
cleanLines(renderer);
}
clean(renderer, isDrawing);
}
protected void drawString(String text, FontRenderOptions fro)
{
float x = 0;
float f = fro.fontScale / options.fontSize * 9;
fro.resetStylesLine();
StringWalker walker = new StringWalker(text, this, fro);
walker.applyStyles(true);
while (walker.walk())
{
CharData cd = getCharData(walker.getChar());
drawChar(cd, x, 0, fro);
x += walker.getWidth() * f;
}
}
protected void drawChar(CharData cd, float offsetX, float offsetY, FontRenderOptions fro)
{
if (Character.isWhitespace(cd.getChar()))
return;
Tessellator t = Tessellator.instance;
float factor = fro.fontScale / options.fontSize * 9;
float w = cd.getFullWidth(options) * factor;
float h = cd.getFullHeight(options) * factor;
float i = fro.italic ? fro.fontScale : 0;
if (drawingShadow)
{
offsetX += fro.fontScale;
offsetY += fro.fontScale;
}
t.setColorOpaque_I(drawingShadow ? fro.getShadowColor() : fro.color);
t.setBrightness(Vertex.BRIGHTNESS_MAX);
t.addVertexWithUV(offsetX + i, offsetY, 0, cd.u(), cd.v());
t.addVertexWithUV(offsetX - i, offsetY + h, 0, cd.u(), cd.V());
t.addVertexWithUV(offsetX + w - i, offsetY + h, 0, cd.U(), cd.V());
t.addVertexWithUV(offsetX + w + i, offsetY, 0, cd.U(), cd.v());
}
protected void drawLines(String text, FontRenderOptions fro)
{
float x = 0;
float f = fro.fontScale / options.fontSize * 9;
fro.resetStylesLine();
StringWalker walker = new StringWalker(text, this, fro);
walker.applyStyles(true);
while (walker.walk())
{
if (!walker.isFormatting())
{
CharData cd = getCharData(walker.getChar());
if (fro.underline)
drawLineChar(cd, x, getStringHeight(fro) + fro.fontScale, fro);
if (fro.strikethrough)
drawLineChar(cd, x, getStringHeight(fro) * 0.5F + fro.fontScale, fro);
x += walker.getWidth() * f;
}
}
}
protected void drawLineChar(CharData cd, float offsetX, float offsetY, FontRenderOptions fro)
{
Tessellator t = Tessellator.instance;
float factor = fro.fontScale / options.fontSize * 9;
float w = cd.getFullWidth(options) * factor;
float h = cd.getFullHeight(options) / 9F * factor;
if (drawingShadow)
{
offsetX += fro.fontScale;
offsetY += fro.fontScale;
}
t.setColorOpaque_I(drawingShadow ? fro.getShadowColor() : fro.color);
t.addVertex(offsetX, offsetY, 0);
t.addVertex(offsetX, offsetY + h, 0);
t.addVertex(offsetX + w, offsetY + h, 0);
t.addVertex(offsetX + w, offsetY, 0);
}
//#region String processing
/**
* Processes the passed string by translating it and replacing spacing characters and new lines.<br>
* Keeps the formatting if passed at the beginning of the translation key.
*
* @param str the str
* @return the string
*/
public String processString(String str, FontRenderOptions fro)
{
str = translate(str);
//str = str.replaceAll("\r?\n", "").replaceAll("\t", " ");
return str;
}
private String translate(String str)
{
if (str.indexOf('{') == -1 || str.indexOf('{') >= str.indexOf('}'))
return StatCollector.translateToLocal(str);
StringBuffer output = new StringBuffer();
Matcher matcher = pattern.matcher(str);
while (matcher.find())
matcher.appendReplacement(output, StatCollector.translateToLocal(matcher.group(1)));
matcher.appendTail(output);
return output.toString();
}
private boolean hasLines(String text, FontRenderOptions fro)
{
return fro.underline || fro.strikethrough || text.contains(EnumChatFormatting.UNDERLINE.toString())
|| text.contains(EnumChatFormatting.STRIKETHROUGH.toString());
}
/**
* Clips a string to fit in the specified width. The string is translated before clipping.
*
* @param str the str
* @param width the width
* @return the string
*/
public String clipString(String str, int width)
{
return clipString(str, width, null, false);
}
/**
* Clips a string to fit in the specified width. The string is translated before clipping.
*
* @param str the str
* @param width the width
* @param fro the fro
* @return the string
*/
public String clipString(String str, int width, FontRenderOptions fro)
{
return clipString(str, width, fro, false);
}
/**
* Clips a string to fit in the specified width. The string is translated before clipping.
*
* @param str the str
* @param width the width
* @param fro the fro
* @param appendPeriods the append periods
* @return the string
*/
public String clipString(String str, int width, FontRenderOptions fro, boolean appendPeriods)
{
str = processString(str, fro);
if (appendPeriods)
width -= 4;
int pos = (int) getCharPosition(str, fro, width, 0);
return str.substring(0, pos) + (appendPeriods ? "..." : "");
}
/**
* Gets rendering width of a string.
*
* @param str the str
* @return the string width
*/
public float getStringWidth(String str)
{
return getStringWidth(str, null);
}
/**
* Gets rendering width of a string according to fontScale.
*
* @param str the str
* @param fro the fro
* @param start the start
* @param end the end
* @return the string width
*/
public float getStringWidth(String str, FontRenderOptions fro, int start, int end)
{
if (start > end)
return 0;
if (fro != null && !fro.disableECF)
str = EnumChatFormatting.getTextWithoutFormattingCodes(str);
if (StringUtils.isEmpty(str))
return 0;
str = processString(str, fro);
return (float) font.getStringBounds(str, frc).getWidth() / options.fontSize * (fro != null ? fro.fontScale : 1) * 9;
}
public float getStringWidth(String str, FontRenderOptions fro)
{
if (StringUtils.isEmpty(str))
return 0;
return getStringWidth(str, fro, 0, 0);
}
/**
* Gets the rendering height of strings.
*
* @return the string height
*/
public float getStringHeight()
{
return getStringHeight(null);
}
/**
* Gets the rendering height of strings according to fontscale.
*
* @param fro the fro
* @return the string height
*/
public float getStringHeight(FontRenderOptions fro)
{
return (fro != null ? fro.fontScale : 1) * 9;
}
/**
* Gets the max string width.
*
* @param strings the strings
* @return the max string width
*/
public float getMaxStringWidth(List<String> strings)
{
return getMaxStringWidth(strings, null);
}
/**
* Gets max rendering width of an array of string.
*
* @param strings the strings
* @param fro the fro
* @return the max string width
*/
public float getMaxStringWidth(List<String> strings, FontRenderOptions fro)
{
float width = 0;
for (String str : strings)
width = Math.max(width, getStringWidth(str, fro));
return width;
}
/**
* Gets the rendering width of a char.
*
* @param c the c
* @return the char width
*/
public float getCharWidth(char c)
{
return getCharWidth(c, null);
}
/**
* Gets the rendering width of a char with the specified fontScale.
*
* @param c the c
* @param fro the fro
* @return the char width
*/
public float getCharWidth(char c, FontRenderOptions fro)
{
if (c == '\r' || c == '\n')
return 0;
if (c == '\t')
return getCharWidth(' ', fro) * 4;
return getCharData(c).getCharWidth() / options.fontSize * (fro != null ? fro.fontScale : 1) * 9;
}
/**
* Determines the character for a given X coordinate.
*
* @param str the str
* @param fro the fro
* @param position the position
* @param charOffset the char offset
* @return position
*/
public float getCharPosition(String str, FontRenderOptions fro, int position, int charOffset)
{
if (StringUtils.isEmpty(str))
return 0;
str = processString(str, fro);
float fx = position / (fro != null ? fro.fontScale : 1); //factor the position instead of the char widths
StringWalker walker = new StringWalker(str, this, fro);
walker.startIndex(charOffset);
walker.skipChars(true);
return walker.walkTo(fx);
}
/**
* Splits the string in multiple lines to fit in the specified maxWidth.
*
* @param text the text
* @param maxWidth the max width
* @return list of lines that won't exceed maxWidth limit
*/
public List<String> wrapText(String text, int maxWidth)
{
return wrapText(text, maxWidth, null);
}
/**
* Splits the string in multiple lines to fit in the specified maxWidth using the specified fontScale.
*
* @param str the str
* @param maxWidth the max width
* @param fro the fro
* @return list of lines that won't exceed maxWidth limit
*/
public List<String> wrapText(String str, int maxWidth, FontRenderOptions fro)
{
List<String> lines = new ArrayList<>();
String[] texts = str.split("\r?(?<=\n)");
if (texts.length > 1)
{
for (String t : texts)
lines.addAll(wrapText(t, maxWidth, fro));
return lines;
}
StringBuilder line = new StringBuilder();
StringBuilder word = new StringBuilder();
//FontRenderOptions fro = new FontRenderOptions();
maxWidth -= 4;
maxWidth /= (fro != null ? fro.fontScale : 1); //factor the position instead of the char widths
float lineWidth = 0;
float wordWidth = 0;
str = processString(str, fro);
StringWalker walker = new StringWalker(str, this, fro);
walker.skipChars(false);
walker.applyStyles(false);
while (walker.walk())
{
char c = walker.getChar();
lineWidth += walker.getWidth();
wordWidth += walker.getWidth();
// if (walker.isFormatting())
// word.append(walker.getFormatting());
// continue;
// else
word.append(c);
//we just ended a new word, add it to the current line
if (c == ' ' || c == '-' || c == '.')
{
line.append(word);
word.setLength(0);
wordWidth = 0;
}
if (lineWidth >= maxWidth)
{
//the first word on the line is too large, split anyway
if (line.length() == 0)
{
line.append(word);
word.setLength(0);
wordWidth = 0;
}
//make a new line
lines.add(line.toString());
line.setLength(0);
lineWidth = wordWidth;
}
}
line.append(word);
lines.add(line.toString());
return lines;
}
//#end String processing
//#region Load font
protected void loadCharacterData()
{
frc = new FontRenderContext(null, true, true);
float totalWidth = 0;
for (char c = 0; c < 256; c++)
{
String s = "" + c;
LineMetrics lm = font.getLineMetrics(s, frc);
Rectangle2D bounds = font.getStringBounds(s, frc);
CharData cd = new CharData(c, lm.getAscent(), (float) bounds.getWidth(), options.fontSize);
charData[c] = cd;
totalWidth += cd.getFullWidth(options);
}
int split = 1;
while (totalWidth / split > options.fontSize * split)
split++;
//size = (int) Math.max(totalWidth / (split - 1), options.fontSize * (split - 1));
size = roundUp((int) totalWidth / (split - 1));
}
protected int roundUp(int n)
{
int r = n - 1;
r |= r >> 1;
r |= r >> 2;
r |= r >> 4;
r |= r >> 8;
r |= r >> 16;
return r + 1;
}
protected void loadTexture(boolean forceGenerate)
{
File textureFile = new File("fonts/" + font.getName() + ".png");
File uvFile = new File("fonts/" + font.getName() + ".bin");
BufferedImage img;
if (!textureFile.exists() || !uvFile.exists() || forceGenerate)
{
MalisisCore.log.info("Generating files for " + font.getName());
img = new FontGenerator(font, charData, options).generate(size, textureFile, uvFile);
}
else
{
MalisisCore.log.info("Loading texture and data for " + font.getName());
img = readTextureFile(textureFile);
readUVFile(uvFile);
}
if (img == null)
return;
if (textureRl != null)
Minecraft.getMinecraft().getTextureManager().deleteTexture(textureRl);
DynamicTexture dynTex = new DynamicTexture(img);
textureRl = Minecraft.getMinecraft().getTextureManager().getDynamicTextureLocation(font.getName(), dynTex);
}
protected BufferedImage readTextureFile(File textureFile)
{
try
{
BufferedImage img = ImageIO.read(textureFile);
size = img.getWidth();
return img;
}
catch (IOException e)
{
MalisisCore.log.error("Failed to read font texture.", e);
}
return null;
}
protected void readUVFile(File uvFile)
{
int i = 0;
try
{
for (String str : Files.readLines(uvFile, StandardCharsets.UTF_8))
{
String[] split = str.split(";");
CharData cd = charData[i++];
cd.setUVs(Float.parseFloat(split[1]), Float.parseFloat(split[2]), Float.parseFloat(split[3]), Float.parseFloat(split[4]));
}
}
catch (IOException | NumberFormatException e)
{
MalisisCore.log.error("Failed to read font data. (Line " + i + " (" + (char) i + ")", e);
}
}
//#end Load font
//#region Font load
public static Font load(ResourceLocation rl, FontGeneratorOptions options)
{
try
{
return load(Minecraft.getMinecraft().getResourceManager().getResource(rl).getInputStream(), options);
}
catch (IOException e)
{
MalisisCore.log.error("[MalisiFont] Couldn't load font from ResourceLocation.", e);
return null;
}
}
public static Font load(File file, FontGeneratorOptions options)
{
try
{
return load(new FileInputStream(file), options);
}
catch (FileNotFoundException e)
{
MalisisCore.log.error("[MalisiFont] Couldn't load font from File.", e);
return null;
}
}
public static Font load(InputStream is, FontGeneratorOptions options)
{
try
{
Font font = Font.createFont(options.fontType, is);
return font.deriveFont(options.fontSize);
}
catch (IOException | FontFormatException e)
{
MalisisCore.log.error("[MalisiFont] Couldn't load font from InputStream.", e);
return null;
}
}
//#end Font load
}
|
package net.timbusproject.extractors.pojo;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.osgi.service.log.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;
import java.util.Scanner;
public class CallBack {
@Autowired
LogService log;
private String fromMail;
private String smtp;
private String port;
private String password;
private String socketFactoryClass;
private String mailAuth;
public CallBack() {}
public synchronized void doCallBack(RequestExtractionList extractionList) throws URISyntaxException, IOException {
CallBackInfo info = extractionList.getCallbackInfo();
if (info == null)
System.out.println("No callback information provided");
else {
if (info.getMails() != null) {
setMailConfiguration();
for (String a : info.getMails()) {
System.out.println("Email adress is: " + a);
if (isValidEmailAddress(a)) {
sendEmail(a, "End of extraction request",
"The extractions were completed. Please, check out /extractors/api/requests/ to view the results");
System.out.println("Sent email: " + a);
}
}
} else
System.out.println("No e-mail adress(es) provided");
if (info.getEndPoints() != null) {
for (String a : info.getEndPoints()) {
System.out.println("Sending GET request to: " + a);
String uri = a;
if (!uri.startsWith("http:
uri = "http://" + uri;
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0,false));
HttpResponse response = httpClient.execute(new HttpGet(uri));
System.out.println("Sent GET request to " + uri);
System.out.println("Endpoint " + a + " says: " + response.getStatusLine());
}
} else
System.out.println("No endpoints provided");
}
}
private boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
if (result)
System.out.println("The e-mail " + email + " adress is valid.");
else
System.out.println("The e-mail " + email + " adress is not valid");
return result;
}
public void sendEmail(String to, String subject, String body) {
final String fromUser = fromMail;
final String passUser = password;
Properties props = new Properties();
props.put("mail.smtp.host", smtp);
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", socketFactoryClass);
props.put("mail.smtp.auth", mailAuth);
props.put("mail.smtp.port", port);
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromUser, passUser);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromUser));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public void setMailConfiguration() {
Scanner s = new Scanner(CallBack.class.getResourceAsStream("/default/callback"));
s.findInLine("mail:");
fromMail = s.nextLine().trim().toLowerCase();
while (s.hasNextLine()) {
switch (s.next().trim().replace(":", "")) {
case "smtp":
smtp = s.nextLine().trim();
break;
case "password":
password = s.nextLine().trim();
break;
case "port":
port = s.nextLine().trim();
break;
case "socketfactoryclass":
socketFactoryClass = s.nextLine().trim();
break;
case "mailauthentication":
mailAuth = s.nextLine().trim();
break;
default:
s.nextLine();
break;
}
}
}
}
|
package nl.hsac.fitnesse.fixture.slim;
import nl.hsac.fitnesse.fixture.util.JsonPathHelper;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import java.util.List;
/**
* Fixture to make Http calls and interpret the result as JSON.
*/
public class JsonHttpTest extends HttpTest {
public boolean postValuesAsJsonTo(String serviceUrl) {
return postToImpl(jsonEncodeCurrentValues(), serviceUrl);
}
public boolean putValuesAsJsonTo(String serviceUrl) {
return putToImpl(jsonEncodeCurrentValues(), serviceUrl);
}
protected String jsonEncodeCurrentValues() {
return new JSONObject(getCurrentValues()).toString();
}
@Override
protected String formatValue(String value) {
return getEnvironment().getHtmlForJson(value);
}
public Object jsonPath(String path) {
String responseString = getResponseBody();
String jsonPath = getPathExpr(path);
return getPathHelper().getJsonPath(responseString, jsonPath);
}
public int jsonPathCount(String path) {
List<Object> all = getAllMatches(path);
return all.size();
}
protected List<Object> getAllMatches(String path) {
String responseString = getResponseBody();
String jsonPath = getPathExpr(path);
return getPathHelper().getAllJsonPath(responseString, jsonPath);
}
protected String getResponseBody() {
String responseString = getResponse().getResponse();
if (StringUtils.isEmpty(responseString)) {
throw new SlimFixtureException(false, "No response body available");
}
return responseString;
}
/**
* Gets a HTML list with all matches to the supplied JsonPath.
* @param expr expression to evaluate.
* @return list containing all results of expression evaluation against last response received, null if there were no matches.
* @throws RuntimeException if no valid response was available or Json Path could not be evaluated.
*/
public String allJsonPathMatches(String expr) {
String result = null;
List<Object> allJsonPath = getAllMatches(expr);
if (allJsonPath != null && !allJsonPath.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("<div><ul>");
for (Object match : allJsonPath) {
sb.append("<li>");
sb.append(match);
sb.append("</li>");
}
sb.append("</ul></div>");
result = sb.toString();
}
return result;
}
/**
* Update a value in a the response by supplied jsonPath
* @param path the jsonPath to locate the key whose value needs changing
* @param value the new value to set
*/
public void setJsonPathTo(String path, String value) {
String jsonStr = getResponseBody();
String jsonPath = getPathExpr(path);
String newResponse = getPathHelper().updateJsonPathWithValue(jsonStr, jsonPath, value);
getResponse().setResponse(newResponse);
}
protected String getPathExpr(String path) {
String jsonPath = path;
if (!path.startsWith("$")) {
if (path.startsWith("[") || path.startsWith(".")) {
jsonPath = "$" + path;
} else {
jsonPath = "$." + path;
}
}
return jsonPath;
}
@Override
protected String urlEncode(String str) {
String strNoSpaces = str.replace(" ", "+");
return super.urlEncode(strNoSpaces);
}
protected JsonPathHelper getPathHelper() {
return getEnvironment().getJsonPathHelper();
}
}
|
package org.ambraproject.wombat.model;
import com.google.common.collect.ImmutableList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class SearchFilter {
private final ImmutableList<SearchFilterItem> searchFilterResult;
private Set<SearchFilterItem> activeFilterItems;
private Set<SearchFilterItem> inactiveFilterItems;
private final String filterTypeMapKey;
public SearchFilter(List<SearchFilterItem> searchFilterResult, String filterTypeMapKey) {
this.searchFilterResult = ImmutableList.copyOf(searchFilterResult);
this.filterTypeMapKey = filterTypeMapKey;
}
public List<SearchFilterItem> getSearchFilterResult() {
return searchFilterResult;
}
public String getFilterTypeMapKey() {
return filterTypeMapKey;
}
public Set<SearchFilterItem> getActiveFilterItems() {
return activeFilterItems;
}
public Set<SearchFilterItem> getInactiveFilterItems() {
return inactiveFilterItems;
}
public void setActiveAndInactiveFilterItems(List<String> filterDisplayNames) {
this.activeFilterItems = getSearchFilterResult().stream()
.filter((SearchFilterItem filterItem) -> isFilterItemActive(filterDisplayNames, filterItem))
.collect(Collectors.toCollection(LinkedHashSet::new));
this.inactiveFilterItems = getSearchFilterResult().stream()
.filter((SearchFilterItem filterItem) -> isFilterItemInactive(filterDisplayNames, filterItem))
.collect(Collectors.toCollection(LinkedHashSet::new));
}
private boolean isFilterItemActive(List<String> filterDisplayNames,
SearchFilterItem searchFilterItem) {
return filterDisplayNames.stream()
.anyMatch(filterDisplayName ->
filterDisplayName.equalsIgnoreCase(searchFilterItem.getFilterValue()));
}
private boolean isFilterItemInactive(List<String> filterDisplayNames,
SearchFilterItem searchFilterItem) {
return filterDisplayNames.stream()
.noneMatch(filterDisplayName ->
filterDisplayName.equalsIgnoreCase(searchFilterItem.getFilterValue()));
}
}
|
package org.freeswitch.esl.client.internal;
import io.netty.channel.Channel;
import org.freeswitch.esl.client.transport.CommandResponse;
import org.freeswitch.esl.client.transport.SendMsg;
import org.freeswitch.esl.client.transport.event.EslEvent;
import org.freeswitch.esl.client.transport.message.EslMessage;
import java.util.concurrent.CompletableFuture;
import static com.google.common.base.Preconditions.*;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.base.Throwables.propagate;
import static com.google.common.util.concurrent.Futures.getUnchecked;
import static org.freeswitch.esl.client.internal.IModEslApi.EventFormat.*;
public class Context implements IModEslApi {
private final AbstractEslClientHandler handler;
private final Channel channel;
public Context(Channel channel, AbstractEslClientHandler clientHandler) {
this.handler = clientHandler;
this.channel = channel;
}
@Override
public boolean canSend() {
return channel != null && channel.isActive();
}
/**
* Sends a mod_event_socket command to FreeSWITCH server and blocks, waiting for an immediate response from the
* server.
* <p/>
* The outcome of the command from the server is returned in an {@link org.freeswitch.esl.client.transport.message.EslMessage} object.
*
* @param command a mod_event_socket command to send
* @return an {@link org.freeswitch.esl.client.transport.message.EslMessage} containing command results
*/
public EslMessage sendCommand(String command) {
checkArgument(!isNullOrEmpty(command), "command cannot be null or empty");
try {
return getUnchecked(handler.sendApiSingleLineCommand(channel, command.toUpperCase().trim()));
} catch (Throwable t) {
throw propagate(t);
}
}
/**
* Sends a FreeSWITCH API command to the server and blocks, waiting for an immediate response from the
* server.
* <p/>
* The outcome of the command from the server is returned in an {@link org.freeswitch.esl.client.transport.message.EslMessage} object.
*
* @param command API command to send
* @param arg command arguments
* @return an {@link org.freeswitch.esl.client.transport.message.EslMessage} containing command results
*/
@Override
public EslMessage sendApiCommand(String command, String arg) {
checkArgument(!isNullOrEmpty(command), "command cannot be null or empty");
try {
final StringBuilder sb = new StringBuilder();
sb.append("api ").append(command);
if (!isNullOrEmpty(arg)) {
sb.append(' ').append(arg);
}
return getUnchecked(handler.sendApiSingleLineCommand(channel, sb.toString()));
} catch (Throwable t) {
throw propagate(t);
}
}
/**
* Submit a FreeSWITCH API command to the server to be executed in background mode. A synchronous
* response from the server provides a UUID to identify the job execution results. When the server
* has completed the job execution it fires a BACKGROUND_JOB Event with the execution results.<p/>
* Note that this Client must be subscribed in the normal way to BACKGROUND_JOB Events, in order to
* receive this event.
*
* @param command API command to send
* @param arg command arguments
* @return String Job-UUID that the server will tag result event with.
*/
@Override
public CompletableFuture<EslEvent> sendBackgroundApiCommand(String command, String arg) {
checkArgument(!isNullOrEmpty(command), "command cannot be null or empty");
final StringBuilder sb = new StringBuilder();
sb.append("bgapi ").append(command);
if (!isNullOrEmpty(arg)) {
sb.append(' ').append(arg);
}
return handler.sendBackgroundApiCommand(channel, sb.toString());
}
/**
* Set the current event subscription for this connection to the server. Examples of the events
* argument are:
* <pre>
* ALL
* CHANNEL_CREATE CHANNEL_DESTROY HEARTBEAT
* CUSTOM conference::maintenance
* CHANNEL_CREATE CHANNEL_DESTROY CUSTOM conference::maintenance sofia::register sofia::expire
* </pre>
* Subsequent calls to this method replaces any previous subscriptions that were set.
* </p>
* Note: current implementation can only process 'plain' events.
*
* @param format can be { plain | xml }
* @param events { all | space separated list of events }
* @return a {@link org.freeswitch.esl.client.transport.CommandResponse} with the server's response.
*/
@Override
public CommandResponse setEventSubscriptions(EventFormat format, String events) {
// temporary hack
checkState(format.equals(PLAIN), "Only 'plain' event format is supported at present");
try {
final StringBuilder sb = new StringBuilder();
sb.append("event ").append(format.toString());
if (!isNullOrEmpty(events)) {
sb.append(' ').append(events);
}
final EslMessage response = getUnchecked(handler.sendApiSingleLineCommand(channel, sb.toString()));
return new CommandResponse(sb.toString(), response);
} catch (Throwable t) {
throw propagate(t);
}
}
/**
* Cancel any existing event subscription.
*
* @return a {@link CommandResponse} with the server's response.
*/
@Override
public CommandResponse cancelEventSubscriptions() {
try {
final EslMessage response = getUnchecked(handler.sendApiSingleLineCommand(channel, "noevents"));
return new CommandResponse("noevents", response);
} catch (Throwable t) {
throw propagate(t);
}
}
@Override
public CommandResponse addEventFilter(String eventHeader, String valueToFilter) {
checkArgument(!isNullOrEmpty(eventHeader), "eventHeader cannot be null or empty");
try {
final StringBuilder sb = new StringBuilder();
sb.append("filter ").append(eventHeader);
if (!isNullOrEmpty(valueToFilter)) {
sb.append(' ').append(valueToFilter);
}
final EslMessage response = getUnchecked(handler.sendApiSingleLineCommand(channel, sb.toString()));
return new CommandResponse(sb.toString(), response);
} catch (Throwable t) {
throw propagate(t);
}
}
/**
* Delete an event filter from the current set of event filters on this connection. See
*
* @param eventHeader to remove
* @param valueToFilter to remove
* @return a {@link CommandResponse} with the server's response.
*/
@Override
public CommandResponse deleteEventFilter(String eventHeader, String valueToFilter) {
checkArgument(!isNullOrEmpty(eventHeader), "eventHeader cannot be null or empty");
try {
final StringBuilder sb = new StringBuilder();
sb.append("filter delete ").append(eventHeader);
if (!isNullOrEmpty(valueToFilter)) {
sb.append(' ').append(valueToFilter);
}
final EslMessage response = getUnchecked(handler.sendApiSingleLineCommand(channel, sb.toString()));
return new CommandResponse(sb.toString(), response);
} catch (Throwable t) {
throw propagate(t);
}
}
/**
* Send a {@link SendMsg} command to FreeSWITCH. This client requires that the {@link SendMsg}
* has a call UUID parameter.
*
* @param sendMsg a {@link SendMsg} with call UUID
* @return a {@link CommandResponse} with the server's response.
*/
@Override
public CommandResponse sendMessage(SendMsg sendMsg) {
checkNotNull(sendMsg, "sendMsg cannot be null");
try {
final EslMessage response = getUnchecked(handler.sendApiMultiLineCommand(channel, sendMsg.getMsgLines()));
return new CommandResponse(sendMsg.toString(), response);
} catch (Throwable t) {
throw propagate(t);
}
}
/**
* Enable log output.
*
* @param level using the same values as in console.conf
* @return a {@link CommandResponse} with the server's response.
*/
@Override
public CommandResponse setLoggingLevel(LoggingLevel level) {
try {
final StringBuilder sb = new StringBuilder();
sb.append("log ").append(level.toString());
final EslMessage response = getUnchecked(handler.sendApiSingleLineCommand(channel, sb.toString()));
return new CommandResponse(sb.toString(), response);
} catch (Throwable t) {
throw propagate(t);
}
}
/**
* Disable any logging previously enabled with setLogLevel().
*
* @return a {@link CommandResponse} with the server's response.
*/
@Override
public CommandResponse cancelLogging() {
try {
final EslMessage response = getUnchecked(handler.sendApiSingleLineCommand(channel, "nolog"));
return new CommandResponse("nolog", response);
} catch (Throwable t) {
throw propagate(t);
}
}
public void closeChannel() {
try {
if(channel != null && channel.isOpen())
channel.close();
} catch (Throwable t) {
throw propagate(t);
}
}
}
|
package org.graphwalker.core.machine;
import org.graphwalker.core.generator.NoPathFoundException;
import org.graphwalker.core.model.Action;
import org.graphwalker.core.model.Element;
import org.graphwalker.core.model.Vertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.util.*;
import static org.graphwalker.core.model.Edge.RuntimeEdge;
import static org.graphwalker.core.model.Vertex.RuntimeVertex;
/**
* @author Nils Olsson
*/
public final class SimpleMachine extends ObservableMachine {
private static final Logger logger = LoggerFactory.getLogger(SimpleMachine.class);
private final List<ExecutionContext> contexts = new ArrayList<>();
private ExecutionContext currentContext;
public SimpleMachine(ExecutionContext context) {
this(Arrays.asList(context));
}
public SimpleMachine(List<ExecutionContext> contexts) {
this.contexts.addAll(contexts);
this.currentContext = contexts.get(0);
}
@Override
public Context getNextStep() {
MDC.put("trace", UUID.randomUUID().toString());
currentContext.getProfiler().stop();
walk(currentContext);
currentContext.getProfiler().start();
execute(currentContext.getCurrentElement());
return currentContext;
}
private void walk(ExecutionContext context) {
if (null == context.getCurrentElement()) {
if (null == context.getNextElement()) {
throw new NoPathFoundException("No Start element defined");
}
context.setCurrentElement(context.getNextElement());
} else {
if (isVertex(currentContext.getCurrentElement())) {
RuntimeVertex vertex = (RuntimeVertex)currentContext.getCurrentElement();
if (vertex.hasSharedState() && hasPossibleSharedStates(vertex)) {
List<SharedStateTupel> candidates = getPossibleSharedStates(vertex.getSharedState());
// TODO: If we need other way of determine the next state, we should have some interface for this
Random random = new Random(System.nanoTime());
SharedStateTupel candidate = candidates.get(random.nextInt(candidates.size()));
if (!candidate.getVertex().equals(currentContext.getCurrentElement())) {
candidate.context.setCurrentElement(candidate.getVertex());
currentContext = candidate.context;
} else {
context.getPathGenerator().getNextStep(context);
}
} else {
context.getPathGenerator().getNextStep(context);
}
} else {
context.getPathGenerator().getNextStep(context);
}
}
setChanged();
notifyObservers(context.getCurrentElement());
}
private boolean isVertex(Element element) {
return element instanceof RuntimeVertex;
}
private boolean hasPossibleSharedStates(RuntimeVertex vertex) {
return null != vertex.getSharedState() && 0 < getPossibleSharedStates(vertex.getSharedState()).size();
}
private List<SharedStateTupel> getPossibleSharedStates(String sharedState) {
List<SharedStateTupel> sharedStates = new ArrayList<>();
for (ExecutionContext context: contexts) {
for (RuntimeVertex vertex: context.getModel().getSharedStates(sharedState)) {
if (context.getPathGenerator().hasNextStep(context)) {
if ( !context.getModel().getOutEdges(vertex).isEmpty() ) {
sharedStates.add(new SharedStateTupel(context, vertex));
}
}
}
}
return sharedStates;
}
@Override
public boolean hasNextStep() {
MDC.put("trace", UUID.randomUUID().toString());
for (ExecutionContext context: contexts) {
if (hasNextStep(context)) {
return true;
}
}
return false;
}
private boolean hasNextStep(ExecutionContext context) {
return context.getPathGenerator().hasNextStep(context);
}
private void execute(Element element) {
if (element instanceof RuntimeVertex) {
execute((RuntimeVertex)element);
} else if (element instanceof RuntimeEdge) {
execute((RuntimeEdge)element);
}
}
private void execute(RuntimeEdge edge) {
logger.info("Execute {}", currentContext.getCurrentElement());
execute(edge.getActions());
if (edge.hasName()) {
currentContext.execute(edge.getName());
}
}
private void execute(List<Action> actions) {
for (Action action: actions) {
logger.info("Execute {}", action);
currentContext.execute(action);
}
}
private void execute(RuntimeVertex vertex) {
logger.info("Execute {}", currentContext.getCurrentElement());
if (vertex.hasName()) {
currentContext.execute(vertex.getName());
}
}
public ExecutionContext getCurrentContext() {
return currentContext;
}
private static class SharedStateTupel {
private final ExecutionContext context;
private final RuntimeVertex vertex;
private SharedStateTupel(ExecutionContext context, RuntimeVertex vertex) {
this.context = context;
this.vertex = vertex;
}
public ExecutionContext getContext() {
return context;
}
public RuntimeVertex getVertex() {
return vertex;
}
}
}
|
package org.jboss.remoting3.remote;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.nio.ByteBuffer;
import org.jboss.remoting3.MessageOutputStream;
import org.jboss.remoting3.NotOpenException;
import org.xnio.IoUtils;
import org.xnio.Pooled;
import org.xnio.channels.Channels;
import org.xnio.channels.ConnectedMessageChannel;
import org.xnio.streams.BufferPipeOutputStream;
import static org.jboss.remoting3.remote.RemoteLogger.log;
/**
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
final class OutboundMessage extends MessageOutputStream {
final short messageId;
final RemoteConnectionChannel channel;
final BufferPipeOutputStream pipeOutputStream;
final int maximumWindow;
int window;
boolean closed;
boolean cancelled;
boolean cancelSent;
final BufferPipeOutputStream.BufferWriter bufferWriter = new BufferPipeOutputStream.BufferWriter() {
public Pooled<ByteBuffer> getBuffer(boolean firstBuffer) throws IOException {
Pooled<ByteBuffer> pooled = allocate(Protocol.MESSAGE_DATA);
ByteBuffer buffer = pooled.getResource();
//Reserve room for the transmit data which is 4 bytes
buffer.limit(buffer.limit() - 4);
buffer.put(firstBuffer ? Protocol.MSG_FLAG_NEW : 0); // flags
// header size plus window size
int windowPlusHeader = maximumWindow + 8;
if (buffer.remaining() > windowPlusHeader) {
// never try to write more than the maximum window size
buffer.limit(windowPlusHeader);
}
return pooled;
}
public void accept(final Pooled<ByteBuffer> pooledBuffer, final boolean eof) throws IOException {
try {
final ByteBuffer buffer = pooledBuffer.getResource();
final ConnectedMessageChannel messageChannel = channel.getRemoteConnection().getChannel();
if (eof) {
// EOF flag (sync close)
buffer.put(7, (byte) (buffer.get(7) | Protocol.MSG_FLAG_EOF));
log.tracef("Sending message (with EOF) (%s) to %s", buffer, messageChannel);
}
assert Thread.holdsLock(pipeOutputStream);
final int msgSize = buffer.remaining() - 8;
window -= msgSize;
for (;;) {
if (closed) {
throw new NotOpenException("Message was closed asynchronously");
}
if (cancelled) {
if (cancelSent) {
return;
}
buffer.put(7, (byte)(buffer.get(7) | Protocol.MSG_FLAG_CANCELLED));
buffer.limit(8); // discard everything in the buffer
log.trace("Message includes cancel flag");
break;
}
if (window >= msgSize) {
break;
}
try {
log.trace("Message window is closed, waiting");
pipeOutputStream.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException("Interrupted on write");
}
}
log.trace("Message window is open, proceeding with send");
if (cancelled) {
cancelSent = true;
}
Channels.sendBlocking(messageChannel, buffer);
Channels.flushBlocking(messageChannel);
} finally {
pooledBuffer.free();
if (eof) {
channel.free(OutboundMessage.this);
}
}
}
public void flush() throws IOException {
log.trace("Flushing message channel");
Channels.flushBlocking(channel.getRemoteConnection().getChannel());
}
};
static final IntIndexer<OutboundMessage> INDEXER = new IntIndexer<OutboundMessage>() {
public int getKey(final OutboundMessage argument) {
return argument.messageId & 0xffff;
}
public boolean equals(final OutboundMessage argument, final int index) {
return (argument.messageId & 0xffff) == index;
}
};
OutboundMessage(final short messageId, final RemoteConnectionChannel channel, final int window) {
this.messageId = messageId;
this.channel = channel;
this.window = maximumWindow = window;
try {
pipeOutputStream = new BufferPipeOutputStream(bufferWriter);
} catch (IOException e) {
// not possible
throw new IllegalStateException(e);
}
}
Pooled<ByteBuffer> allocate(byte protoId) {
Pooled<ByteBuffer> pooled = channel.allocate(protoId);
ByteBuffer buffer = pooled.getResource();
buffer.putShort(messageId);
return pooled;
}
void acknowledge(int count) {
synchronized (pipeOutputStream) {
if (log.isTraceEnabled()) {
// do trace enabled check because of boxing here
log.tracef("Acknowledged %d bytes on %s", Integer.valueOf(count), this);
}
window += count;
pipeOutputStream.notifyAll();
}
}
void closeAsync() {
synchronized (pipeOutputStream) {
Pooled<ByteBuffer> pooled = pipeOutputStream.breakPipe();
if (pooled != null) {
pooled.free();
}
channel.free(this);
closed = true;
// wake up waiters
pipeOutputStream.notifyAll();
}
}
public void write(final int b) throws IOException {
pipeOutputStream.write(b);
}
public void write(final byte[] b) throws IOException {
pipeOutputStream.write(b);
}
public void write(final byte[] b, final int off, final int len) throws IOException {
pipeOutputStream.write(b, off, len);
}
public void flush() throws IOException {
pipeOutputStream.flush();
}
public void close() throws IOException {
synchronized (pipeOutputStream) {
pipeOutputStream.notifyAll();
pipeOutputStream.close();
}
}
public MessageOutputStream cancel() {
synchronized (pipeOutputStream) {
cancelled = true;
pipeOutputStream.notifyAll();
IoUtils.safeClose(pipeOutputStream);
return this;
}
}
public String toString() {
return String.format("Outbound message ID %04x on %s", Short.valueOf(messageId), channel);
}
void dumpState(final StringBuilder b) {
b.append(" ").append(String.format("Outbound message ID %04x, window %d of %d\n", messageId & 0xFFFF, window, maximumWindow));
b.append(" ").append("* flags: ");
if (cancelled) b.append("cancelled ");
if (cancelSent) b.append("cancel-sent ");
if (closed) b.append("closed ");
b.append('\n');
}
}
|
package org.jcodec.codecs.h264.decode;
import static org.jcodec.codecs.h264.H264Const.ARRAY;
import static org.jcodec.codecs.h264.H264Const.BLK8x8_BLOCKS;
import static org.jcodec.codecs.h264.H264Const.BLK_4x4_MB_OFF_LUMA;
import static org.jcodec.codecs.h264.H264Const.BLK_8x8_IND;
import static org.jcodec.codecs.h264.H264Const.BLK_8x8_MB_OFF_CHROMA;
import static org.jcodec.codecs.h264.H264Const.BLK_8x8_MB_OFF_LUMA;
import static org.jcodec.codecs.h264.H264Const.BLK_INV_MAP;
import static org.jcodec.codecs.h264.H264Const.COMP_BLOCK_4x4_LUT;
import static org.jcodec.codecs.h264.H264Const.COMP_BLOCK_8x8_LUT;
import static org.jcodec.codecs.h264.H264Const.COMP_POS_4x4_LUT;
import static org.jcodec.codecs.h264.H264Const.COMP_POS_8x8_LUT;
import static org.jcodec.codecs.h264.H264Const.QP_SCALE_CR;
import static org.jcodec.codecs.h264.H264Const.bPartPredModes;
import static org.jcodec.codecs.h264.H264Const.bSubMbTypes;
import static org.jcodec.codecs.h264.H264Const.identityMapping16;
import static org.jcodec.codecs.h264.H264Const.identityMapping4;
import static org.jcodec.codecs.h264.H264Const.last_sig_coeff_map_8x8;
import static org.jcodec.codecs.h264.H264Const.sig_coeff_map_8x8;
import static org.jcodec.codecs.h264.H264Const.PartPred.Bi;
import static org.jcodec.codecs.h264.H264Const.PartPred.Direct;
import static org.jcodec.codecs.h264.H264Const.PartPred.L0;
import static org.jcodec.codecs.h264.H264Const.PartPred.L1;
import static org.jcodec.codecs.h264.decode.CAVLCReader.moreRBSPData;
import static org.jcodec.codecs.h264.decode.CAVLCReader.readBool;
import static org.jcodec.codecs.h264.decode.CAVLCReader.readNBit;
import static org.jcodec.codecs.h264.decode.CAVLCReader.readSE;
import static org.jcodec.codecs.h264.decode.CAVLCReader.readTE;
import static org.jcodec.codecs.h264.decode.CAVLCReader.readUE;
import static org.jcodec.codecs.h264.decode.CoeffTransformer.reorderDC4x4;
import static org.jcodec.codecs.h264.io.model.MBType.B_8x8;
import static org.jcodec.codecs.h264.io.model.MBType.I_16x16;
import static org.jcodec.codecs.h264.io.model.MBType.P_16x16;
import static org.jcodec.codecs.h264.io.model.MBType.P_16x8;
import static org.jcodec.codecs.h264.io.model.MBType.P_8x16;
import static org.jcodec.codecs.h264.io.model.MBType.P_8x8;
import static org.jcodec.codecs.h264.io.model.SliceType.P;
import static org.jcodec.common.model.ColorSpace.MONO;
import static org.jcodec.common.tools.MathUtil.abs;
import static org.jcodec.common.tools.MathUtil.clip;
import static org.jcodec.common.tools.MathUtil.wrap;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Comparator;
import org.jcodec.codecs.common.biari.MDecoder;
import org.jcodec.codecs.h264.H264Const;
import org.jcodec.codecs.h264.H264Const.PartPred;
import org.jcodec.codecs.h264.decode.aso.MapManager;
import org.jcodec.codecs.h264.decode.aso.Mapper;
import org.jcodec.codecs.h264.io.CABAC;
import org.jcodec.codecs.h264.io.CABAC.BlockType;
import org.jcodec.codecs.h264.io.CAVLC;
import org.jcodec.codecs.h264.io.model.Frame;
import org.jcodec.codecs.h264.io.model.MBType;
import org.jcodec.codecs.h264.io.model.NALUnit;
import org.jcodec.codecs.h264.io.model.PictureParameterSet;
import org.jcodec.codecs.h264.io.model.SeqParameterSet;
import org.jcodec.codecs.h264.io.model.SliceHeader;
import org.jcodec.codecs.h264.io.model.SliceType;
import org.jcodec.common.IntObjectMap;
import org.jcodec.common.io.BitReader;
import org.jcodec.common.logging.Logger;
import org.jcodec.common.model.ColorSpace;
import org.jcodec.common.model.Picture8Bit;
import org.jcodec.common.tools.MathUtil;
public class SliceDecoder {
private static final int[] NULL_VECTOR = new int[] { 0, 0, -1 };
private SliceHeader sh;
private CAVLC[] cavlc;
private CABAC cabac;
private Mapper mapper;
private int[] chromaQpOffset;
private int qp;
private byte[][] leftRow;
private byte[][] topLine;
private byte[][] topLeft;
private int[] i4x4PredTop;
private int[] i4x4PredLeft;
private MBType[] topMBType;
private MBType leftMBType;
private ColorSpace chromaFormat;
private boolean transform8x8;
private int[][][] mvTop;
private int[][][] mvLeft;
private int[][] mvTopLeft;
private SeqParameterSet activeSps;
private PictureParameterSet activePps;
private int[][] nCoeff;
private int[][][][] mvs;
private MBType[] mbTypes;
private int[][] mbQps;
private Frame thisFrame;
private Frame[] sRefs;
private IntObjectMap<Frame> lRefs;
private MDecoder mDecoder;
private SliceHeader[] shs;
private int leftCBPLuma;
private int[] topCBPLuma;
private int leftCBPChroma;
private int[] topCBPChroma;
private int[] numRef;
private boolean tf8x8Left;
private boolean[] tf8x8Top;
private PartPred[] predModeLeft;
private PartPred[] predModeTop;
private boolean[] tr8x8Used;
private Frame[][][] refsUsed;
private Prediction prediction;
private boolean debug;
public SliceDecoder(SeqParameterSet activeSps, PictureParameterSet activePps, int[][] nCoeff, int[][][][] mvs,
MBType[] mbTypes, int[][] mbQps, SliceHeader[] shs, boolean[] tr8x8Used, Frame[][][] refsUsed,
Frame result, Frame[] sRefs, IntObjectMap<Frame> lRefs) {
this.activeSps = activeSps;
this.activePps = activePps;
this.nCoeff = nCoeff;
this.mvs = mvs;
this.mbTypes = mbTypes;
this.mbQps = mbQps;
this.shs = shs;
this.thisFrame = result;
this.sRefs = sRefs;
this.lRefs = lRefs;
this.tr8x8Used = tr8x8Used;
this.refsUsed = refsUsed;
}
public void decode(ByteBuffer segment, NALUnit nalUnit) {
BitReader in = new BitReader(segment);
SliceHeaderReader shr = new SliceHeaderReader();
sh = shr.readPart1(in);
sh.sps = activeSps;
sh.pps = activePps;
cavlc = new CAVLC[] { new CAVLC(sh.sps, sh.pps, 2, 2), new CAVLC(sh.sps, sh.pps, 1, 1),
new CAVLC(sh.sps, sh.pps, 1, 1) };
int mbWidth = sh.sps.pic_width_in_mbs_minus1 + 1;
cabac = new CABAC(mbWidth);
chromaQpOffset = new int[] { sh.pps.chroma_qp_index_offset,
sh.pps.extended != null ? sh.pps.extended.second_chroma_qp_index_offset : sh.pps.chroma_qp_index_offset };
chromaFormat = sh.sps.chroma_format_idc;
transform8x8 = sh.pps.extended == null ? false : sh.pps.extended.transform_8x8_mode_flag;
i4x4PredLeft = new int[4];
i4x4PredTop = new int[mbWidth << 2];
topMBType = new MBType[mbWidth];
this.topCBPLuma = new int[mbWidth];
this.topCBPChroma = new int[mbWidth];
mvTop = new int[2][(mbWidth << 2) + 1][3];
mvLeft = new int[2][4][3];
mvTopLeft = new int[2][3];
leftRow = new byte[3][16];
topLeft = new byte[3][4];
topLine = new byte[3][mbWidth << 4];
this.predModeLeft = new PartPred[2];
this.predModeTop = new PartPred[mbWidth << 1];
this.tf8x8Top = new boolean[mbWidth];
shr.readPart2(sh, nalUnit, sh.sps, sh.pps, in);
prediction = new Prediction(sh);
qp = sh.pps.pic_init_qp_minus26 + 26 + sh.slice_qp_delta;
if (activePps.entropy_coding_mode_flag) {
in.terminate();
int[][] cm = new int[2][1024];
cabac.initModels(cm, sh.slice_type, sh.cabac_init_idc, qp);
mDecoder = new MDecoder(segment, cm);
}
if (sh.num_ref_idx_active_override_flag)
numRef = new int[] { sh.num_ref_idx_active_minus1[0] + 1, sh.num_ref_idx_active_minus1[1] + 1 };
else
numRef = new int[] { activePps.num_ref_idx_active_minus1[0] + 1, activePps.num_ref_idx_active_minus1[1] + 1 };
debugPrint("============" + thisFrame.getPOC() + "============= " + sh.slice_type.name());
Frame[][] refList = null;
if (sh.slice_type == SliceType.P) {
refList = new Frame[][] { buildRefListP(), null };
} else if (sh.slice_type == SliceType.B) {
refList = buildRefListB();
}
debugPrint("
if (refList != null) {
for (int l = 0; l < 2; l++) {
if (refList[l] != null)
for (int i = 0; i < refList[l].length; i++)
if (refList[l][i] != null)
debugPrint("REF[" + l + "][" + i + "]: " + ((Frame) refList[l][i]).getPOC());
}
}
mapper = new MapManager(sh.sps, sh.pps).getMapper(sh);
Picture8Bit mb = Picture8Bit.create(16, 16, sh.sps.chroma_format_idc);
boolean mbaffFrameFlag = (sh.sps.mb_adaptive_frame_field_flag && !sh.field_pic_flag);
boolean prevMbSkipped = false;
int i;
MBType prevMBType = null;
for (i = 0;; i++) {
if (sh.slice_type.isInter() && !activePps.entropy_coding_mode_flag) {
int mbSkipRun = readUE(in, "mb_skip_run");
for (int j = 0; j < mbSkipRun; j++, i++) {
int mbAddr = mapper.getAddress(i);
debugPrint("
+ ")
decodeSkip(refList, i, mb, sh.slice_type);
shs[mbAddr] = sh;
refsUsed[mbAddr] = refList;
put(thisFrame, mb, mapper.getMbX(i), mapper.getMbY(i));
wipe(mb);
}
prevMbSkipped = mbSkipRun > 0;
prevMBType = null;
if (!moreRBSPData(in))
break;
}
int mbAddr = mapper.getAddress(i);
shs[mbAddr] = sh;
refsUsed[mbAddr] = refList;
int mbX = mbAddr % mbWidth;
int mbY = mbAddr / mbWidth;
debugPrint("
if (sh.slice_type.isIntra()
|| (!activePps.entropy_coding_mode_flag || !cabac.readMBSkipFlag(mDecoder, sh.slice_type,
mapper.leftAvailable(i), mapper.topAvailable(i), mbX))) {
boolean mb_field_decoding_flag = false;
if (mbaffFrameFlag && (i % 2 == 0 || (i % 2 == 1 && prevMbSkipped))) {
mb_field_decoding_flag = readBool(in, "mb_field_decoding_flag");
}
prevMBType = decode(sh.slice_type, i, in, mb_field_decoding_flag, prevMBType, mb, refList);
} else {
decodeSkip(refList, i, mb, sh.slice_type);
prevMBType = null;
}
put(thisFrame, mb, mbX, mbY);
if (activePps.entropy_coding_mode_flag && mDecoder.decodeFinalBin() == 1)
break;
else if (!activePps.entropy_coding_mode_flag && !moreRBSPData(in))
break;
wipe(mb);
}
}
private Frame[] buildRefListP() {
int frame_num = sh.frame_num;
int maxFrames = 1 << (sh.sps.log2_max_frame_num_minus4 + 4);
// int nLongTerm = Math.min(lRefs.size(), numRef[0] - 1);
Frame[] result = new Frame[numRef[0]];
int refs = 0;
for (int i = frame_num - 1; i >= frame_num - maxFrames && refs < numRef[0]; i
int fn = i < 0 ? i + maxFrames : i;
if (sRefs[fn] != null) {
result[refs] = sRefs[fn] == H264Const.NO_PIC ? null : sRefs[fn];
++refs;
}
}
int[] keys = lRefs.keys();
Arrays.sort(keys);
for (int i = 0; i < keys.length && refs < numRef[0]; i++) {
result[refs++] = lRefs.get(keys[i]);
}
reorder(result, 0);
return result;
}
private Frame[][] buildRefListB() {
Frame[] l0 = buildList(Frame.POCDesc, Frame.POCAsc);
Frame[] l1 = buildList(Frame.POCAsc, Frame.POCDesc);
if (Arrays.equals(l0, l1) && count(l1) > 1) {
Frame frame = l1[1];
l1[1] = l1[0];
l1[0] = frame;
}
Frame[][] result = { Arrays.copyOf(l0, numRef[0]), Arrays.copyOf(l1, numRef[1]) };
reorder(result[0], 0);
reorder(result[1], 1);
return result;
}
private Frame[] buildList(Comparator<Frame> cmpFwd, Comparator<Frame> cmpInv) {
Frame[] refs = new Frame[sRefs.length + lRefs.size()];
Frame[] fwd = copySort(cmpFwd, thisFrame);
Frame[] inv = copySort(cmpInv, thisFrame);
int nFwd = count(fwd);
int nInv = count(inv);
int ref = 0;
for (int i = 0; i < nFwd; i++, ref++)
refs[ref] = fwd[i];
for (int i = 0; i < nInv; i++, ref++)
refs[ref] = inv[i];
int[] keys = lRefs.keys();
Arrays.sort(keys);
for (int i = 0; i < keys.length; i++, ref++)
refs[ref] = lRefs.get(keys[i]);
return refs;
}
private int count(Frame[] arr) {
for (int nn = 0; nn < arr.length; nn++)
if (arr[nn] == null)
return nn;
return arr.length;
}
private Frame[] copySort(Comparator<Frame> fwd, Frame dummy) {
Frame[] copyOf = Arrays.copyOf(sRefs, sRefs.length);
for (int i = 0; i < copyOf.length; i++)
if (fwd.compare(dummy, copyOf[i]) > 0)
copyOf[i] = null;
Arrays.sort(copyOf, fwd);
return copyOf;
}
private void reorder(Picture8Bit[] result, int list) {
if (sh.refPicReordering[list] == null)
return;
int predict = sh.frame_num;
int maxFrames = 1 << (sh.sps.log2_max_frame_num_minus4 + 4);
for (int ind = 0; ind < sh.refPicReordering[list][0].length; ind++) {
switch (sh.refPicReordering[list][0][ind]) {
case 0:
predict = wrap(predict - sh.refPicReordering[list][1][ind] - 1, maxFrames);
break;
case 1:
predict = wrap(predict + sh.refPicReordering[list][1][ind] + 1, maxFrames);
break;
case 2:
throw new RuntimeException("long term");
}
for (int i = numRef[list] - 1; i > ind; i
result[i] = result[i - 1];
result[ind] = sRefs[predict];
for (int i = ind + 1, j = i; i < numRef[list] && result[i] != null; i++) {
if (result[i] != sRefs[predict])
result[j++] = result[i];
}
}
}
public MBType decode(SliceType sliceType, int mbAddr, BitReader reader, boolean field, MBType prevMbType,
Picture8Bit mb, Frame[][] references) {
if (sliceType == SliceType.I) {
return decodeMBlockI(mbAddr, reader, field, prevMbType, mb);
} else if (sliceType == SliceType.P) {
return decodeMBlockP(mbAddr, reader, field, prevMbType, mb, references);
} else {
return decodeMBlockB(mbAddr, reader, field, prevMbType, mb, references);
}
}
private MBType decodeMBlockI(int mbIdx, BitReader reader, boolean field, MBType prevMbType, Picture8Bit mb) {
int mbType;
if (!activePps.entropy_coding_mode_flag)
mbType = readUE(reader, "MB: mb_type");
else
mbType = cabac.readMBTypeI(mDecoder, leftMBType, topMBType[mapper.getMbX(mbIdx)],
mapper.leftAvailable(mbIdx), mapper.topAvailable(mbIdx));
return decodeMBlockIInt(mbType, mbIdx, reader, field, prevMbType, mb);
}
private MBType decodeMBlockIInt(int mbType, int mbIdx, BitReader reader, boolean field, MBType prevMbType,
Picture8Bit mb) {
MBType mbt;
if (mbType == 0) {
decodeMBlockIntraNxN(reader, mbIdx, prevMbType, mb);
mbt = MBType.I_NxN;
} else if (mbType >= 1 && mbType <= 24) {
mbType
decodeMBlockIntra16x16(reader, mbType, mbIdx, prevMbType, mb);
mbt = MBType.I_16x16;
} else {
Logger.warn("IPCM macroblock found. Not tested, may cause unpredictable behavior.");
decodeMBlockIPCM(reader, mbIdx, mb);
mbt = MBType.I_PCM;
}
int xx = mapper.getMbX(mbIdx) << 2;
copyVect(mvTopLeft[0], mvTop[0][xx + 3]);
copyVect(mvTopLeft[1], mvTop[1][xx + 3]);
saveVect(mvTop[0], xx, xx + 4, 0, 0, -1);
saveVect(mvLeft[0], 0, 4, 0, 0, -1);
saveVect(mvTop[1], xx, xx + 4, 0, 0, -1);
saveVect(mvLeft[1], 0, 4, 0, 0, -1);
return mbt;
}
private MBType decodeMBlockP(int mbIdx, BitReader reader, boolean field, MBType prevMbType, Picture8Bit mb,
Frame[][] references) {
int mbType;
if (!activePps.entropy_coding_mode_flag)
mbType = readUE(reader, "MB: mb_type");
else
mbType = cabac.readMBTypeP(mDecoder);
switch (mbType) {
case 0:
decodeInter16x16(reader, mb, references, mbIdx, prevMbType, L0, P_16x16);
return MBType.P_16x16;
case 1:
decodeInter16x8(reader, mb, references, mbIdx, prevMbType, L0, L0, P_16x8);
return MBType.P_16x8;
case 2:
decodeInter8x16(reader, mb, references, mbIdx, prevMbType, L0, L0, P_8x16);
return MBType.P_8x16;
case 3:
decodeMBInter8x8(reader, mbType, references, mb, P, mbIdx, field, prevMbType, false);
return MBType.P_8x8;
case 4:
decodeMBInter8x8(reader, mbType, references, mb, P, mbIdx, field, prevMbType, true);
return MBType.P_8x8ref0;
default:
return decodeMBlockIInt(mbType - 5, mbIdx, reader, field, prevMbType, mb);
}
}
private MBType decodeMBlockB(int mbIdx, BitReader reader, boolean field, MBType prevMbType, Picture8Bit mb,
Frame[][] references) {
int mbType;
if (!activePps.entropy_coding_mode_flag)
mbType = readUE(reader, "MB: mb_type");
else
mbType = cabac.readMBTypeB(mDecoder, leftMBType, topMBType[mapper.getMbX(mbIdx)],
mapper.leftAvailable(mbIdx), mapper.topAvailable(mbIdx));
if (mbType >= 23) {
return decodeMBlockIInt(mbType - 23, mbIdx, reader, field, prevMbType, mb);
} else {
MBType curMBType = H264Const.bMbTypes[mbType];
if (mbType == 0)
decodeMBBiDirect(mbIdx, reader, field, prevMbType, mb, references);
else if (mbType <= 3)
decodeInter16x16(reader, mb, references, mbIdx, prevMbType, H264Const.bPredModes[mbType][0], curMBType);
else if (mbType == 22)
decodeMBInter8x8(reader, mbType, references, mb, SliceType.B, mbIdx, field, prevMbType, false);
else if ((mbType & 1) == 0)
decodeInter16x8(reader, mb, references, mbIdx, prevMbType, H264Const.bPredModes[mbType][0],
H264Const.bPredModes[mbType][1], curMBType);
else
decodeInter8x16(reader, mb, references, mbIdx, prevMbType, H264Const.bPredModes[mbType][0],
H264Const.bPredModes[mbType][1], curMBType);
return curMBType;
}
}
public void put(Picture8Bit tgt, Picture8Bit decoded, int mbX, int mbY) {
byte[] luma = tgt.getPlaneData(0);
int stride = tgt.getPlaneWidth(0);
byte[] cb = tgt.getPlaneData(1);
byte[] cr = tgt.getPlaneData(2);
int strideChroma = tgt.getPlaneWidth(1);
int dOff = 0;
for (int i = 0; i < 16; i++) {
System.arraycopy(decoded.getPlaneData(0), dOff, luma, (mbY * 16 + i) * stride + mbX * 16, 16);
dOff += 16;
}
for (int i = 0; i < 8; i++) {
System.arraycopy(decoded.getPlaneData(1), i * 8, cb, (mbY * 8 + i) * strideChroma + mbX * 8, 8);
}
for (int i = 0; i < 8; i++) {
System.arraycopy(decoded.getPlaneData(2), i * 8, cr, (mbY * 8 + i) * strideChroma + mbX * 8, 8);
}
}
public void decodeMBlockIntra16x16(BitReader reader, int mbType, int mbIndex, MBType prevMbType, Picture8Bit mb) {
int mbX = mapper.getMbX(mbIndex);
int mbY = mapper.getMbY(mbIndex);
int address = mapper.getAddress(mbIndex);
int cbpChroma = (mbType / 4) % 3;
int cbpLuma = (mbType / 12) * 15;
boolean leftAvailable = mapper.leftAvailable(mbIndex);
boolean topAvailable = mapper.topAvailable(mbIndex);
int chromaPredictionMode = readChromaPredMode(reader, mbX, leftAvailable, topAvailable);
int mbQPDelta = readMBQpDelta(reader, prevMbType);
qp = (qp + mbQPDelta + 52) % 52;
mbQps[0][address] = qp;
int[][] residual = new int[16][16];
residualLumaI16x16(reader, leftAvailable, topAvailable, mbX, mbY, cbpLuma, residual);
Intra16x16PredictionBuilder.predictWithMode(mbType % 4, residual, leftAvailable, topAvailable,
leftRow[0], topLine[0], topLeft[0], mbX << 4, mb.getPlaneData(0));
decodeChroma(reader, cbpChroma, chromaPredictionMode, mbX, mbY, leftAvailable, topAvailable, mb, qp,
MBType.I_16x16);
mbTypes[address] = topMBType[mbX] = leftMBType = MBType.I_16x16;
// System.out.println("idx: " + mbIndex + ", addr: " + address);
topCBPLuma[mbX] = leftCBPLuma = cbpLuma;
topCBPChroma[mbX] = leftCBPChroma = cbpChroma;
tf8x8Left = tf8x8Top[mbX] = false;
collectPredictors(mb, mbX);
saveMvsIntra(mbX, mbY);
}
public void decodeMBlockIntraNxN(BitReader reader, int mbIndex, MBType prevMbType, Picture8Bit mb) {
int mbX = mapper.getMbX(mbIndex);
int mbY = mapper.getMbY(mbIndex);
int mbAddr = mapper.getAddress(mbIndex);
boolean leftAvailable = mapper.leftAvailable(mbIndex);
boolean topAvailable = mapper.topAvailable(mbIndex);
boolean topLeftAvailable = mapper.topLeftAvailable(mbIndex);
boolean topRightAvailable = mapper.topRightAvailable(mbIndex);
boolean transform8x8Used = false;
if (transform8x8) {
transform8x8Used = readTransform8x8Flag(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX],
tf8x8Left, tf8x8Top[mbX]);
}
int[] lumaModes;
if (!transform8x8Used) {
lumaModes = new int[16];
for (int i = 0; i < 16; i++) {
int blkX = H264Const.MB_BLK_OFF_LEFT[i];
int blkY = H264Const.MB_BLK_OFF_TOP[i];
lumaModes[i] = readPredictionI4x4Block(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX],
blkX, blkY, mbX);
}
} else {
lumaModes = new int[4];
for (int i = 0; i < 4; i++) {
int blkX = (i & 1) << 1;
int blkY = i & 2;
lumaModes[i] = readPredictionI4x4Block(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX],
blkX, blkY, mbX);
i4x4PredLeft[blkY + 1] = i4x4PredLeft[blkY];
i4x4PredTop[(mbX << 2) + blkX + 1] = i4x4PredTop[(mbX << 2) + blkX];
}
}
int chromaMode = readChromaPredMode(reader, mbX, leftAvailable, topAvailable);
int codedBlockPattern = readCodedBlockPatternIntra(reader, leftAvailable, topAvailable, leftCBPLuma
| (leftCBPChroma << 4), topCBPLuma[mbX] | (topCBPChroma[mbX] << 4), leftMBType, topMBType[mbX]);
int cbpLuma = codedBlockPattern & 0xf;
int cbpChroma = codedBlockPattern >> 4;
if (cbpLuma > 0 || cbpChroma > 0) {
qp = (qp + readMBQpDelta(reader, prevMbType) + 52) % 52;
}
mbQps[0][mbAddr] = qp;
int[][] lumaResidual = transform8x8Used ? new int[4][64] : new int[16][16];
residualLuma(reader, leftAvailable, topAvailable, mbX, mbY, codedBlockPattern, MBType.I_NxN,
transform8x8Used, tf8x8Left, tf8x8Top[mbX], lumaResidual);
if (!transform8x8Used) {
for (int i = 0; i < 16; i++) {
int blkX = (i & 3) << 2;
int blkY = i & ~3;
int bi = H264Const.BLK_INV_MAP[i];
boolean trAvailable = ((bi == 0 || bi == 1 || bi == 4) && topAvailable)
|| (bi == 5 && topRightAvailable) || bi == 2 || bi == 6 || bi == 8 || bi == 9 || bi == 10
|| bi == 12 || bi == 14;
Intra4x4PredictionBuilder.predictWithMode(lumaModes[bi], lumaResidual[bi], blkX == 0 ? leftAvailable
: true, blkY == 0 ? topAvailable : true, trAvailable, leftRow[0], topLine[0], topLeft[0],
(mbX << 4), blkX, blkY, mb.getPlaneData(0));
}
} else {
for (int i = 0; i < 4; i++) {
int blkX = (i & 1) << 1;
int blkY = i & 2;
boolean trAvailable = (i == 0 && topAvailable) || (i == 1 && topRightAvailable) || i == 2;
boolean tlAvailable = i == 0 ? topLeftAvailable : (i == 1 ? topAvailable : (i == 2 ? leftAvailable
: true));
Intra8x8PredictionBuilder.predictWithMode(lumaModes[i], lumaResidual[i], blkX == 0 ? leftAvailable
: true, blkY == 0 ? topAvailable : true, tlAvailable, trAvailable, leftRow[0], topLine[0],
topLeft[0], (mbX << 4), blkX << 2, blkY << 2, mb.getPlaneData(0));
}
}
decodeChroma(reader, cbpChroma, chromaMode, mbX, mbY, leftAvailable, topAvailable, mb, qp, MBType.I_NxN);
mbTypes[mbAddr] = topMBType[mbX] = leftMBType = MBType.I_NxN;
// System.out.println("idx: " + mbIndex + ", addr: " + address);
topCBPLuma[mbX] = leftCBPLuma = cbpLuma;
topCBPChroma[mbX] = leftCBPChroma = cbpChroma;
tf8x8Left = tf8x8Top[mbX] = transform8x8Used;
tr8x8Used[mbAddr] = transform8x8Used;
collectChromaPredictors(mb, mbX);
saveMvsIntra(mbX, mbY);
}
private void decodeInter16x16(BitReader reader, Picture8Bit mb, Frame[][] refs, int mbIdx, MBType prevMbType,
PartPred p0, MBType curMBType) {
int mbX = mapper.getMbX(mbIdx);
int mbY = mapper.getMbY(mbIdx);
boolean leftAvailable = mapper.leftAvailable(mbIdx);
boolean topAvailable = mapper.topAvailable(mbIdx);
boolean topLeftAvailable = mapper.topLeftAvailable(mbIdx);
boolean topRightAvailable = mapper.topRightAvailable(mbIdx);
int address = mapper.getAddress(mbIdx);
int[][][] x = new int[2][][];
int xx = mbX << 2;
int[] refIdx = { 0, 0 };
for (int list = 0; list < 2; list++) {
if (p0.usesList(list) && numRef[list] > 1)
refIdx[list] = readRefIdx(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX],
predModeLeft[0], predModeTop[(mbX << 1)], p0, mbX, 0, 0, 4, 4, list);
}
Picture8Bit[] mbb = { Picture8Bit.create(16, 16, chromaFormat), Picture8Bit.create(16, 16, chromaFormat) };
for (int list = 0; list < 2; list++) {
predictInter16x16(reader, mbb[list], refs, mbX, mbY, leftAvailable, topAvailable, topLeftAvailable,
topRightAvailable, x, xx, refIdx, list, p0);
}
prediction.mergePrediction(x[0][0][2], x[1][0][2], p0, 0, mbb[0].getPlaneData(0), mbb[1].getPlaneData(0), 0,
16, 16, 16, mb.getPlaneData(0), refs, thisFrame);
predModeLeft[0] = predModeLeft[1] = predModeTop[mbX << 1] = predModeTop[(mbX << 1) + 1] = p0;
PartPred[] partPreds = new PartPred[] { p0, p0, p0, p0 };
predictChromaInter(refs, x, mbX << 3, mbY << 3, 1, mb, partPreds);
predictChromaInter(refs, x, mbX << 3, mbY << 3, 2, mb, partPreds);
int[][][] residual = residualInter(reader, refs, leftAvailable, topAvailable, mbX, mbY, x, partPreds,
mapper.getAddress(mbIdx), prevMbType, curMBType);
boolean transform8x8Used = residual[0][0].length == 64;
mergeResidual(mb, residual, transform8x8Used ? COMP_BLOCK_8x8_LUT : COMP_BLOCK_4x4_LUT,
transform8x8Used ? COMP_POS_8x8_LUT : COMP_POS_4x4_LUT);
collectPredictors(mb, mbX);
mbTypes[address] = topMBType[mbX] = leftMBType = curMBType;
}
private void decodeInter16x8(BitReader reader, Picture8Bit mb, Frame[][] refs, int mbIdx, MBType prevMbType,
PartPred p0, PartPred p1, MBType curMBType) {
int mbX = mapper.getMbX(mbIdx);
int mbY = mapper.getMbY(mbIdx);
boolean leftAvailable = mapper.leftAvailable(mbIdx);
boolean topAvailable = mapper.topAvailable(mbIdx);
boolean topLeftAvailable = mapper.topLeftAvailable(mbIdx);
boolean topRightAvailable = mapper.topRightAvailable(mbIdx);
int address = mapper.getAddress(mbIdx);
int xx = mbX << 2;
int[] refIdx1 = { 0, 0 }, refIdx2 = { 0, 0 };
int[][][] x = new int[2][][];
for (int list = 0; list < 2; list++) {
if (p0.usesList(list) && numRef[list] > 1)
refIdx1[list] = readRefIdx(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX],
predModeLeft[0], predModeTop[(mbX << 1)], p0, mbX, 0, 0, 4, 2, list);
if (p1.usesList(list) && numRef[list] > 1)
refIdx2[list] = readRefIdx(reader, leftAvailable, true, leftMBType, curMBType, predModeLeft[1], p0, p1,
mbX, 0, 2, 4, 2, list);
}
Picture8Bit[] mbb = { Picture8Bit.create(16, 16, chromaFormat), Picture8Bit.create(16, 16, chromaFormat) };
for (int list = 0; list < 2; list++) {
predictInter16x8(reader, mbb[list], refs, mbX, mbY, leftAvailable, topAvailable, topLeftAvailable,
topRightAvailable, xx, refIdx1, refIdx2, x, p0, p1, list);
}
prediction.mergePrediction(x[0][0][2], x[1][0][2], p0, 0, mbb[0].getPlaneData(0), mbb[1].getPlaneData(0), 0,
16, 16, 8, mb.getPlaneData(0), refs, thisFrame);
prediction.mergePrediction(x[0][8][2], x[1][8][2], p1, 0, mbb[0].getPlaneData(0), mbb[1].getPlaneData(0), 128,
16, 16, 8, mb.getPlaneData(0), refs, thisFrame);
predModeLeft[0] = p0;
predModeLeft[1] = predModeTop[mbX << 1] = predModeTop[(mbX << 1) + 1] = p1;
PartPred[] partPreds = new PartPred[] { p0, p0, p1, p1 };
predictChromaInter(refs, x, mbX << 3, mbY << 3, 1, mb, partPreds);
predictChromaInter(refs, x, mbX << 3, mbY << 3, 2, mb, partPreds);
int[][][] residual = residualInter(reader, refs, leftAvailable, topAvailable, mbX, mbY, x, partPreds,
mapper.getAddress(mbIdx), prevMbType, curMBType);
boolean transform8x8Used = residual[0][0].length == 64;
mergeResidual(mb, residual, transform8x8Used ? COMP_BLOCK_8x8_LUT : COMP_BLOCK_4x4_LUT,
transform8x8Used ? COMP_POS_8x8_LUT : COMP_POS_4x4_LUT);
collectPredictors(mb, mbX);
mbTypes[address] = topMBType[mbX] = leftMBType = curMBType;
}
private void decodeInter8x16(BitReader reader, Picture8Bit mb, Frame[][] refs, int mbIdx, MBType prevMbType,
PartPred p0, PartPred p1, MBType curMBType) {
int mbX = mapper.getMbX(mbIdx);
int mbY = mapper.getMbY(mbIdx);
boolean leftAvailable = mapper.leftAvailable(mbIdx);
boolean topAvailable = mapper.topAvailable(mbIdx);
boolean topLeftAvailable = mapper.topLeftAvailable(mbIdx);
boolean topRightAvailable = mapper.topRightAvailable(mbIdx);
int address = mapper.getAddress(mbIdx);
int[][][] x = new int[2][][];
int[] refIdx1 = { 0, 0 }, refIdx2 = { 0, 0 };
for (int list = 0; list < 2; list++) {
if (p0.usesList(list) && numRef[list] > 1)
refIdx1[list] = readRefIdx(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX],
predModeLeft[0], predModeTop[mbX << 1], p0, mbX, 0, 0, 2, 4, list);
if (p1.usesList(list) && numRef[list] > 1)
refIdx2[list] = readRefIdx(reader, true, topAvailable, curMBType, topMBType[mbX], p0,
predModeTop[(mbX << 1) + 1], p1, mbX, 2, 0, 2, 4, list);
}
Picture8Bit[] mbb = { Picture8Bit.create(16, 16, chromaFormat), Picture8Bit.create(16, 16, chromaFormat) };
for (int list = 0; list < 2; list++) {
predictInter8x16(reader, mbb[list], refs, mbX, mbY, leftAvailable, topAvailable, topLeftAvailable,
topRightAvailable, x, refIdx1, refIdx2, list, p0, p1);
}
prediction.mergePrediction(x[0][0][2], x[1][0][2], p0, 0, mbb[0].getPlaneData(0), mbb[1].getPlaneData(0), 0,
16, 8, 16, mb.getPlaneData(0), refs, thisFrame);
prediction.mergePrediction(x[0][2][2], x[1][2][2], p1, 0, mbb[0].getPlaneData(0), mbb[1].getPlaneData(0), 8,
16, 8, 16, mb.getPlaneData(0), refs, thisFrame);
PartPred[] predType = new PartPred[] { p0, p1, p0, p1 };
predictChromaInter(refs, x, mbX << 3, mbY << 3, 1, mb, predType);
predictChromaInter(refs, x, mbX << 3, mbY << 3, 2, mb, predType);
predModeTop[mbX << 1] = p0;
predModeTop[(mbX << 1) + 1] = predModeLeft[0] = predModeLeft[1] = p1;
int[][][] residual = residualInter(reader, refs, leftAvailable, topAvailable, mbX, mbY, x, predType,
mapper.getAddress(mbIdx), prevMbType, curMBType);
boolean transform8x8Used = residual[0][0].length == 64;
mergeResidual(mb, residual, transform8x8Used ? COMP_BLOCK_8x8_LUT : COMP_BLOCK_4x4_LUT,
transform8x8Used ? COMP_POS_8x8_LUT : COMP_POS_4x4_LUT);
collectPredictors(mb, mbX);
mbTypes[address] = topMBType[mbX] = leftMBType = curMBType;
}
public void decodeMBInter8x8(BitReader reader, int mb_type, Frame[][] references, Picture8Bit mb, SliceType sliceType,
int mbIdx, boolean mb_field_decoding_flag, MBType prevMbType, boolean ref0) {
int mbX = mapper.getMbX(mbIdx);
int mbY = mapper.getMbY(mbIdx);
int mbAddr = mapper.getAddress(mbIdx);
boolean leftAvailable = mapper.leftAvailable(mbIdx);
boolean topAvailable = mapper.topAvailable(mbIdx);
boolean topLeftAvailable = mapper.topLeftAvailable(mbIdx);
boolean topRightAvailable = mapper.topRightAvailable(mbIdx);
int[][][] x = new int[2][16][3];
PartPred[] pp = new PartPred[4];
for (int i = 0; i < 16; i++)
x[0][i][2] = x[1][i][2] = -1;
MBType curMBType;
boolean noSubMBLessThen8x8;
if (sliceType == SliceType.P) {
noSubMBLessThen8x8 = predict8x8P(reader, references[0], mb, ref0, mbX, mbY, leftAvailable, topAvailable,
topLeftAvailable, topRightAvailable, x, pp);
curMBType = P_8x8;
} else {
noSubMBLessThen8x8 = predict8x8B(reader, references, mb, ref0, mbX, mbY, leftAvailable, topAvailable,
topLeftAvailable, topRightAvailable, x, pp);
curMBType = B_8x8;
}
predictChromaInter(references, x, mbX << 3, mbY << 3, 1, mb, pp);
predictChromaInter(references, x, mbX << 3, mbY << 3, 2, mb, pp);
int codedBlockPattern = readCodedBlockPatternInter(reader, leftAvailable, topAvailable, leftCBPLuma
| (leftCBPChroma << 4), topCBPLuma[mbX] | (topCBPChroma[mbX] << 4), leftMBType, topMBType[mbX]);
int cbpLuma = codedBlockPattern & 0xf;
int cbpChroma = codedBlockPattern >> 4;
boolean transform8x8Used = false;
if (transform8x8 && cbpLuma != 0 && noSubMBLessThen8x8) {
transform8x8Used = readTransform8x8Flag(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX],
tf8x8Left, tf8x8Top[mbX]);
}
if (cbpLuma > 0 || cbpChroma > 0) {
qp = (qp + readMBQpDelta(reader, prevMbType) + 52) % 52;
}
mbQps[0][mbAddr] = qp;
int[][][] residual = {
transform8x8Used ? new int[4][64] : new int[16][16],
new int[4][16],
new int[4][16]
};
residualLuma(reader, leftAvailable, topAvailable, mbX, mbY, codedBlockPattern, curMBType, transform8x8Used,
tf8x8Left, tf8x8Top[mbX], residual[0]);
saveMvs(x, mbX, mbY);
int qp1 = calcQpChroma(qp, chromaQpOffset[0]);
int qp2 = calcQpChroma(qp, chromaQpOffset[1]);
decodeChromaResidual(reader, leftAvailable, topAvailable, mbX, mbY, codedBlockPattern >> 4, qp1, qp2, MBType.P_16x16, residual[1], residual[2]);
mbQps[1][mbAddr] = qp1;
mbQps[2][mbAddr] = qp2;
mergeResidual(mb, residual, transform8x8Used ? COMP_BLOCK_8x8_LUT : COMP_BLOCK_4x4_LUT,
transform8x8Used ? COMP_POS_8x8_LUT : COMP_POS_4x4_LUT);
collectPredictors(mb, mbX);
mbTypes[mbAddr] = topMBType[mbX] = leftMBType = curMBType;
topCBPLuma[mbX] = leftCBPLuma = cbpLuma;
topCBPChroma[mbX] = leftCBPChroma = cbpChroma;
tf8x8Left = tf8x8Top[mbX] = transform8x8Used;
tr8x8Used[mbAddr] = transform8x8Used;
}
private void decodeMBBiDirect(int mbIdx, BitReader reader, boolean field, MBType prevMbType, Picture8Bit mb,
Frame[][] references) {
int mbX = mapper.getMbX(mbIdx);
int mbY = mapper.getMbY(mbIdx);
int mbAddr = mapper.getAddress(mbIdx);
boolean lAvb = mapper.leftAvailable(mbIdx);
boolean tAvb = mapper.topAvailable(mbIdx);
boolean tlAvb = mapper.topLeftAvailable(mbIdx);
boolean trAvb = mapper.topRightAvailable(mbIdx);
int[][][] x = new int[2][16][3];
for (int i = 0; i < 16; i++)
x[0][i][2] = x[1][i][2] = -1;
PartPred[] pp = new PartPred[4];
predictBDirect(references, mbX, mbY, lAvb, tAvb, tlAvb, trAvb, x, pp, mb, identityMapping4);
predictChromaInter(references, x, mbX << 3, mbY << 3, 1, mb, pp);
predictChromaInter(references, x, mbX << 3, mbY << 3, 2, mb, pp);
int codedBlockPattern = readCodedBlockPatternInter(reader, lAvb, tAvb, leftCBPLuma | (leftCBPChroma << 4),
topCBPLuma[mbX] | (topCBPChroma[mbX] << 4), leftMBType, topMBType[mbX]);
int cbpLuma = codedBlockPattern & 0xf;
int cbpChroma = codedBlockPattern >> 4;
boolean transform8x8Used = false;
if (transform8x8 && cbpLuma != 0 && activeSps.direct_8x8_inference_flag) {
transform8x8Used = readTransform8x8Flag(reader, lAvb, tAvb, leftMBType, topMBType[mbX], tf8x8Left,
tf8x8Top[mbX]);
}
if (cbpLuma > 0 || cbpChroma > 0) {
qp = (qp + readMBQpDelta(reader, prevMbType) + 52) % 52;
}
mbQps[0][mbAddr] = qp;
int[][][] residual = {
transform8x8Used ? new int[4][64] : new int[16][16],
new int[4][16],
new int[4][16]
};
residualLuma(reader, lAvb, tAvb, mbX, mbY, codedBlockPattern, MBType.P_8x8, transform8x8Used, tf8x8Left,
tf8x8Top[mbX], residual[0]);
savePrediction8x8(mbX, x[0], 0);
savePrediction8x8(mbX, x[1], 1);
saveMvs(x, mbX, mbY);
int qp1 = calcQpChroma(qp, chromaQpOffset[0]);
int qp2 = calcQpChroma(qp, chromaQpOffset[1]);
decodeChromaResidual(reader, lAvb, tAvb, mbX, mbY, codedBlockPattern >> 4, qp1, qp2, MBType.P_16x16, residual[1], residual[2]);
mbQps[1][mbAddr] = qp1;
mbQps[2][mbAddr] = qp2;
mergeResidual(mb, residual, transform8x8Used ? COMP_BLOCK_8x8_LUT : COMP_BLOCK_4x4_LUT,
transform8x8Used ? COMP_POS_8x8_LUT : COMP_POS_4x4_LUT);
collectPredictors(mb, mbX);
mbTypes[mbAddr] = topMBType[mbX] = leftMBType = MBType.B_Direct_16x16;
topCBPLuma[mbX] = leftCBPLuma = cbpLuma;
topCBPChroma[mbX] = leftCBPChroma = cbpChroma;
tf8x8Left = tf8x8Top[mbX] = transform8x8Used;
tr8x8Used[mbAddr] = transform8x8Used;
predModeTop[mbX << 1] = predModeTop[(mbX << 1) + 1] = predModeLeft[0] = predModeLeft[1] = Direct;
}
public void decodeSkip(Frame[][] refs, int mbIdx, Picture8Bit mb, SliceType sliceType) {
int mbX = mapper.getMbX(mbIdx);
int mbY = mapper.getMbY(mbIdx);
int mbAddr = mapper.getAddress(mbIdx);
int[][][] x = new int[2][16][3];
PartPred[] pp = new PartPred[4];
for (int i = 0; i < 16; i++)
x[0][i][2] = x[1][i][2] = -1;
if (sliceType == P) {
predictPSkip(refs, mbX, mbY, mapper.leftAvailable(mbIdx), mapper.topAvailable(mbIdx),
mapper.topLeftAvailable(mbIdx), mapper.topRightAvailable(mbIdx), x, mb);
Arrays.fill(pp, PartPred.L0);
} else {
predictBDirect(refs, mbX, mbY, mapper.leftAvailable(mbIdx), mapper.topAvailable(mbIdx),
mapper.topLeftAvailable(mbIdx), mapper.topRightAvailable(mbIdx), x, pp, mb, identityMapping4);
savePrediction8x8(mbX, x[0], 0);
savePrediction8x8(mbX, x[1], 1);
}
decodeChromaSkip(refs, x, pp, mbX, mbY, mb);
collectPredictors(mb, mbX);
saveMvs(x, mbX, mbY);
mbTypes[mbAddr] = topMBType[mbX] = leftMBType = null;
mbQps[0][mbAddr] = qp;
mbQps[1][mbAddr] = calcQpChroma(qp, chromaQpOffset[0]);
mbQps[2][mbAddr] = calcQpChroma(qp, chromaQpOffset[1]);
}
public void decodeChroma(BitReader reader, int pattern, int chromaMode, int mbX, int mbY, boolean leftAvailable,
boolean topAvailable, Picture8Bit mb, int qp, MBType curMbType) {
if (chromaFormat == MONO) {
Arrays.fill(mb.getPlaneData(1), (byte) 0);
Arrays.fill(mb.getPlaneData(2), (byte) 0);
return;
}
int[][] residualCb = new int[4][16];
int[][] residualCr = new int[4][16];
int qp1 = calcQpChroma(qp, chromaQpOffset[0]);
int qp2 = calcQpChroma(qp, chromaQpOffset[1]);
if (pattern != 0) {
decodeChromaResidual(reader, leftAvailable, topAvailable, mbX, mbY, pattern, qp1, qp2, curMbType, residualCb, residualCr);
} else if (!activePps.entropy_coding_mode_flag) {
cavlc[1].setZeroCoeff(mbX << 1, 0);
cavlc[1].setZeroCoeff((mbX << 1) + 1, 1);
cavlc[2].setZeroCoeff(mbX << 1, 0);
cavlc[2].setZeroCoeff((mbX << 1) + 1, 1);
}
int addr = mbY * (activeSps.pic_width_in_mbs_minus1 + 1) + mbX;
mbQps[1][addr] = qp1;
mbQps[2][addr] = qp2;
ChromaPredictionBuilder.predictWithMode(residualCb, chromaMode, mbX, leftAvailable, topAvailable,
leftRow[1], topLine[1], topLeft[1], mb.getPlaneData(1));
ChromaPredictionBuilder.predictWithMode(residualCr, chromaMode, mbX, leftAvailable, topAvailable,
leftRow[2], topLine[2], topLeft[2], mb.getPlaneData(2));
}
private void decodeChromaResidual(BitReader reader, boolean leftAvailable, boolean topAvailable, int mbX, int mbY,
int pattern, int crQp1, int crQp2, MBType curMbType, int[][] residualCbOut, int[][] residualCrOut) {
int[] dc1 = new int[(16 >> chromaFormat.compWidth[1]) >> chromaFormat.compHeight[1]];
int[] dc2 = new int[(16 >> chromaFormat.compWidth[2]) >> chromaFormat.compHeight[2]];
if ((pattern & 3) > 0) {
chromaDC(reader, mbX, leftAvailable, topAvailable, dc1, 1, crQp1, curMbType);
chromaDC(reader, mbX, leftAvailable, topAvailable, dc2, 2, crQp2, curMbType);
}
chromaAC(reader, leftAvailable, topAvailable, mbX, mbY, dc1, 1, crQp1, curMbType, (pattern & 2) > 0, residualCbOut);
chromaAC(reader, leftAvailable, topAvailable, mbX, mbY, dc2, 2, crQp2, curMbType, (pattern & 2) > 0, residualCrOut);
}
private void chromaDC(BitReader reader, int mbX, boolean leftAvailable, boolean topAvailable, int[] dc, int comp,
int crQp, MBType curMbType) {
if (!activePps.entropy_coding_mode_flag)
cavlc[comp].readChromaDCBlock(reader, dc, leftAvailable, topAvailable);
else {
if (cabac.readCodedBlockFlagChromaDC(mDecoder, mbX, comp, leftMBType, topMBType[mbX], leftAvailable,
topAvailable, leftCBPChroma, topCBPChroma[mbX], curMbType) == 1)
cabac.readCoeffs(mDecoder, BlockType.CHROMA_DC, dc, 0, 4, identityMapping16, identityMapping16,
identityMapping16);
}
CoeffTransformer.invDC2x2(dc);
CoeffTransformer.dequantizeDC2x2(dc, crQp);
}
private void chromaAC(BitReader reader, boolean leftAvailable, boolean topAvailable, int mbX, int mbY,
int[] dc, int comp, int crQp, MBType curMbType, boolean codedAC, int[][] residualOut) {
for (int i = 0; i < dc.length; i++) {
int[] ac = residualOut[i];
int blkOffLeft = H264Const.MB_BLK_OFF_LEFT[i];
int blkOffTop = H264Const.MB_BLK_OFF_TOP[i];
int blkX = (mbX << 1) + blkOffLeft;
int blkY = (mbY << 1) + blkOffTop;
if (codedAC) {
if (!activePps.entropy_coding_mode_flag)
cavlc[comp].readACBlock(reader, ac, blkX, blkOffTop, blkOffLeft != 0 || leftAvailable,
blkOffLeft == 0 ? leftMBType : curMbType, blkOffTop != 0 || topAvailable,
blkOffTop == 0 ? topMBType[mbX] : curMbType, 1, 15, CoeffTransformer.zigzag4x4);
else {
if (cabac.readCodedBlockFlagChromaAC(mDecoder, blkX, blkOffTop, comp, leftMBType, topMBType[mbX],
leftAvailable, topAvailable, leftCBPChroma, topCBPChroma[mbX], curMbType) == 1)
cabac.readCoeffs(mDecoder, BlockType.CHROMA_AC, ac, 1, 15, CoeffTransformer.zigzag4x4,
identityMapping16, identityMapping16);
}
CoeffTransformer.dequantizeAC(ac, crQp);
} else {
if (!activePps.entropy_coding_mode_flag)
cavlc[comp].setZeroCoeff(blkX, blkOffTop);
}
ac[0] = dc[i];
CoeffTransformer.idct4x4(ac);
}
}
private int calcQpChroma(int qp, int crQpOffset) {
return QP_SCALE_CR[MathUtil.clip(qp + crQpOffset, 0, 51)];
}
private int readMBQpDelta(BitReader reader, MBType prevMbType) {
int mbQPDelta;
if (!activePps.entropy_coding_mode_flag) {
mbQPDelta = readSE(reader, "mb_qp_delta");
} else {
mbQPDelta = cabac.readMBQpDelta(mDecoder, prevMbType);
}
return mbQPDelta;
}
private int readChromaPredMode(BitReader reader, int mbX, boolean leftAvailable, boolean topAvailable) {
int chromaPredictionMode;
if (!activePps.entropy_coding_mode_flag) {
chromaPredictionMode = readUE(reader, "MBP: intra_chroma_pred_mode");
} else {
chromaPredictionMode = cabac.readIntraChromaPredMode(mDecoder, mbX, leftMBType, topMBType[mbX],
leftAvailable, topAvailable);
}
return chromaPredictionMode;
}
private void wipe(Picture8Bit mb) {
Arrays.fill(mb.getPlaneData(0), (byte)0);
Arrays.fill(mb.getPlaneData(1), (byte)0);
Arrays.fill(mb.getPlaneData(2), (byte)0);
}
private void collectPredictors(Picture8Bit outMB, int mbX) {
topLeft[0][0] = topLine[0][(mbX << 4) + 15];
topLeft[0][1] = outMB.getPlaneData(0)[63];
topLeft[0][2] = outMB.getPlaneData(0)[127];
topLeft[0][3] = outMB.getPlaneData(0)[191];
System.arraycopy(outMB.getPlaneData(0), 240, topLine[0], mbX << 4, 16);
copyCol(outMB.getPlaneData(0), 16, 15, 16, leftRow[0]);
collectChromaPredictors(outMB, mbX);
}
private void collectChromaPredictors(Picture8Bit outMB, int mbX) {
topLeft[1][0] = topLine[1][(mbX << 3) + 7];
topLeft[2][0] = topLine[2][(mbX << 3) + 7];
System.arraycopy(outMB.getPlaneData(1), 56, topLine[1], mbX << 3, 8);
System.arraycopy(outMB.getPlaneData(2), 56, topLine[2], mbX << 3, 8);
copyCol(outMB.getPlaneData(1), 8, 7, 8, leftRow[1]);
copyCol(outMB.getPlaneData(2), 8, 7, 8, leftRow[2]);
}
private void copyCol(byte[] planeData, int n, int off, int stride, byte[] out) {
for (int i = 0; i < n; i++, off += stride) {
out[i] = planeData[off];
}
}
private void residualLumaI16x16(BitReader reader, boolean leftAvailable, boolean topAvailable, int mbX, int mbY,
int cbpLuma, int[][] residualOut) {
int[] dc = new int[16];
if (!activePps.entropy_coding_mode_flag)
cavlc[0].readLumaDCBlock(reader, dc, mbX, leftAvailable, leftMBType, topAvailable, topMBType[mbX],
CoeffTransformer.zigzag4x4);
else {
if (cabac.readCodedBlockFlagLumaDC(mDecoder, mbX, leftMBType, topMBType[mbX], leftAvailable, topAvailable,
MBType.I_16x16) == 1)
cabac.readCoeffs(mDecoder, BlockType.LUMA_16_DC, dc, 0, 16, CoeffTransformer.zigzag4x4,
identityMapping16, identityMapping16);
}
CoeffTransformer.invDC4x4(dc);
CoeffTransformer.dequantizeDC4x4(dc, qp);
reorderDC4x4(dc);
for (int i = 0; i < 16; i++) {
int[] ac = residualOut[i];
int blkOffLeft = H264Const.MB_BLK_OFF_LEFT[i];
int blkOffTop = H264Const.MB_BLK_OFF_TOP[i];
int blkX = (mbX << 2) + blkOffLeft;
int blkY = (mbY << 2) + blkOffTop;
if ((cbpLuma & (1 << (i >> 2))) != 0) {
if (!activePps.entropy_coding_mode_flag) {
nCoeff[blkY][blkX] = cavlc[0].readACBlock(reader, ac, blkX, blkOffTop, blkOffLeft != 0
|| leftAvailable, blkOffLeft == 0 ? leftMBType : I_16x16, blkOffTop != 0 || topAvailable,
blkOffTop == 0 ? topMBType[mbX] : I_16x16, 1, 15, CoeffTransformer.zigzag4x4);
} else {
if (cabac.readCodedBlockFlagLumaAC(mDecoder, BlockType.LUMA_15_AC, blkX, blkOffTop, 0, leftMBType,
topMBType[mbX], leftAvailable, topAvailable, leftCBPLuma, topCBPLuma[mbX], cbpLuma,
MBType.I_16x16) == 1)
nCoeff[blkY][blkX] = cabac.readCoeffs(mDecoder, BlockType.LUMA_15_AC, ac, 1, 15,
CoeffTransformer.zigzag4x4, identityMapping16, identityMapping16);
}
CoeffTransformer.dequantizeAC(ac, qp);
} else {
if (!activePps.entropy_coding_mode_flag)
cavlc[0].setZeroCoeff(blkX, blkOffTop);
}
ac[0] = dc[i];
CoeffTransformer.idct4x4(ac);
}
}
private void residualLuma(BitReader reader, boolean leftAvailable, boolean topAvailable, int mbX, int mbY,
int codedBlockPattern, MBType mbType, boolean transform8x8Used, boolean is8x8Left,
boolean is8x8Top, int[][] residualOut) {
if (!transform8x8Used)
residualLuma(reader, leftAvailable, topAvailable, mbX, mbY, codedBlockPattern, mbType, residualOut);
else if (activePps.entropy_coding_mode_flag)
residualLuma8x8CABAC(reader, leftAvailable, topAvailable, mbX, mbY, codedBlockPattern, mbType,
is8x8Left, is8x8Top, residualOut);
else
residualLuma8x8CAVLC(reader, leftAvailable, topAvailable, mbX, mbY, codedBlockPattern, mbType, residualOut);
}
private void residualLuma(BitReader reader, boolean leftAvailable, boolean topAvailable, int mbX, int mbY,
int codedBlockPattern, MBType curMbType, int[][] residualOut) {
int cbpLuma = codedBlockPattern & 0xf;
for (int i = 0; i < 16; i++) {
int blkOffLeft = H264Const.MB_BLK_OFF_LEFT[i];
int blkOffTop = H264Const.MB_BLK_OFF_TOP[i];
int blkX = (mbX << 2) + blkOffLeft;
int blkY = (mbY << 2) + blkOffTop;
if ((cbpLuma & (1 << (i >> 2))) == 0) {
if (!activePps.entropy_coding_mode_flag)
cavlc[0].setZeroCoeff(blkX, blkOffTop);
continue;
}
int[] ac = residualOut[i];
if (!activePps.entropy_coding_mode_flag) {
nCoeff[blkY][blkX] = cavlc[0].readACBlock(reader, ac, blkX, blkOffTop,
blkOffLeft != 0 || leftAvailable, blkOffLeft == 0 ? leftMBType : curMbType, blkOffTop != 0
|| topAvailable, blkOffTop == 0 ? topMBType[mbX] : curMbType, 0, 16,
CoeffTransformer.zigzag4x4);
} else {
if (cabac.readCodedBlockFlagLumaAC(mDecoder, BlockType.LUMA_16, blkX, blkOffTop, 0, leftMBType,
topMBType[mbX], leftAvailable, topAvailable, leftCBPLuma, topCBPLuma[mbX], cbpLuma, curMbType) == 1)
nCoeff[blkY][blkX] = cabac.readCoeffs(mDecoder, BlockType.LUMA_16, ac, 0, 16,
CoeffTransformer.zigzag4x4, identityMapping16, identityMapping16);
}
CoeffTransformer.dequantizeAC(ac, qp);
CoeffTransformer.idct4x4(ac);
}
if (activePps.entropy_coding_mode_flag)
cabac.setPrevCBP(codedBlockPattern);
}
private void residualLuma8x8CABAC(BitReader reader, boolean leftAvailable, boolean topAvailable, int mbX, int mbY,
int codedBlockPattern, MBType curMbType, boolean is8x8Left, boolean is8x8Top, int[][] residualOut) {
int cbpLuma = codedBlockPattern & 0xf;
for (int i = 0; i < 4; i++) {
int blkOffLeft = (i & 1) << 1;
int blkOffTop = i & 2;
int blkX = (mbX << 2) + blkOffLeft;
int blkY = (mbY << 2) + blkOffTop;
if ((cbpLuma & (1 << i)) == 0) {
continue;
}
int[] ac = residualOut[i];
nCoeff[blkY][blkX] = nCoeff[blkY][blkX + 1] = nCoeff[blkY + 1][blkX] = nCoeff[blkY + 1][blkX + 1] = cabac
.readCoeffs(mDecoder, BlockType.LUMA_64, ac, 0, 64, CoeffTransformer.zigzag8x8, sig_coeff_map_8x8,
last_sig_coeff_map_8x8);
cabac.setCodedBlock(blkX, blkY);
cabac.setCodedBlock(blkX + 1, blkY);
cabac.setCodedBlock(blkX, blkY + 1);
cabac.setCodedBlock(blkX + 1, blkY + 1);
CoeffTransformer.dequantizeAC8x8(ac, qp);
CoeffTransformer.idct8x8(ac);
}
cabac.setPrevCBP(codedBlockPattern);
}
private void residualLuma8x8CAVLC(BitReader reader, boolean leftAvailable, boolean topAvailable, int mbX, int mbY,
int codedBlockPattern, MBType curMbType, int[][] residualOut) {
int cbpLuma = codedBlockPattern & 0xf;
for (int i = 0; i < 4; i++) {
int blk8x8OffLeft = (i & 1) << 1;
int blk8x8OffTop = i & 2;
int blkX = (mbX << 2) + blk8x8OffLeft;
int blkY = (mbY << 2) + blk8x8OffTop;
if ((cbpLuma & (1 << i)) == 0) {
cavlc[0].setZeroCoeff(blkX, blk8x8OffTop);
cavlc[0].setZeroCoeff(blkX + 1, blk8x8OffTop);
cavlc[0].setZeroCoeff(blkX, blk8x8OffTop + 1);
cavlc[0].setZeroCoeff(blkX + 1, blk8x8OffTop + 1);
continue;
}
int[] ac64 = residualOut[i];
int coeffs = 0;
for (int j = 0; j < 4; j++) {
int[] ac16 = new int[16];
int blkOffLeft = blk8x8OffLeft + (j & 1);
int blkOffTop = blk8x8OffTop + (j >> 1);
coeffs += cavlc[0].readACBlock(reader, ac16, blkX + (j & 1), blkOffTop, blkOffLeft != 0
|| leftAvailable, blkOffLeft == 0 ? leftMBType : curMbType, blkOffTop != 0 || topAvailable,
blkOffTop == 0 ? topMBType[mbX] : curMbType, 0, 16, H264Const.identityMapping16);
for (int k = 0; k < 16; k++)
ac64[CoeffTransformer.zigzag8x8[(k << 2) + j]] = ac16[k];
}
nCoeff[blkY][blkX] = nCoeff[blkY][blkX + 1] = nCoeff[blkY + 1][blkX] = nCoeff[blkY + 1][blkX + 1] = coeffs;
CoeffTransformer.dequantizeAC8x8(ac64, qp);
CoeffTransformer.idct8x8(ac64);
}
}
private int[][][] residualInter(BitReader reader, Frame[][] refs, boolean leftAvailable,
boolean topAvailable, int mbX, int mbY, int[][][] x, PartPred[] pp, int mbAddr, MBType prevMbType,
MBType curMbType) {
int codedBlockPattern = readCodedBlockPatternInter(reader, leftAvailable, topAvailable, leftCBPLuma
| (leftCBPChroma << 4), topCBPLuma[mbX] | (topCBPChroma[mbX] << 4), leftMBType, topMBType[mbX]);
int cbpLuma = codedBlockPattern & 0xf;
int cbpChroma = codedBlockPattern >> 4;
boolean transform8x8Used = false;
if (cbpLuma != 0 && transform8x8) {
transform8x8Used = readTransform8x8Flag(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX],
tf8x8Left, tf8x8Top[mbX]);
}
int[][][] residualOut = {
transform8x8Used ? new int[4][64] : new int[16][16],
new int[4][16],
new int[4][16]
};
if (cbpLuma > 0 || cbpChroma > 0) {
int mbQpDelta = readMBQpDelta(reader, prevMbType);
qp = (qp + mbQpDelta + 52) % 52;
}
mbQps[0][mbAddr] = qp;
residualLuma(reader, leftAvailable, topAvailable, mbX, mbY, codedBlockPattern, curMbType,
transform8x8Used, tf8x8Left, tf8x8Top[mbX], residualOut[0]);
saveMvs(x, mbX, mbY);
if (chromaFormat != MONO) {
int qp1 = calcQpChroma(qp, chromaQpOffset[0]);
int qp2 = calcQpChroma(qp, chromaQpOffset[1]);
decodeChromaResidual(reader, leftAvailable, topAvailable, mbX, mbY, cbpChroma, qp1, qp2, MBType.P_16x16, residualOut[1], residualOut[2]);
mbQps[1][mbAddr] = qp1;
mbQps[2][mbAddr] = qp2;
}
topCBPLuma[mbX] = leftCBPLuma = cbpLuma;
topCBPChroma[mbX] = leftCBPChroma = cbpChroma;
tf8x8Left = tf8x8Top[mbX] = transform8x8Used;
tr8x8Used[mbAddr] = transform8x8Used;
return residualOut;
}
private void saveMvsIntra(int mbX, int mbY) {
for (int j = 0, blkOffY = mbY << 2, blkInd = 0; j < 4; j++, blkOffY++) {
for (int i = 0, blkOffX = mbX << 2; i < 4; i++, blkOffX++, blkInd++) {
mvs[0][blkOffY][blkOffX] = NULL_VECTOR;
mvs[1][blkOffY][blkOffX] = NULL_VECTOR;
}
}
}
private boolean readTransform8x8Flag(BitReader reader, boolean leftAvailable, boolean topAvailable,
MBType leftType, MBType topType, boolean is8x8Left, boolean is8x8Top) {
if (!activePps.entropy_coding_mode_flag)
return readBool(reader, "transform_size_8x8_flag");
else
return cabac.readTransform8x8Flag(mDecoder, leftAvailable, topAvailable, leftType, topType, is8x8Left,
is8x8Top);
}
protected int readCodedBlockPatternIntra(BitReader reader, boolean leftAvailable, boolean topAvailable,
int leftCBP, int topCBP, MBType leftMB, MBType topMB) {
if (!activePps.entropy_coding_mode_flag)
return H264Const.CODED_BLOCK_PATTERN_INTRA_COLOR[readUE(reader, "coded_block_pattern")];
else
return cabac.codedBlockPatternIntra(mDecoder, leftAvailable, topAvailable, leftCBP, topCBP, leftMB, topMB);
}
protected int readCodedBlockPatternInter(BitReader reader, boolean leftAvailable, boolean topAvailable,
int leftCBP, int topCBP, MBType leftMB, MBType topMB) {
if (!activePps.entropy_coding_mode_flag)
return H264Const.CODED_BLOCK_PATTERN_INTER_COLOR[readUE(reader, "coded_block_pattern")];
else
return cabac.codedBlockPatternIntra(mDecoder, leftAvailable, topAvailable, leftCBP, topCBP, leftMB, topMB);
}
private int readPredictionI4x4Block(BitReader reader, boolean leftAvailable, boolean topAvailable,
MBType leftMBType, MBType topMBType, int blkX, int blkY, int mbX) {
int mode = 2;
if ((leftAvailable || blkX > 0) && (topAvailable || blkY > 0)) {
int predModeB = topMBType == MBType.I_NxN || blkY > 0 ? i4x4PredTop[(mbX << 2) + blkX] : 2;
int predModeA = leftMBType == MBType.I_NxN || blkX > 0 ? i4x4PredLeft[blkY] : 2;
mode = Math.min(predModeB, predModeA);
}
if (!prev4x4PredMode(reader)) {
int rem_intra4x4_pred_mode = rem4x4PredMode(reader);
mode = rem_intra4x4_pred_mode + (rem_intra4x4_pred_mode < mode ? 0 : 1);
}
i4x4PredTop[(mbX << 2) + blkX] = i4x4PredLeft[blkY] = mode;
return mode;
}
private int rem4x4PredMode(BitReader reader) {
if (!activePps.entropy_coding_mode_flag)
return readNBit(reader, 3, "MB: rem_intra4x4_pred_mode");
else
return cabac.rem4x4PredMode(mDecoder);
}
private boolean prev4x4PredMode(BitReader reader) {
if (!activePps.entropy_coding_mode_flag)
return readBool(reader, "MBP: prev_intra4x4_pred_mode_flag");
else
return cabac.prev4x4PredModeFlag(mDecoder);
}
private void predictInter16x8(BitReader reader, Picture8Bit mb, Picture8Bit[][] references, int mbX, int mbY,
boolean leftAvailable, boolean topAvailable, boolean tlAvailable, boolean trAvailable, int xx,
int[] refIdx1, int[] refIdx2, int[][][] x, PartPred p0, PartPred p1, int list) {
int blk8x8X = mbX << 1;
int mvX1 = 0, mvY1 = 0, mvX2 = 0, mvY2 = 0, r1 = -1, r2 = -1;
if (p0.usesList(list)) {
int mvdX1 = readMVD(reader, 0, leftAvailable, topAvailable, leftMBType, topMBType[mbX], predModeLeft[0],
predModeTop[blk8x8X], p0, mbX, 0, 0, 4, 2, list);
int mvdY1 = readMVD(reader, 1, leftAvailable, topAvailable, leftMBType, topMBType[mbX], predModeLeft[0],
predModeTop[blk8x8X], p0, mbX, 0, 0, 4, 2, list);
int mvpX1 = calcMVPrediction16x8Top(mvLeft[list][0], mvTop[list][mbX << 2], mvTop[list][(mbX << 2) + 4],
mvTopLeft[list], leftAvailable, topAvailable, trAvailable, tlAvailable, refIdx1[list], 0);
int mvpY1 = calcMVPrediction16x8Top(mvLeft[list][0], mvTop[list][mbX << 2], mvTop[list][(mbX << 2) + 4],
mvTopLeft[list], leftAvailable, topAvailable, trAvailable, tlAvailable, refIdx1[list], 1);
mvX1 = mvdX1 + mvpX1;
mvY1 = mvdY1 + mvpY1;
debugPrint("MVP: (" + mvpX1 + ", " + mvpY1 + "), MVD: (" + mvdX1 + ", " + mvdY1 + "), MV: (" + mvX1 + ","
+ mvY1 + "," + refIdx1[list] + ")");
BlockInterpolator.getBlockLuma(references[list][refIdx1[list]], mb, 0, (mbX << 6) + mvX1,
(mbY << 6) + mvY1, 16, 8);
r1 = refIdx1[list];
}
int[] v1 = { mvX1, mvY1, r1 };
if (p1.usesList(list)) {
int mvdX2 = readMVD(reader, 0, leftAvailable, true, leftMBType, MBType.P_16x8, predModeLeft[1], p0, p1,
mbX, 0, 2, 4, 2, list);
int mvdY2 = readMVD(reader, 1, leftAvailable, true, leftMBType, MBType.P_16x8, predModeLeft[1], p0, p1,
mbX, 0, 2, 4, 2, list);
int mvpX2 = calcMVPrediction16x8Bottom(mvLeft[list][2], v1, null, mvLeft[list][1], leftAvailable, true,
false, leftAvailable, refIdx2[list], 0);
int mvpY2 = calcMVPrediction16x8Bottom(mvLeft[list][2], v1, null, mvLeft[list][1], leftAvailable, true,
false, leftAvailable, refIdx2[list], 1);
mvX2 = mvdX2 + mvpX2;
mvY2 = mvdY2 + mvpY2;
debugPrint("MVP: (" + mvpX2 + ", " + mvpY2 + "), MVD: (" + mvdX2 + ", " + mvdY2 + "), MV: (" + mvX2 + ","
+ mvY2 + "," + refIdx2[list] + ")");
BlockInterpolator.getBlockLuma(references[list][refIdx2[list]], mb, 128, (mbX << 6) + mvX2, (mbY << 6) + 32
+ mvY2, 16, 8);
r2 = refIdx2[list];
}
int[] v2 = { mvX2, mvY2, r2 };
copyVect(mvTopLeft[list], mvTop[list][xx + 3]);
saveVect(mvLeft[list], 0, 2, mvX1, mvY1, r1);
saveVect(mvLeft[list], 2, 4, mvX2, mvY2, r2);
saveVect(mvTop[list], xx, xx + 4, mvX2, mvY2, r2);
x[list] = new int[][] { v1, v1, v1, v1, v1, v1, v1, v1, v2, v2, v2, v2, v2, v2, v2, v2 };
}
private void mergeResidual(Picture8Bit mb, int[][][] residual, int[][] blockLUT, int[][] posLUT) {
for (int comp = 0; comp < 3; comp++) {
byte[] to = mb.getPlaneData(comp);
for (int i = 0; i < to.length; i++) {
to[i] = (byte)clip(to[i] + residual[comp][blockLUT[comp][i]][posLUT[comp][i]], -128, 127);
}
}
}
private void predictInter8x16(BitReader reader, Picture8Bit mb, Picture8Bit[][] references, int mbX, int mbY,
boolean leftAvailable, boolean topAvailable, boolean tlAvailable, boolean trAvailable, int[][][] x,
int[] refIdx1, int[] refIdx2, int list, PartPred p0, PartPred p1) {
int xx = mbX << 2;
int blk8x8X = (mbX << 1);
int mvX1 = 0, mvY1 = 0, r1 = -1, mvX2 = 0, mvY2 = 0, r2 = -1;
if (p0.usesList(list)) {
int mvdX1 = readMVD(reader, 0, leftAvailable, topAvailable, leftMBType, topMBType[mbX], predModeLeft[0],
predModeTop[blk8x8X], p0, mbX, 0, 0, 2, 4, list);
int mvdY1 = readMVD(reader, 1, leftAvailable, topAvailable, leftMBType, topMBType[mbX], predModeLeft[0],
predModeTop[blk8x8X], p0, mbX, 0, 0, 2, 4, list);
int mvpX1 = calcMVPrediction8x16Left(mvLeft[list][0], mvTop[list][mbX << 2], mvTop[list][(mbX << 2) + 2],
mvTopLeft[list], leftAvailable, topAvailable, topAvailable, tlAvailable, refIdx1[list], 0);
int mvpY1 = calcMVPrediction8x16Left(mvLeft[list][0], mvTop[list][mbX << 2], mvTop[list][(mbX << 2) + 2],
mvTopLeft[list], leftAvailable, topAvailable, topAvailable, tlAvailable, refIdx1[list], 1);
mvX1 = mvdX1 + mvpX1;
mvY1 = mvdY1 + mvpY1;
debugPrint("MVP: (" + mvpX1 + ", " + mvpY1 + "), MVD: (" + mvdX1 + ", " + mvdY1 + "), MV: (" + mvX1 + ","
+ mvY1 + "," + refIdx1[list] + ")");
BlockInterpolator.getBlockLuma(references[list][refIdx1[list]], mb, 0, (mbX << 6) + mvX1,
(mbY << 6) + mvY1, 8, 16);
r1 = refIdx1[list];
}
int[] v1 = { mvX1, mvY1, r1 };
if (p1.usesList(list)) {
int mvdX2 = readMVD(reader, 0, true, topAvailable, MBType.P_8x16, topMBType[mbX], p0,
predModeTop[blk8x8X + 1], p1, mbX, 2, 0, 2, 4, list);
int mvdY2 = readMVD(reader, 1, true, topAvailable, MBType.P_8x16, topMBType[mbX], p0,
predModeTop[blk8x8X + 1], p1, mbX, 2, 0, 2, 4, list);
int mvpX2 = calcMVPrediction8x16Right(v1, mvTop[list][(mbX << 2) + 2], mvTop[list][(mbX << 2) + 4],
mvTop[list][(mbX << 2) + 1], true, topAvailable, trAvailable, topAvailable, refIdx2[list], 0);
int mvpY2 = calcMVPrediction8x16Right(v1, mvTop[list][(mbX << 2) + 2], mvTop[list][(mbX << 2) + 4],
mvTop[list][(mbX << 2) + 1], true, topAvailable, trAvailable, topAvailable, refIdx2[list], 1);
mvX2 = mvdX2 + mvpX2;
mvY2 = mvdY2 + mvpY2;
debugPrint("MVP: (" + mvpX2 + ", " + mvpY2 + "), MVD: (" + mvdX2 + ", " + mvdY2 + "), MV: (" + mvX2 + ","
+ mvY2 + "," + refIdx2[list] + ")");
BlockInterpolator.getBlockLuma(references[list][refIdx2[list]], mb, 8, (mbX << 6) + 32 + mvX2, (mbY << 6)
+ mvY2, 8, 16);
r2 = refIdx2[list];
}
int[] v2 = { mvX2, mvY2, r2 };
copyVect(mvTopLeft[list], mvTop[list][xx + 3]);
saveVect(mvTop[list], xx, xx + 2, mvX1, mvY1, r1);
saveVect(mvTop[list], xx + 2, xx + 4, mvX2, mvY2, r2);
saveVect(mvLeft[list], 0, 4, mvX2, mvY2, r2);
x[list] = new int[][] { v1, v1, v2, v2, v1, v1, v2, v2, v1, v1, v2, v2, v1, v1, v2, v2 };
}
private void predictInter16x16(BitReader reader, Picture8Bit mb, Picture8Bit[][] references, int mbX, int mbY,
boolean leftAvailable, boolean topAvailable, boolean tlAvailable, boolean trAvailable, int[][][] x, int xx,
int[] refIdx, int list, PartPred curPred) {
int blk8x8X = (mbX << 1);
int mvX = 0, mvY = 0, r = -1;
if (curPred.usesList(list)) {
int mvpX = calcMVPredictionMedian(mvLeft[list][0], mvTop[list][mbX << 2], mvTop[list][(mbX << 2) + 4],
mvTopLeft[list], leftAvailable, topAvailable, trAvailable, tlAvailable, refIdx[list], 0);
int mvpY = calcMVPredictionMedian(mvLeft[list][0], mvTop[list][mbX << 2], mvTop[list][(mbX << 2) + 4],
mvTopLeft[list], leftAvailable, topAvailable, trAvailable, tlAvailable, refIdx[list], 1);
int mvdX = readMVD(reader, 0, leftAvailable, topAvailable, leftMBType, topMBType[mbX], predModeLeft[0],
predModeTop[blk8x8X], curPred, mbX, 0, 0, 4, 4, list);
int mvdY = readMVD(reader, 1, leftAvailable, topAvailable, leftMBType, topMBType[mbX], predModeLeft[0],
predModeTop[blk8x8X], curPred, mbX, 0, 0, 4, 4, list);
mvX = mvdX + mvpX;
mvY = mvdY + mvpY;
debugPrint("MVP: (" + mvpX + ", " + mvpY + "), MVD: (" + mvdX + ", " + mvdY + "), MV: (" + mvX + "," + mvY
+ "," + refIdx[list] + ")");
r = refIdx[list];
BlockInterpolator.getBlockLuma(references[list][r], mb, 0, (mbX << 6) + mvX, (mbY << 6) + mvY, 16, 16);
}
copyVect(mvTopLeft[list], mvTop[list][xx + 3]);
saveVect(mvTop[list], xx, xx + 4, mvX, mvY, r);
saveVect(mvLeft[list], 0, 4, mvX, mvY, r);
int[] v = { mvX, mvY, r };
x[list] = new int[][] { v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v };
}
private int readRefIdx(BitReader reader, boolean leftAvailable, boolean topAvailable, MBType leftType,
MBType topType, PartPred leftPred, PartPred topPred, PartPred curPred, int mbX, int partX, int partY,
int partW, int partH, int list) {
if (!activePps.entropy_coding_mode_flag)
return readTE(reader, numRef[list] - 1);
else
return cabac.readRefIdx(mDecoder, leftAvailable, topAvailable, leftType, topType, leftPred, topPred,
curPred, mbX, partX, partY, partW, partH, list);
}
private void saveVect(int[][] mv, int from, int to, int x, int y, int r) {
for (int i = from; i < to; i++) {
mv[i][0] = x;
mv[i][1] = y;
mv[i][2] = r;
}
}
public int calcMVPredictionMedian(int[] a, int[] b, int[] c, int[] d, boolean aAvb, boolean bAvb, boolean cAvb,
boolean dAvb, int ref, int comp) {
if (!cAvb) {
c = d;
cAvb = dAvb;
}
if (aAvb && !bAvb && !cAvb) {
b = c = a;
bAvb = cAvb = aAvb;
}
a = aAvb ? a : NULL_VECTOR;
b = bAvb ? b : NULL_VECTOR;
c = cAvb ? c : NULL_VECTOR;
if (a[2] == ref && b[2] != ref && c[2] != ref)
return a[comp];
else if (b[2] == ref && a[2] != ref && c[2] != ref)
return b[comp];
else if (c[2] == ref && a[2] != ref && b[2] != ref)
return c[comp];
return a[comp] + b[comp] + c[comp] - min(a[comp], b[comp], c[comp]) - max(a[comp], b[comp], c[comp]);
}
private int max(int x, int x2, int x3) {
return x > x2 ? (x > x3 ? x : x3) : (x2 > x3 ? x2 : x3);
}
private int min(int x, int x2, int x3) {
return x < x2 ? (x < x3 ? x : x3) : (x2 < x3 ? x2 : x3);
}
public int calcMVPrediction16x8Top(int[] a, int[] b, int[] c, int[] d, boolean aAvb, boolean bAvb, boolean cAvb,
boolean dAvb, int refIdx, int comp) {
if (bAvb && b[2] == refIdx)
return b[comp];
else
return calcMVPredictionMedian(a, b, c, d, aAvb, bAvb, cAvb, dAvb, refIdx, comp);
}
public int calcMVPrediction16x8Bottom(int[] a, int[] b, int[] c, int[] d, boolean aAvb, boolean bAvb, boolean cAvb,
boolean dAvb, int refIdx, int comp) {
if (aAvb && a[2] == refIdx)
return a[comp];
else
return calcMVPredictionMedian(a, b, c, d, aAvb, bAvb, cAvb, dAvb, refIdx, comp);
}
public int calcMVPrediction8x16Left(int[] a, int[] b, int[] c, int[] d, boolean aAvb, boolean bAvb, boolean cAvb,
boolean dAvb, int refIdx, int comp) {
if (aAvb && a[2] == refIdx)
return a[comp];
else
return calcMVPredictionMedian(a, b, c, d, aAvb, bAvb, cAvb, dAvb, refIdx, comp);
}
public int calcMVPrediction8x16Right(int[] a, int[] b, int[] c, int[] d, boolean aAvb, boolean bAvb, boolean cAvb,
boolean dAvb, int refIdx, int comp) {
int[] lc = cAvb ? c : (dAvb ? d : NULL_VECTOR);
if (lc[2] == refIdx)
return lc[comp];
else
return calcMVPredictionMedian(a, b, c, d, aAvb, bAvb, cAvb, dAvb, refIdx, comp);
}
private boolean predict8x8P(BitReader reader, Picture8Bit[] references, Picture8Bit mb, boolean ref0, int mbX, int mbY,
boolean leftAvailable, boolean topAvailable, boolean tlAvailable, boolean topRightAvailable, int[][][] x,
PartPred[] pp) {
int[] subMbTypes = new int[4];
for (int i = 0; i < 4; i++) {
subMbTypes[i] = readSubMBTypeP(reader);
}
Arrays.fill(pp, L0);
int blk8x8X = mbX << 1;
int[] refIdx = new int[4];
if (numRef[0] > 1 && !ref0) {
refIdx[0] = readRefIdx(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX], L0, L0, L0, mbX, 0,
0, 2, 2, 0);
refIdx[1] = readRefIdx(reader, true, topAvailable, P_8x8, topMBType[mbX], L0, L0, L0, mbX, 2, 0, 2, 2, 0);
refIdx[2] = readRefIdx(reader, leftAvailable, true, leftMBType, P_8x8, L0, L0, L0, mbX, 0, 2, 2, 2, 0);
refIdx[3] = readRefIdx(reader, true, true, P_8x8, P_8x8, L0, L0, L0, mbX, 2, 2, 2, 2, 0);
}
decodeSubMb8x8(reader, subMbTypes[0], references, mbX << 6, mbY << 6, x[0], mvTopLeft[0], mvTop[0][mbX << 2],
mvTop[0][(mbX << 2) + 1], mvTop[0][(mbX << 2) + 2], mvLeft[0][0], mvLeft[0][1], tlAvailable,
topAvailable, topAvailable, leftAvailable, x[0][0], x[0][1], x[0][4], x[0][5], refIdx[0], mb, 0, 0, 0,
mbX, leftMBType, topMBType[mbX], P_8x8, L0, L0, L0, 0);
decodeSubMb8x8(reader, subMbTypes[1], references, (mbX << 6) + 32, mbY << 6, x[0], mvTop[0][(mbX << 2) + 1],
mvTop[0][(mbX << 2) + 2], mvTop[0][(mbX << 2) + 3], mvTop[0][(mbX << 2) + 4], x[0][1], x[0][5],
topAvailable, topAvailable, topRightAvailable, true, x[0][2], x[0][3], x[0][6], x[0][7], refIdx[1], mb,
8, 2, 0, mbX, P_8x8, topMBType[mbX], P_8x8, L0, L0, L0, 0);
decodeSubMb8x8(reader, subMbTypes[2], references, mbX << 6, (mbY << 6) + 32, x[0], mvLeft[0][1], x[0][4],
x[0][5], x[0][6], mvLeft[0][2], mvLeft[0][3], leftAvailable, true, true, leftAvailable, x[0][8],
x[0][9], x[0][12], x[0][13], refIdx[2], mb, 128, 0, 2, mbX, leftMBType, P_8x8, P_8x8, L0, L0, L0, 0);
decodeSubMb8x8(reader, subMbTypes[3], references, (mbX << 6) + 32, (mbY << 6) + 32, x[0], x[0][5], x[0][6],
x[0][7], null, x[0][9], x[0][13], true, true, false, true, x[0][10], x[0][11], x[0][14], x[0][15],
refIdx[3], mb, 136, 2, 2, mbX, P_8x8, P_8x8, P_8x8, L0, L0, L0, 0);
savePrediction8x8(mbX, x[0], 0);
predModeLeft[0] = predModeLeft[1] = predModeTop[blk8x8X] = predModeTop[blk8x8X + 1] = L0;
return subMbTypes[0] == 0 && subMbTypes[1] == 0 && subMbTypes[2] == 0 && subMbTypes[3] == 0;
}
private boolean predict8x8B(BitReader reader, Frame[][] refs, Picture8Bit mb, boolean ref0, int mbX, int mbY,
boolean leftAvailable, boolean topAvailable, boolean tlAvailable, boolean topRightAvailable, int[][][] x,
PartPred[] p) {
int[] subMbTypes = new int[4];
for (int i = 0; i < 4; i++) {
subMbTypes[i] = readSubMBTypeB(reader);
p[i] = bPartPredModes[subMbTypes[i]];
}
int[][] refIdx = new int[2][4];
for (int list = 0; list < 2; list++) {
if (numRef[list] <= 1)
continue;
if (p[0].usesList(list))
refIdx[list][0] = readRefIdx(reader, leftAvailable, topAvailable, leftMBType, topMBType[mbX],
predModeLeft[0], predModeTop[mbX << 1], p[0], mbX, 0, 0, 2, 2, list);
if (p[1].usesList(list))
refIdx[list][1] = readRefIdx(reader, true, topAvailable, B_8x8, topMBType[mbX], p[0],
predModeTop[(mbX << 1) + 1], p[1], mbX, 2, 0, 2, 2, list);
if (p[2].usesList(list))
refIdx[list][2] = readRefIdx(reader, leftAvailable, true, leftMBType, B_8x8, predModeLeft[1], p[0],
p[2], mbX, 0, 2, 2, 2, list);
if (p[3].usesList(list))
refIdx[list][3] = readRefIdx(reader, true, true, B_8x8, B_8x8, p[2], p[1], p[3], mbX, 2, 2, 2, 2, list);
}
Picture8Bit[] mbb = { Picture8Bit.create(16, 16, chromaFormat), Picture8Bit.create(16, 16, chromaFormat) };
PartPred[] _pp = new PartPred[4];
for (int i = 0; i < 4; i++) {
if (p[i] == Direct)
predictBDirect(refs, mbX, mbY, leftAvailable, topAvailable, tlAvailable, topRightAvailable, x, _pp, mb,
ARRAY[i]);
}
int blk8x8X = mbX << 1;
for (int list = 0; list < 2; list++) {
if (p[0].usesList(list))
decodeSubMb8x8(reader, bSubMbTypes[subMbTypes[0]], refs[list], mbX << 6, mbY << 6, x[list],
mvTopLeft[list], mvTop[list][mbX << 2], mvTop[list][(mbX << 2) + 1],
mvTop[list][(mbX << 2) + 2], mvLeft[list][0], mvLeft[list][1], tlAvailable, topAvailable,
topAvailable, leftAvailable, x[list][0], x[list][1], x[list][4], x[list][5], refIdx[list][0],
mbb[list], 0, 0, 0, mbX, leftMBType, topMBType[mbX], B_8x8, predModeLeft[0],
predModeTop[blk8x8X], p[0], list);
if (p[1].usesList(list))
decodeSubMb8x8(reader, bSubMbTypes[subMbTypes[1]], refs[list], (mbX << 6) + 32, mbY << 6, x[list],
mvTop[list][(mbX << 2) + 1], mvTop[list][(mbX << 2) + 2], mvTop[list][(mbX << 2) + 3],
mvTop[list][(mbX << 2) + 4], x[list][1], x[list][5], topAvailable, topAvailable,
topRightAvailable, true, x[list][2], x[list][3], x[list][6], x[list][7], refIdx[list][1],
mbb[list], 8, 2, 0, mbX, B_8x8, topMBType[mbX], B_8x8, p[0], predModeTop[blk8x8X + 1], p[1],
list);
if (p[2].usesList(list))
decodeSubMb8x8(reader, bSubMbTypes[subMbTypes[2]], refs[list], mbX << 6, (mbY << 6) + 32, x[list],
mvLeft[list][1], x[list][4], x[list][5], x[list][6], mvLeft[list][2], mvLeft[list][3],
leftAvailable, true, true, leftAvailable, x[list][8], x[list][9], x[list][12], x[list][13],
refIdx[list][2], mbb[list], 128, 0, 2, mbX, leftMBType, B_8x8, B_8x8, predModeLeft[1], p[0],
p[2], list);
if (p[3].usesList(list))
decodeSubMb8x8(reader, bSubMbTypes[subMbTypes[3]], refs[list], (mbX << 6) + 32, (mbY << 6) + 32,
x[list], x[list][5], x[list][6], x[list][7], null, x[list][9], x[list][13], true, true, false,
true, x[list][10], x[list][11], x[list][14], x[list][15], refIdx[list][3], mbb[list], 136, 2,
2, mbX, B_8x8, B_8x8, B_8x8, p[2], p[1], p[3], list);
}
for (int i = 0; i < 4; i++) {
int blk4x4 = BLK8x8_BLOCKS[i][0];
prediction.mergePrediction(x[0][blk4x4][2], x[1][blk4x4][2], p[i], 0, mbb[0].getPlaneData(0),
mbb[1].getPlaneData(0), BLK_8x8_MB_OFF_LUMA[i], 16, 8, 8, mb.getPlaneData(0), refs, thisFrame);
}
predModeLeft[0] = p[1];
predModeTop[blk8x8X] = p[2];
predModeLeft[1] = predModeTop[blk8x8X + 1] = p[3];
savePrediction8x8(mbX, x[0], 0);
savePrediction8x8(mbX, x[1], 1);
for (int i = 0; i < 4; i++)
if (p[i] == Direct)
p[i] = _pp[i];
return bSubMbTypes[subMbTypes[0]] == 0 && bSubMbTypes[subMbTypes[1]] == 0 && bSubMbTypes[subMbTypes[2]] == 0
&& bSubMbTypes[subMbTypes[3]] == 0;
}
private int readSubMBTypeP(BitReader reader) {
if (!activePps.entropy_coding_mode_flag)
return readUE(reader, "SUB: sub_mb_type");
else
return cabac.readSubMbTypeP(mDecoder);
}
private int readSubMBTypeB(BitReader reader) {
if (!activePps.entropy_coding_mode_flag)
return readUE(reader, "SUB: sub_mb_type");
else
return cabac.readSubMbTypeB(mDecoder);
}
private void savePrediction8x8(int mbX, int[][] x, int list) {
copyVect(mvTopLeft[list], mvTop[list][(mbX << 2) + 3]);
copyVect(mvLeft[list][0], x[3]);
copyVect(mvLeft[list][1], x[7]);
copyVect(mvLeft[list][2], x[11]);
copyVect(mvLeft[list][3], x[15]);
copyVect(mvTop[list][mbX << 2], x[12]);
copyVect(mvTop[list][(mbX << 2) + 1], x[13]);
copyVect(mvTop[list][(mbX << 2) + 2], x[14]);
copyVect(mvTop[list][(mbX << 2) + 3], x[15]);
}
private void copyVect(int[] to, int[] from) {
to[0] = from[0];
to[1] = from[1];
to[2] = from[2];
}
private void decodeSubMb8x8(BitReader reader, int subMbType, Picture8Bit[] references, int offX, int offY, int[][] x,
int[] tl, int[] t0, int[] t1, int[] tr, int[] l0, int[] l1, boolean tlAvb, boolean tAvb, boolean trAvb,
boolean lAvb, int[] x00, int[] x01, int[] x10, int[] x11, int refIdx, Picture8Bit mb, int off, int blk8x8X,
int blk8x8Y, int mbX, MBType leftMBType, MBType topMBType, MBType curMBType, PartPred leftPred,
PartPred topPred, PartPred partPred, int list) {
x00[2] = x01[2] = x10[2] = x11[2] = refIdx;
switch (subMbType) {
case 3:
decodeSub4x4(reader, references, offX, offY, tl, t0, t1, tr, l0, l1, tlAvb, tAvb, trAvb, lAvb, x00, x01,
x10, x11, refIdx, mb, off, blk8x8X, blk8x8Y, mbX, leftMBType, topMBType, curMBType, leftPred,
topPred, partPred, list);
break;
case 2:
decodeSub4x8(reader, references, offX, offY, tl, t0, t1, tr, l0, tlAvb, tAvb, trAvb, lAvb, x00, x01, x10,
x11, refIdx, mb, off, blk8x8X, blk8x8Y, mbX, leftMBType, topMBType, curMBType, leftPred, topPred,
partPred, list);
break;
case 1:
decodeSub8x4(reader, references, offX, offY, tl, t0, tr, l0, l1, tlAvb, tAvb, trAvb, lAvb, x00, x01, x10,
x11, refIdx, mb, off, blk8x8X, blk8x8Y, mbX, leftMBType, topMBType, curMBType, leftPred, topPred,
partPred, list);
break;
case 0:
decodeSub8x8(reader, references, offX, offY, tl, t0, tr, l0, tlAvb, tAvb, trAvb, lAvb, x00, x01, x10, x11,
refIdx, mb, off, blk8x8X, blk8x8Y, mbX, leftMBType, topMBType, curMBType, leftPred, topPred,
partPred, list);
}
}
private void decodeSub8x8(BitReader reader, Picture8Bit[] references, int offX, int offY, int[] tl, int[] t0, int[] tr,
int[] l0, boolean tlAvb, boolean tAvb, boolean trAvb, boolean lAvb, int[] x00, int[] x01, int[] x10,
int[] x11, int refIdx, Picture8Bit mb, int off, int blk8x8X, int blk8x8Y, int mbX, MBType leftMBType,
MBType topMBType, MBType curMBType, PartPred leftPred, PartPred topPred, PartPred partPred, int list) {
int mvdX = readMVD(reader, 0, lAvb, tAvb, leftMBType, topMBType, leftPred, topPred, partPred, mbX, blk8x8X,
blk8x8Y, 2, 2, list);
int mvdY = readMVD(reader, 1, lAvb, tAvb, leftMBType, topMBType, leftPred, topPred, partPred, mbX, blk8x8X,
blk8x8Y, 2, 2, list);
int mvpX = calcMVPredictionMedian(l0, t0, tr, tl, lAvb, tAvb, trAvb, tlAvb, refIdx, 0);
int mvpY = calcMVPredictionMedian(l0, t0, tr, tl, lAvb, tAvb, trAvb, tlAvb, refIdx, 1);
x00[0] = x01[0] = x10[0] = x11[0] = mvdX + mvpX;
x00[1] = x01[1] = x10[1] = x11[1] = mvpY + mvdY;
debugPrint("MVP: (" + mvpX + ", " + mvpY + "), MVD: (" + mvdX + ", " + mvdY + "), MV: (" + x00[0] + ","
+ x00[1] + "," + refIdx + ")");
BlockInterpolator.getBlockLuma(references[refIdx], mb, off, offX + x00[0], offY + x00[1], 8, 8);
}
private void decodeSub8x4(BitReader reader, Picture8Bit[] references, int offX, int offY, int[] tl, int[] t0, int[] tr,
int[] l0, int[] l1, boolean tlAvb, boolean tAvb, boolean trAvb, boolean lAvb, int[] x00, int[] x01,
int[] x10, int[] x11, int refIdx, Picture8Bit mb, int off, int blk8x8X, int blk8x8Y, int mbX,
MBType leftMBType, MBType topMBType, MBType curMBType, PartPred leftPred, PartPred topPred,
PartPred partPred, int list) {
int mvdX1 = readMVD(reader, 0, lAvb, tAvb, leftMBType, topMBType, leftPred, topPred, partPred, mbX, blk8x8X,
blk8x8Y, 2, 1, list);
int mvdY1 = readMVD(reader, 1, lAvb, tAvb, leftMBType, topMBType, leftPred, topPred, partPred, mbX, blk8x8X,
blk8x8Y, 2, 1, list);
int mvpX1 = calcMVPredictionMedian(l0, t0, tr, tl, lAvb, tAvb, trAvb, tlAvb, refIdx, 0);
int mvpY1 = calcMVPredictionMedian(l0, t0, tr, tl, lAvb, tAvb, trAvb, tlAvb, refIdx, 1);
x00[0] = x01[0] = mvdX1 + mvpX1;
x00[1] = x01[1] = mvdY1 + mvpY1;
debugPrint("MVP: (" + mvpX1 + ", " + mvpY1 + "), MVD: (" + mvdX1 + ", " + mvdY1 + "), MV: (" + x00[0] + ","
+ x00[1] + "," + refIdx + ")");
int mvdX2 = readMVD(reader, 0, lAvb, true, leftMBType, curMBType, leftPred, partPred, partPred, mbX, blk8x8X,
blk8x8Y + 1, 2, 1, list);
int mvdY2 = readMVD(reader, 1, lAvb, true, leftMBType, curMBType, leftPred, partPred, partPred, mbX, blk8x8X,
blk8x8Y + 1, 2, 1, list);
int mvpX2 = calcMVPredictionMedian(l1, x00, NULL_VECTOR, l0, lAvb, true, false, lAvb, refIdx, 0);
int mvpY2 = calcMVPredictionMedian(l1, x00, NULL_VECTOR, l0, lAvb, true, false, lAvb, refIdx, 1);
x10[0] = x11[0] = mvdX2 + mvpX2;
x10[1] = x11[1] = mvdY2 + mvpY2;
debugPrint("MVP: (" + mvpX2 + ", " + mvpY2 + "), MVD: (" + mvdX2 + ", " + mvdY2 + "), MV: (" + x10[0] + ","
+ x10[1] + "," + refIdx + ")");
BlockInterpolator.getBlockLuma(references[refIdx], mb, off, offX + x00[0], offY + x00[1], 8, 4);
BlockInterpolator.getBlockLuma(references[refIdx], mb, off + mb.getWidth() * 4, offX + x10[0], offY + x10[1]
+ 16, 8, 4);
}
private void decodeSub4x8(BitReader reader, Picture8Bit[] references, int offX, int offY, int[] tl, int[] t0, int[] t1,
int[] tr, int[] l0, boolean tlAvb, boolean tAvb, boolean trAvb, boolean lAvb, int[] x00, int[] x01,
int[] x10, int[] x11, int refIdx, Picture8Bit mb, int off, int blk8x8X, int blk8x8Y, int mbX,
MBType leftMBType, MBType topMBType, MBType curMBType, PartPred leftPred, PartPred topPred,
PartPred partPred, int list) {
int mvdX1 = readMVD(reader, 0, lAvb, tAvb, leftMBType, topMBType, leftPred, topPred, partPred, mbX, blk8x8X,
blk8x8Y, 1, 2, list);
int mvdY1 = readMVD(reader, 1, lAvb, tAvb, leftMBType, topMBType, leftPred, topPred, partPred, mbX, blk8x8X,
blk8x8Y, 1, 2, list);
int mvpX1 = calcMVPredictionMedian(l0, t0, t1, tl, lAvb, tAvb, tAvb, tlAvb, refIdx, 0);
int mvpY1 = calcMVPredictionMedian(l0, t0, t1, tl, lAvb, tAvb, tAvb, tlAvb, refIdx, 1);
x00[0] = x10[0] = mvdX1 + mvpX1;
x00[1] = x10[1] = mvdY1 + mvpY1;
debugPrint("MVP: (" + mvpX1 + ", " + mvpY1 + "), MVD: (" + mvdX1 + ", " + mvdY1 + "), MV: (" + x00[0] + ","
+ x00[1] + "," + refIdx + ")");
int mvdX2 = readMVD(reader, 0, true, tAvb, curMBType, topMBType, partPred, topPred, partPred, mbX, blk8x8X + 1,
blk8x8Y, 1, 2, list);
int mvdY2 = readMVD(reader, 1, true, tAvb, curMBType, topMBType, partPred, topPred, partPred, mbX, blk8x8X + 1,
blk8x8Y, 1, 2, list);
int mvpX2 = calcMVPredictionMedian(x00, t1, tr, t0, true, tAvb, trAvb, tAvb, refIdx, 0);
int mvpY2 = calcMVPredictionMedian(x00, t1, tr, t0, true, tAvb, trAvb, tAvb, refIdx, 1);
x01[0] = x11[0] = mvdX2 + mvpX2;
x01[1] = x11[1] = mvdY2 + mvpY2;
debugPrint("MVP: (" + mvpX2 + ", " + mvpY2 + "), MVD: (" + mvdX2 + ", " + mvdY2 + "), MV: (" + x01[0] + ","
+ x01[1] + "," + refIdx + ")");
BlockInterpolator.getBlockLuma(references[refIdx], mb, off, offX + x00[0], offY + x00[1], 4, 8);
BlockInterpolator.getBlockLuma(references[refIdx], mb, off + 4, offX + x01[0] + 16, offY + x01[1], 4, 8);
}
private void decodeSub4x4(BitReader reader, Picture8Bit[] references, int offX, int offY, int[] tl, int[] t0, int[] t1,
int[] tr, int[] l0, int[] l1, boolean tlAvb, boolean tAvb, boolean trAvb, boolean lAvb, int[] x00,
int[] x01, int[] x10, int[] x11, int refIdx, Picture8Bit mb, int off, int blk8x8X, int blk8x8Y, int mbX,
MBType leftMBType, MBType topMBType, MBType curMBType, PartPred leftPred, PartPred topPred,
PartPred partPred, int list) {
int mvdX1 = readMVD(reader, 0, lAvb, tAvb, leftMBType, topMBType, leftPred, topPred, partPred, mbX, blk8x8X,
blk8x8Y, 1, 1, list);
int mvdY1 = readMVD(reader, 1, lAvb, tAvb, leftMBType, topMBType, leftPred, topPred, partPred, mbX, blk8x8X,
blk8x8Y, 1, 1, list);
int mvpX1 = calcMVPredictionMedian(l0, t0, t1, tl, lAvb, tAvb, tAvb, tlAvb, refIdx, 0);
int mvpY1 = calcMVPredictionMedian(l0, t0, t1, tl, lAvb, tAvb, tAvb, tlAvb, refIdx, 1);
x00[0] = mvdX1 + mvpX1;
x00[1] = mvdY1 + mvpY1;
debugPrint("MVP: (" + mvpX1 + ", " + mvpY1 + "), MVD: (" + mvdX1 + ", " + mvdY1 + "), MV: (" + x00[0] + ","
+ x00[1] + "," + refIdx + ")");
int mvdX2 = readMVD(reader, 0, true, tAvb, curMBType, topMBType, partPred, topPred, partPred, mbX, blk8x8X + 1,
blk8x8Y, 1, 1, list);
int mvdY2 = readMVD(reader, 1, true, tAvb, curMBType, topMBType, partPred, topPred, partPred, mbX, blk8x8X + 1,
blk8x8Y, 1, 1, list);
int mvpX2 = calcMVPredictionMedian(x00, t1, tr, t0, true, tAvb, trAvb, tAvb, refIdx, 0);
int mvpY2 = calcMVPredictionMedian(x00, t1, tr, t0, true, tAvb, trAvb, tAvb, refIdx, 1);
x01[0] = mvdX2 + mvpX2;
x01[1] = mvdY2 + mvpY2;
debugPrint("MVP: (" + mvpX2 + ", " + mvpY2 + "), MVD: (" + mvdX2 + ", " + mvdY2 + "), MV: (" + x01[0] + ","
+ x01[1] + "," + refIdx + ")");
int mvdX3 = readMVD(reader, 0, lAvb, true, leftMBType, curMBType, leftPred, partPred, partPred, mbX, blk8x8X,
blk8x8Y + 1, 1, 1, list);
int mvdY3 = readMVD(reader, 1, lAvb, true, leftMBType, curMBType, leftPred, partPred, partPred, mbX, blk8x8X,
blk8x8Y + 1, 1, 1, list);
int mvpX3 = calcMVPredictionMedian(l1, x00, x01, l0, lAvb, true, true, lAvb, refIdx, 0);
int mvpY3 = calcMVPredictionMedian(l1, x00, x01, l0, lAvb, true, true, lAvb, refIdx, 1);
x10[0] = mvdX3 + mvpX3;
x10[1] = mvdY3 + mvpY3;
debugPrint("MVP: (" + mvpX3 + ", " + mvpY3 + "), MVD: (" + mvdX3 + ", " + mvdY3 + "), MV: (" + x10[0] + ","
+ x10[1] + "," + refIdx + ")");
int mvdX4 = readMVD(reader, 0, true, true, curMBType, curMBType, partPred, partPred, partPred, mbX,
blk8x8X + 1, blk8x8Y + 1, 1, 1, list);
int mvdY4 = readMVD(reader, 1, true, true, curMBType, curMBType, partPred, partPred, partPred, mbX,
blk8x8X + 1, blk8x8Y + 1, 1, 1, list);
int mvpX4 = calcMVPredictionMedian(x10, x01, NULL_VECTOR, x00, true, true, false, true, refIdx, 0);
int mvpY4 = calcMVPredictionMedian(x10, x01, NULL_VECTOR, x00, true, true, false, true, refIdx, 1);
x11[0] = mvdX4 + mvpX4;
x11[1] = mvdY4 + mvpY4;
debugPrint("MVP: (" + mvpX4 + ", " + mvpY4 + "), MVD: (" + mvdX4 + ", " + mvdY4 + "), MV: (" + x11[0] + ","
+ x11[1] + "," + refIdx + ")");
BlockInterpolator.getBlockLuma(references[refIdx], mb, off, offX + x00[0], offY + x00[1], 4, 4);
BlockInterpolator.getBlockLuma(references[refIdx], mb, off + 4, offX + x01[0] + 16, offY + x01[1], 4, 4);
BlockInterpolator.getBlockLuma(references[refIdx], mb, off + mb.getWidth() * 4, offX + x10[0], offY + x10[1]
+ 16, 4, 4);
BlockInterpolator.getBlockLuma(references[refIdx], mb, off + mb.getWidth() * 4 + 4, offX + x11[0] + 16, offY
+ x11[1] + 16, 4, 4);
}
private int readMVD(BitReader reader, int comp, boolean leftAvailable, boolean topAvailable, MBType leftType,
MBType topType, PartPred leftPred, PartPred topPred, PartPred curPred, int mbX, int partX, int partY,
int partW, int partH, int list) {
if (!activePps.entropy_coding_mode_flag)
return readSE(reader, "mvd_l0_x");
else
return cabac.readMVD(mDecoder, comp, leftAvailable, topAvailable, leftType, topType, leftPred, topPred,
curPred, mbX, partX, partY, partW, partH, list);
}
public void decodeChromaInter(BitReader reader, int pattern, Frame[][] refs, int[][][] x, PartPred[] predType,
boolean leftAvailable, boolean topAvailable, int mbX, int mbY, int mbAddr, int qp, Picture8Bit mb1,
int[][] residualCbOut, int[][] residualCrOut) {
predictChromaInter(refs, x, mbX << 3, mbY << 3, 1, mb1, predType);
predictChromaInter(refs, x, mbX << 3, mbY << 3, 2, mb1, predType);
int qp1 = calcQpChroma(qp, chromaQpOffset[0]);
int qp2 = calcQpChroma(qp, chromaQpOffset[1]);
decodeChromaResidual(reader, leftAvailable, topAvailable, mbX, mbY, pattern, qp1, qp2, MBType.P_16x16, residualCbOut, residualCrOut);
mbQps[1][mbAddr] = qp1;
mbQps[2][mbAddr] = qp2;
}
private void saveMvs(int[][][] x, int mbX, int mbY) {
for (int j = 0, blkOffY = mbY << 2, blkInd = 0; j < 4; j++, blkOffY++) {
for (int i = 0, blkOffX = mbX << 2; i < 4; i++, blkOffX++, blkInd++) {
mvs[0][blkOffY][blkOffX] = x[0][blkInd];
mvs[1][blkOffY][blkOffX] = x[1][blkInd];
}
}
}
public void predictChromaInter(Frame[][] refs, int[][][] vectors, int x, int y, int comp, Picture8Bit mb,
PartPred[] predType) {
Picture8Bit[] mbb = { Picture8Bit.create(16, 16, chromaFormat), Picture8Bit.create(16, 16, chromaFormat) };
for (int blk8x8 = 0; blk8x8 < 4; blk8x8++) {
for (int list = 0; list < 2; list++) {
if (!predType[blk8x8].usesList(list))
continue;
for (int blk4x4 = 0; blk4x4 < 4; blk4x4++) {
int i = BLK_INV_MAP[(blk8x8 << 2) + blk4x4];
int[] mv = vectors[list][i];
Picture8Bit ref = refs[list][mv[2]];
int blkPox = (i & 3) << 1;
int blkPoy = (i >> 2) << 1;
int xx = ((x + blkPox) << 3) + mv[0];
int yy = ((y + blkPoy) << 3) + mv[1];
BlockInterpolator.getBlockChroma(ref.getPlaneData(comp), ref.getPlaneWidth(comp),
ref.getPlaneHeight(comp), mbb[list].getPlaneData(comp), blkPoy * mb.getPlaneWidth(comp)
+ blkPox, mb.getPlaneWidth(comp), xx, yy, 2, 2);
}
}
int blk4x4 = BLK8x8_BLOCKS[blk8x8][0];
prediction.mergePrediction(vectors[0][blk4x4][2], vectors[1][blk4x4][2], predType[blk8x8], comp,
mbb[0].getPlaneData(comp), mbb[1].getPlaneData(comp), BLK_8x8_MB_OFF_CHROMA[blk8x8],
mb.getPlaneWidth(comp), 4, 4, mb.getPlaneData(comp), refs, thisFrame);
}
}
public void decodeMBlockIPCM(BitReader reader, int mbIndex, Picture8Bit mb) {
int mbX = mapper.getMbX(mbIndex);
reader.align();
int[] samplesLuma = new int[256];
for (int i = 0; i < 256; i++) {
samplesLuma[i] = reader.readNBit(8);
}
int MbWidthC = 16 >> chromaFormat.compWidth[1];
int MbHeightC = 16 >> chromaFormat.compHeight[1];
int[] samplesChroma = new int[2 * MbWidthC * MbHeightC];
for (int i = 0; i < 2 * MbWidthC * MbHeightC; i++) {
samplesChroma[i] = reader.readNBit(8);
}
collectPredictors(mb, mbX);
}
public void predictBDirect(Frame[][] refs, int mbX, int mbY, boolean lAvb, boolean tAvb, boolean tlAvb,
boolean trAvb, int[][][] x, PartPred[] pp, Picture8Bit mb, int[] blocks) {
if (sh.direct_spatial_mv_pred_flag)
predictBSpatialDirect(refs, mbX, mbY, lAvb, tAvb, tlAvb, trAvb, x, pp, mb, blocks);
else
predictBTemporalDirect(refs, mbX, mbY, lAvb, tAvb, tlAvb, trAvb, x, pp, mb, blocks);
}
private void predictBTemporalDirect(Frame[][] refs, int mbX, int mbY, boolean lAvb, boolean tAvb, boolean tlAvb,
boolean trAvb, int[][][] x, PartPred[] pp, Picture8Bit mb, int[] blocks8x8) {
Picture8Bit mb0 = Picture8Bit.create(16, 16, chromaFormat), mb1 = Picture8Bit.create(16, 16, chromaFormat);
for (int blk8x8 : blocks8x8) {
int blk4x4_0 = H264Const.BLK8x8_BLOCKS[blk8x8][0];
pp[blk8x8] = Bi;
if (!activeSps.direct_8x8_inference_flag)
for (int blk4x4 : BLK8x8_BLOCKS[blk8x8]) {
predTemp4x4(refs, mbX, mbY, x, blk4x4);
int blkIndX = blk4x4 & 3;
int blkIndY = blk4x4 >> 2;
debugPrint("DIRECT_4x4 [" + blkIndY + ", " + blkIndX + "]: (" + x[0][blk4x4][0] + ","
+ x[0][blk4x4][1] + "," + x[0][blk4x4][2] + "), (" + x[1][blk4x4][0] + ","
+ x[1][blk4x4][1] + "," + x[1][blk4x4][2] + ")");
int blkPredX = (mbX << 6) + (blkIndX << 4);
int blkPredY = (mbY << 6) + (blkIndY << 4);
BlockInterpolator.getBlockLuma(refs[0][x[0][blk4x4][2]], mb0, BLK_4x4_MB_OFF_LUMA[blk4x4], blkPredX
+ x[0][blk4x4][0], blkPredY + x[0][blk4x4][1], 4, 4);
BlockInterpolator.getBlockLuma(refs[1][0], mb1, BLK_4x4_MB_OFF_LUMA[blk4x4], blkPredX
+ x[1][blk4x4][0], blkPredY + x[1][blk4x4][1], 4, 4);
}
else {
int blk4x4Pred = BLK_INV_MAP[blk8x8 * 5];
predTemp4x4(refs, mbX, mbY, x, blk4x4Pred);
propagatePred(x, blk8x8, blk4x4Pred);
int blkIndX = blk4x4_0 & 3;
int blkIndY = blk4x4_0 >> 2;
debugPrint("DIRECT_8x8 [" + blkIndY + ", " + blkIndX + "]: (" + x[0][blk4x4_0][0] + ","
+ x[0][blk4x4_0][1] + "," + x[0][blk4x4_0][2] + "), (" + x[1][blk4x4_0][0] + ","
+ x[1][blk4x4_0][1] + "," + x[0][blk4x4_0][2] + ")");
int blkPredX = (mbX << 6) + (blkIndX << 4);
int blkPredY = (mbY << 6) + (blkIndY << 4);
BlockInterpolator.getBlockLuma(refs[0][x[0][blk4x4_0][2]], mb0, BLK_4x4_MB_OFF_LUMA[blk4x4_0], blkPredX
+ x[0][blk4x4_0][0], blkPredY + x[0][blk4x4_0][1], 8, 8);
BlockInterpolator.getBlockLuma(refs[1][0], mb1, BLK_4x4_MB_OFF_LUMA[blk4x4_0], blkPredX
+ x[1][blk4x4_0][0], blkPredY + x[1][blk4x4_0][1], 8, 8);
}
prediction.mergePrediction(x[0][blk4x4_0][2], x[1][blk4x4_0][2], Bi, 0, mb0.getPlaneData(0),
mb1.getPlaneData(0), BLK_4x4_MB_OFF_LUMA[blk4x4_0], 16, 8, 8, mb.getPlaneData(0), refs, thisFrame);
}
}
private void predTemp4x4(Frame[][] refs, int mbX, int mbY, int[][][] x, int blk4x4) {
int mbWidth = activeSps.pic_width_in_mbs_minus1 + 1;
Frame picCol = refs[1][0];
int blkIndX = blk4x4 & 3;
int blkIndY = blk4x4 >> 2;
int blkPosX = (mbX << 2) + blkIndX;
int blkPosY = (mbY << 2) + blkIndY;
int[] mvCol = picCol.getMvs()[0][blkPosY][blkPosX];
Frame refL0;
int refIdxL0;
if (mvCol[2] == -1) {
mvCol = picCol.getMvs()[1][blkPosY][blkPosX];
if (mvCol[2] == -1) {
refIdxL0 = 0;
refL0 = refs[0][0];
} else {
refL0 = picCol.getRefsUsed()[mbY * mbWidth + mbX][1][mvCol[2]];
refIdxL0 = findPic(refs[0], refL0);
}
} else {
refL0 = picCol.getRefsUsed()[mbY * mbWidth + mbX][0][mvCol[2]];
refIdxL0 = findPic(refs[0], refL0);
}
x[0][blk4x4][2] = refIdxL0;
x[1][blk4x4][2] = 0;
int td = MathUtil.clip(picCol.getPOC() - refL0.getPOC(), -128, 127);
if (!refL0.isShortTerm() || td == 0) {
x[0][blk4x4][0] = mvCol[0];
x[0][blk4x4][1] = mvCol[1];
x[1][blk4x4][0] = 0;
x[1][blk4x4][1] = 0;
} else {
int tb = MathUtil.clip(thisFrame.getPOC() - refL0.getPOC(), -128, 127);
int tx = (16384 + Math.abs(td / 2)) / td;
int dsf = clip((tb * tx + 32) >> 6, -1024, 1023);
x[0][blk4x4][0] = (dsf * mvCol[0] + 128) >> 8;
x[0][blk4x4][1] = (dsf * mvCol[1] + 128) >> 8;
x[1][blk4x4][0] = (x[0][blk4x4][0] - mvCol[0]);
x[1][blk4x4][1] = (x[0][blk4x4][1] - mvCol[1]);
}
}
private int findPic(Frame[] frames, Frame refL0) {
for (int i = 0; i < frames.length; i++)
if (frames[i] == refL0)
return i;
Logger.error("RefPicList0 shall contain refPicCol");
return 0;
}
private void predictBSpatialDirect(Frame[][] refs, int mbX, int mbY, boolean lAvb, boolean tAvb, boolean tlAvb,
boolean trAvb, int[][][] x, PartPred[] pp, Picture8Bit mb, int[] blocks8x8) {
int[] a0 = mvLeft[0][0], a1 = mvLeft[1][0];
int[] b0 = mvTop[0][mbX << 2], b1 = mvTop[1][mbX << 2];
int[] c0 = mvTop[0][(mbX << 2) + 4], c1 = mvTop[1][(mbX << 2) + 4];
int[] d0 = mvTopLeft[0];
int[] d1 = mvTopLeft[1];
int refIdxL0 = calcRef(a0, b0, c0, d0, lAvb, tAvb, tlAvb, trAvb, mbX);
int refIdxL1 = calcRef(a1, b1, c1, d1, lAvb, tAvb, tlAvb, trAvb, mbX);
Picture8Bit mb0 = Picture8Bit.create(16, 16, chromaFormat), mb1 = Picture8Bit.create(16, 16, chromaFormat);
if (refIdxL0 < 0 && refIdxL1 < 0) {
for (int blk8x8 : blocks8x8) {
for (int blk4x4 : BLK8x8_BLOCKS[blk8x8]) {
x[0][blk4x4][0] = x[0][blk4x4][1] = x[0][blk4x4][2] = x[1][blk4x4][0] = x[1][blk4x4][1] = x[1][blk4x4][2] = 0;
}
pp[blk8x8] = Bi;
int blkOffX = (blk8x8 & 1) << 5;
int blkOffY = (blk8x8 >> 1) << 5;
BlockInterpolator.getBlockLuma(refs[0][0], mb0, BLK_8x8_MB_OFF_LUMA[blk8x8], (mbX << 6) + blkOffX,
(mbY << 6) + blkOffY, 8, 8);
BlockInterpolator.getBlockLuma(refs[1][0], mb1, BLK_8x8_MB_OFF_LUMA[blk8x8], (mbX << 6) + blkOffX,
(mbY << 6) + blkOffY, 8, 8);
prediction.mergePrediction(0, 0, PartPred.Bi, 0, mb0.getPlaneData(0), mb1.getPlaneData(0),
BLK_8x8_MB_OFF_LUMA[blk8x8], 16, 8, 8, mb.getPlaneData(0), refs, thisFrame);
debugPrint("DIRECT_8x8 [" + (blk8x8 & 2) + ", " + ((blk8x8 << 1) & 2) + "]: (0,0,0), (0,0,0)");
}
return;
}
int mvX0 = calcMVPredictionMedian(a0, b0, c0, d0, lAvb, tAvb, trAvb, tlAvb, refIdxL0, 0);
int mvY0 = calcMVPredictionMedian(a0, b0, c0, d0, lAvb, tAvb, trAvb, tlAvb, refIdxL0, 1);
int mvX1 = calcMVPredictionMedian(a1, b1, c1, d1, lAvb, tAvb, trAvb, tlAvb, refIdxL1, 0);
int mvY1 = calcMVPredictionMedian(a1, b1, c1, d1, lAvb, tAvb, trAvb, tlAvb, refIdxL1, 1);
Frame col = refs[1][0];
PartPred partPred = refIdxL0 >= 0 && refIdxL1 >= 0 ? Bi : (refIdxL0 >= 0 ? L0 : L1);
for (int blk8x8 : blocks8x8) {
int blk4x4_0 = H264Const.BLK8x8_BLOCKS[blk8x8][0];
if (!activeSps.direct_8x8_inference_flag)
for (int blk4x4 : BLK8x8_BLOCKS[blk8x8]) {
pred4x4(mbX, mbY, x, pp, refIdxL0, refIdxL1, mvX0, mvY0, mvX1, mvY1, col, partPred, blk4x4);
int blkIndX = blk4x4 & 3;
int blkIndY = blk4x4 >> 2;
debugPrint("DIRECT_4x4 [" + blkIndY + ", " + blkIndX + "]: (" + x[0][blk4x4][0] + ","
+ x[0][blk4x4][1] + "," + refIdxL0 + "), (" + x[1][blk4x4][0] + "," + x[1][blk4x4][1] + ","
+ refIdxL1 + ")");
int blkPredX = (mbX << 6) + (blkIndX << 4);
int blkPredY = (mbY << 6) + (blkIndY << 4);
if (refIdxL0 >= 0)
BlockInterpolator.getBlockLuma(refs[0][refIdxL0], mb0, BLK_4x4_MB_OFF_LUMA[blk4x4], blkPredX
+ x[0][blk4x4][0], blkPredY + x[0][blk4x4][1], 4, 4);
if (refIdxL1 >= 0)
BlockInterpolator.getBlockLuma(refs[1][refIdxL1], mb1, BLK_4x4_MB_OFF_LUMA[blk4x4], blkPredX
+ x[1][blk4x4][0], blkPredY + x[1][blk4x4][1], 4, 4);
}
else {
int blk4x4Pred = BLK_INV_MAP[blk8x8 * 5];
pred4x4(mbX, mbY, x, pp, refIdxL0, refIdxL1, mvX0, mvY0, mvX1, mvY1, col, partPred, blk4x4Pred);
propagatePred(x, blk8x8, blk4x4Pred);
int blkIndX = blk4x4_0 & 3;
int blkIndY = blk4x4_0 >> 2;
debugPrint("DIRECT_8x8 [" + blkIndY + ", " + blkIndX + "]: (" + x[0][blk4x4_0][0] + ","
+ x[0][blk4x4_0][1] + "," + refIdxL0 + "), (" + x[1][blk4x4_0][0] + "," + x[1][blk4x4_0][1]
+ "," + refIdxL1 + ")");
int blkPredX = (mbX << 6) + (blkIndX << 4);
int blkPredY = (mbY << 6) + (blkIndY << 4);
if (refIdxL0 >= 0)
BlockInterpolator.getBlockLuma(refs[0][refIdxL0], mb0, BLK_4x4_MB_OFF_LUMA[blk4x4_0], blkPredX
+ x[0][blk4x4_0][0], blkPredY + x[0][blk4x4_0][1], 8, 8);
if (refIdxL1 >= 0)
BlockInterpolator.getBlockLuma(refs[1][refIdxL1], mb1, BLK_4x4_MB_OFF_LUMA[blk4x4_0], blkPredX
+ x[1][blk4x4_0][0], blkPredY + x[1][blk4x4_0][1], 8, 8);
}
prediction.mergePrediction(x[0][blk4x4_0][2], x[1][blk4x4_0][2], refIdxL0 >= 0 ? (refIdxL1 >= 0 ? Bi : L0)
: L1, 0, mb0.getPlaneData(0), mb1.getPlaneData(0), BLK_4x4_MB_OFF_LUMA[blk4x4_0], 16, 8, 8, mb
.getPlaneData(0), refs, thisFrame);
}
}
private int calcRef(int[] a0, int[] b0, int[] c0, int[] d0, boolean lAvb, boolean tAvb, boolean tlAvb,
boolean trAvb, int mbX) {
return minPos(minPos(lAvb ? a0[2] : -1, tAvb ? b0[2] : -1), trAvb ? c0[2] : (tlAvb ? d0[2] : -1));
}
private void propagatePred(int[][][] x, int blk8x8, int blk4x4Pred) {
int b0 = BLK8x8_BLOCKS[blk8x8][0];
int b1 = BLK8x8_BLOCKS[blk8x8][1];
int b2 = BLK8x8_BLOCKS[blk8x8][2];
int b3 = BLK8x8_BLOCKS[blk8x8][3];
x[0][b0][0] = x[0][b1][0] = x[0][b2][0] = x[0][b3][0] = x[0][blk4x4Pred][0];
x[0][b0][1] = x[0][b1][1] = x[0][b2][1] = x[0][b3][1] = x[0][blk4x4Pred][1];
x[0][b0][2] = x[0][b1][2] = x[0][b2][2] = x[0][b3][2] = x[0][blk4x4Pred][2];
x[1][b0][0] = x[1][b1][0] = x[1][b2][0] = x[1][b3][0] = x[1][blk4x4Pred][0];
x[1][b0][1] = x[1][b1][1] = x[1][b2][1] = x[1][b3][1] = x[1][blk4x4Pred][1];
x[1][b0][2] = x[1][b1][2] = x[1][b2][2] = x[1][b3][2] = x[1][blk4x4Pred][2];
}
private void pred4x4(int mbX, int mbY, int[][][] x, PartPred[] pp, int refL0, int refL1, int mvX0, int mvY0,
int mvX1, int mvY1, Frame col, PartPred partPred, int blk4x4) {
int blkIndX = blk4x4 & 3;
int blkIndY = blk4x4 >> 2;
int blkPosX = (mbX << 2) + blkIndX;
int blkPosY = (mbY << 2) + blkIndY;
x[0][blk4x4][2] = refL0;
x[1][blk4x4][2] = refL1;
int[] mvCol = col.getMvs()[0][blkPosY][blkPosX];
if (mvCol[2] == -1)
mvCol = col.getMvs()[1][blkPosY][blkPosX];
boolean colZero = col.isShortTerm() && mvCol[2] == 0 && (abs(mvCol[0]) >> 1) == 0 && (abs(mvCol[1]) >> 1) == 0;
if (refL0 > 0 || !colZero) {
x[0][blk4x4][0] = mvX0;
x[0][blk4x4][1] = mvY0;
}
if (refL1 > 0 || !colZero) {
x[1][blk4x4][0] = mvX1;
x[1][blk4x4][1] = mvY1;
}
pp[BLK_8x8_IND[blk4x4]] = partPred;
}
private int minPos(int a, int b) {
return a >= 0 && b >= 0 ? Math.min(a, b) : Math.max(a, b);
}
public void predictPSkip(Frame[][] refs, int mbX, int mbY, boolean lAvb, boolean tAvb, boolean tlAvb,
boolean trAvb, int[][][] x, Picture8Bit mb) {
int mvX = 0, mvY = 0;
if (lAvb && tAvb) {
int[] b = mvTop[0][mbX << 2];
int[] a = mvLeft[0][0];
if ((a[0] != 0 || a[1] != 0 || a[2] != 0) && (b[0] != 0 || b[1] != 0 || b[2] != 0)) {
mvX = calcMVPredictionMedian(a, b, mvTop[0][(mbX << 2) + 4], mvTopLeft[0], lAvb, tAvb, trAvb, tlAvb, 0,
0);
mvY = calcMVPredictionMedian(a, b, mvTop[0][(mbX << 2) + 4], mvTopLeft[0], lAvb, tAvb, trAvb, tlAvb, 0,
1);
}
}
debugPrint("MV_SKIP: (" + mvX + "," + mvY + ")");
int blk8x8X = mbX << 1;
predModeLeft[0] = predModeLeft[1] = predModeTop[blk8x8X] = predModeTop[blk8x8X + 1] = L0;
int xx = mbX << 2;
copyVect(mvTopLeft[0], mvTop[0][xx + 3]);
saveVect(mvTop[0], xx, xx + 4, mvX, mvY, 0);
saveVect(mvLeft[0], 0, 4, mvX, mvY, 0);
for (int i = 0; i < 16; i++) {
x[0][i][0] = mvX;
x[0][i][1] = mvY;
x[0][i][2] = 0;
}
BlockInterpolator.getBlockLuma(refs[0][0], mb, 0, (mbX << 6) + mvX, (mbY << 6) + mvY, 16, 16);
prediction.mergePrediction(0, 0, L0, 0, mb.getPlaneData(0), null, 0, 16, 16, 16, mb.getPlaneData(0), refs,
thisFrame);
}
public void decodeChromaSkip(Frame[][] reference, int[][][] vectors, PartPred[] pp, int mbX, int mbY, Picture8Bit mb) {
predictChromaInter(reference, vectors, mbX << 3, mbY << 3, 1, mb, pp);
predictChromaInter(reference, vectors, mbX << 3, mbY << 3, 2, mb, pp);
}
private void debugPrint(String str) {
if (debug)
Logger.debug(str);
}
public void setDebug(boolean debug) {
this.debug = debug;
}
}
|
package com.stripe.android.model;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Size;
import android.support.annotation.StringDef;
import com.stripe.android.util.CardUtils;
import com.stripe.android.util.DateUtils;
import com.stripe.android.util.LoggingUtils;
import com.stripe.android.util.StripeTextUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
/**
* A model object representing a Card in the Android SDK.
*/
public class Card {
@Retention(RetentionPolicy.SOURCE)
@StringDef({
AMERICAN_EXPRESS,
DISCOVER,
JCB,
DINERS_CLUB,
VISA,
MASTERCARD,
UNKNOWN
})
public @interface CardBrand { }
public static final String AMERICAN_EXPRESS = "American Express";
public static final String DISCOVER = "Discover";
public static final String JCB = "JCB";
public static final String DINERS_CLUB = "Diners Club";
public static final String VISA = "Visa";
public static final String MASTERCARD = "MasterCard";
public static final String UNKNOWN = "Unknown";
@Retention(RetentionPolicy.SOURCE)
@StringDef({
FUNDING_CREDIT,
FUNDING_DEBIT,
FUNDING_PREPAID,
FUNDING_UNKNOWN
})
public @interface FundingType { }
public static final String FUNDING_CREDIT = "credit";
public static final String FUNDING_DEBIT = "debit";
public static final String FUNDING_PREPAID = "prepaid";
public static final String FUNDING_UNKNOWN = "unknown";
// Based on http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29
public static final String[] PREFIXES_AMERICAN_EXPRESS = {"34", "37"};
public static final String[] PREFIXES_DISCOVER = {"60", "62", "64", "65"};
public static final String[] PREFIXES_JCB = {"35"};
public static final String[] PREFIXES_DINERS_CLUB = {"300", "301", "302", "303", "304", "305", "309", "36", "38", "39"};
public static final String[] PREFIXES_VISA = {"4"};
public static final String[] PREFIXES_MASTERCARD = {
"2221", "2222", "2223", "2224", "2225", "2226", "2227", "2228", "2229",
"223", "224", "225", "226", "227", "228", "229",
"23", "24", "25", "26",
"270", "271", "2720",
"50", "51", "52", "53", "54", "55"
};
public static final int MAX_LENGTH_STANDARD = 16;
public static final int MAX_LENGTH_AMERICAN_EXPRESS = 15;
public static final int MAX_LENGTH_DINERS_CLUB = 14;
private String number;
private String cvc;
private Integer expMonth;
private Integer expYear;
private String name;
private String addressLine1;
private String addressLine2;
private String addressCity;
private String addressState;
private String addressZip;
private String addressCountry;
@Size(4) private String last4;
@CardBrand private String brand;
@FundingType private String funding;
private String fingerprint;
private String country;
private String currency;
@NonNull private List<String> loggingTokens = new ArrayList<>();
/**
* Builder class for a {@link Card} model.
*/
public static class Builder {
private final String number;
private final String cvc;
private final Integer expMonth;
private final Integer expYear;
private String name;
private String addressLine1;
private String addressLine2;
private String addressCity;
private String addressState;
private String addressZip;
private String addressCountry;
private @CardBrand String brand;
private @FundingType String funding;
private @Size(4) String last4;
private String fingerprint;
private String country;
private String currency;
/**
* Constructor with most common {@link Card} fields.
*
* @param number the credit card number
* @param expMonth the expiry month, as an integer value between 1 and 12
* @param expYear the expiry year
* @param cvc the card CVC number
*/
public Builder(
String number,
@IntRange(from = 1, to = 12) Integer expMonth,
@IntRange(from = 0) Integer expYear,
String cvc) {
this.number = number;
this.expMonth = expMonth;
this.expYear = expYear;
this.cvc = cvc;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder addressLine1(String address) {
this.addressLine1 = address;
return this;
}
public Builder addressLine2(String address) {
this.addressLine2 = address;
return this;
}
public Builder addressCity(String city) {
this.addressCity = city;
return this;
}
public Builder addressState(String state) {
this.addressState = state;
return this;
}
public Builder addressZip(String zip) {
this.addressZip = zip;
return this;
}
public Builder addressCountry(String country) {
this.addressCountry = country;
return this;
}
public Builder brand(@CardBrand String brand) {
this.brand = brand;
return this;
}
public Builder fingerprint(String fingerprint) {
this.fingerprint = fingerprint;
return this;
}
public Builder funding(@FundingType String funding) {
this.funding = funding;
return this;
}
public Builder country(String country) {
this.country = country;
return this;
}
public Builder currency(String currency) {
this.currency = currency;
return this;
}
public Builder last4(String last4) {
this.last4 = last4;
return this;
}
/**
* Generate a new {@link Card} object based on the arguments held by this Builder.
*
* @return the newly created {@link Card} object
*/
public Card build() {
return new Card(this);
}
}
/**
* Card constructor with all available fields.
*
* @param number the credit card number
* @param expMonth the expiry month
* @param expYear the expiry year
* @param cvc the CVC number
* @param name the card name
* @param addressLine1 first line of the billing address
* @param addressLine2 second line of the billing address
* @param addressCity city of the billing address
* @param addressState state of the billing address
* @param addressZip zip code of the billing address
* @param addressCountry country for the billing address
* @param brand brand of this card
* @param last4 last 4 digits of the card
* @param fingerprint the card fingerprint
* @param funding the funding type of the card
* @param country ISO country code of the card itself
* @param currency currency used by the card
*/
public Card(
String number,
Integer expMonth,
Integer expYear,
String cvc,
String name,
String addressLine1,
String addressLine2,
String addressCity,
String addressState,
String addressZip,
String addressCountry,
String brand,
@Size(4) String last4,
String fingerprint,
String funding,
String country,
String currency) {
this.number = StripeTextUtils.nullIfBlank(normalizeCardNumber(number));
this.expMonth = expMonth;
this.expYear = expYear;
this.cvc = StripeTextUtils.nullIfBlank(cvc);
this.name = StripeTextUtils.nullIfBlank(name);
this.addressLine1 = StripeTextUtils.nullIfBlank(addressLine1);
this.addressLine2 = StripeTextUtils.nullIfBlank(addressLine2);
this.addressCity = StripeTextUtils.nullIfBlank(addressCity);
this.addressState = StripeTextUtils.nullIfBlank(addressState);
this.addressZip = StripeTextUtils.nullIfBlank(addressZip);
this.addressCountry = StripeTextUtils.nullIfBlank(addressCountry);
this.brand = StripeTextUtils.asCardBrand(brand) == null ? getBrand() : brand;
this.last4 = StripeTextUtils.nullIfBlank(last4) == null ? getLast4() : last4;
this.fingerprint = StripeTextUtils.nullIfBlank(fingerprint);
this.funding = StripeTextUtils.asFundingType(funding);
this.country = StripeTextUtils.nullIfBlank(country);
this.currency = StripeTextUtils.nullIfBlank(currency);
}
/**
* Convenience constructor with address and currency.
*
* @param number the card number
* @param expMonth the expiry month
* @param expYear the expiry year
* @param cvc the CVC code
* @param name the cardholder name
* @param addressLine1 the first line of the billing address
* @param addressLine2 the second line of the billing address
* @param addressCity the city of the billing address
* @param addressState the state of the billing address
* @param addressZip the zip code of the billing address
* @param addressCountry the country of the billing address
* @param currency the currency of the card
*/
public Card(
String number,
Integer expMonth,
Integer expYear,
String cvc,
String name,
String addressLine1,
String addressLine2,
String addressCity,
String addressState,
String addressZip,
String addressCountry,
String currency) {
this(
number,
expMonth,
expYear,
cvc,
name,
addressLine1,
addressLine2,
addressCity,
addressState,
addressZip,
addressCountry,
null,
null,
null,
null,
null,
currency);
}
/**
* Convenience constructor for a Card object with a minimum number of inputs.
*
* @param number the card number
* @param expMonth the expiry month
* @param expYear the expiry year
* @param cvc the CVC code
*/
public Card(
String number,
Integer expMonth,
Integer expYear,
String cvc) {
this(
number,
expMonth,
expYear,
cvc,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null);
}
/**
* Checks whether {@code this} represents a valid card.
*
* @return {@code true} if valid, {@code false} otherwise.
*/
public boolean validateCard() {
if (cvc == null) {
return validateNumber() && validateExpiryDate();
} else {
return validateNumber() && validateExpiryDate() && validateCVC();
}
}
/**
* Checks whether or not the {@link #number} field is valid.
*
* @return {@code true} if valid, {@code false} otherwise.
*/
public boolean validateNumber() {
return CardUtils.isValidCardNumber(number);
}
/**
* Checks whether or not the {@link #expMonth} and {@link #expYear} fields represent a valid
* expiry date.
*
* @return {@code true} if valid, {@code false} otherwise
*/
public boolean validateExpiryDate() {
if (!validateExpMonth()) {
return false;
}
if (!validateExpYear()) {
return false;
}
return !DateUtils.hasMonthPassed(expYear, expMonth);
}
/**
* Checks whether or not the {@link #cvc} field is valid.
*
* @return {@code true} if valid, {@code false} otherwise
*/
public boolean validateCVC() {
if (StripeTextUtils.isBlank(cvc)) {
return false;
}
String cvcValue = cvc.trim();
String updatedType = getBrand();
boolean validLength =
(updatedType == null && cvcValue.length() >= 3 && cvcValue.length() <= 4)
|| (AMERICAN_EXPRESS.equals(updatedType) && cvcValue.length() == 4)
|| cvcValue.length() == 3;
return StripeTextUtils.isWholePositiveNumber(cvcValue) && validLength;
}
/**
* Checks whether or not the {@link #expMonth} field is valid.
*
* @return {@code true} if valid, {@code false} otherwise.
*/
public boolean validateExpMonth() {
return expMonth != null && expMonth >= 1 && expMonth <= 12;
}
/**
* Checks whether or not the {@link #expYear} field is valid.
*
* @return {@code true} if valid, {@code false} otherwise.
*/
public boolean validateExpYear() {
return expYear != null && !DateUtils.hasYearPassed(expYear);
}
/**
* @return the {@link #number} of this card
*/
public String getNumber() {
return number;
}
/**
* @return the {@link List} of logging tokens associated with this {@link Card} object
*/
@NonNull
public List<String> getLoggingTokens() {
return loggingTokens;
}
/**
* Add a logging token to this {@link Card} object.
*
* @param loggingToken a token to be logged with this card
* @return {@code this}, for chaining purposes
*/
@NonNull
public Card addLoggingToken(@NonNull @LoggingUtils.LoggingToken String loggingToken) {
loggingTokens.add(loggingToken);
return this;
}
/**
* Setter for the card number. Note that mutating the number of this card object
* invalidates the {@link #brand} and {@link #last4}.
*
* @param number the new {@link #number}
*/
public void setNumber(String number) {
this.number = number;
this.brand = null;
this.last4 = null;
}
/**
* @return the {@link #cvc} for this card
*/
public String getCVC() {
return cvc;
}
/**
* @param cvc the new {@link #cvc} code for this card
*/
public void setCVC(String cvc) {
this.cvc = cvc;
}
/**
* @return the {@link #expMonth} for this card
*/
@Nullable
@IntRange(from = 1, to = 12)
public Integer getExpMonth() {
return expMonth;
}
/**
* @param expMonth sets the {@link #expMonth} for this card
*/
public void setExpMonth(@Nullable @IntRange(from = 1, to = 12) Integer expMonth) {
this.expMonth = expMonth;
}
/**
* @return the {@link #expYear} for this card
*/
public Integer getExpYear() {
return expYear;
}
/**
* @param expYear sets the {@link #expYear} for this card
*/
public void setExpYear(Integer expYear) {
this.expYear = expYear;
}
/**
* @return the cardholder {@link #name} for this card
*/
public String getName() {
return name;
}
/**
* @param name sets the cardholder {@link #name} for this card
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the {@link #addressLine1} of this card
*/
public String getAddressLine1() {
return addressLine1;
}
/**
* @param addressLine1 sets the {@link #addressLine1} for this card
*/
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
/**
* @return the {@link #addressLine2} of this card
*/
public String getAddressLine2() {
return addressLine2;
}
/**
* @param addressLine2 sets the {@link #addressLine2} for this card
*/
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
/**
* @return the {@link #addressCity} for this card
*/
public String getAddressCity() {
return addressCity;
}
/**
* @param addressCity sets the {@link #addressCity} for this card
*/
public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
/**
* @return the {@link #addressZip} of this card
*/
public String getAddressZip() {
return addressZip;
}
/**
* @param addressZip sets the {@link #addressZip} for this card
*/
public void setAddressZip(String addressZip) {
this.addressZip = addressZip;
}
/**
* @return the {@link #addressState} of this card
*/
public String getAddressState() {
return addressState;
}
/**
* @param addressState sets the {@link #addressState} for this card
*/
public void setAddressState(String addressState) {
this.addressState = addressState;
}
/**
* @return the {@link #addressCountry} of this card
*/
public String getAddressCountry() {
return addressCountry;
}
/**
* @param addressCountry sets the {@link #addressCountry} for this card
*/
public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}
/**
* @return the {@link #currency} of this card. Only supported for Managed accounts.
*/
public String getCurrency() {
return currency;
}
/**
* @param currency sets the {@link #currency} of this card. Only supported for Managed accounts.
*/
public void setCurrency(String currency) {
this.currency = currency;
}
/**
* @return the {@link #last4} digits of this card. Sets the value based on the {@link #number}
* if it has not already been set.
*/
public String getLast4() {
if (!StripeTextUtils.isBlank(last4)) {
return last4;
}
if (number != null && number.length() > 4) {
last4 = number.substring(number.length() - 4, number.length());
return last4;
}
return null;
}
/**
* Gets the {@link #brand} of this card, changed from the "type" field. Use {@link #getBrand()}
* instead.
*
* @return the {@link #brand} of this card
*/
@Deprecated
@CardBrand
public String getType() {
return getBrand();
}
/**
* Gets the {@link #brand} of this card. Updates the value if none has yet been set, or
* if the {@link #number} has been changed.
*
* @return the {@link #brand} of this card
*/
@CardBrand
public String getBrand() {
if (StripeTextUtils.isBlank(brand) && !StripeTextUtils.isBlank(number)) {
@CardBrand String evaluatedType;
if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_AMERICAN_EXPRESS)) {
evaluatedType = AMERICAN_EXPRESS;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DISCOVER)) {
evaluatedType = DISCOVER;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_JCB)) {
evaluatedType = JCB;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DINERS_CLUB)) {
evaluatedType = DINERS_CLUB;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_VISA)) {
evaluatedType = VISA;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_MASTERCARD)) {
evaluatedType = MASTERCARD;
} else {
evaluatedType = UNKNOWN;
}
brand = evaluatedType;
}
return brand;
}
/**
* @return the {@link #fingerprint} of this card
*/
public String getFingerprint() {
return fingerprint;
}
/**
* @return the {@link #funding} type of this card
*/
@Nullable
@FundingType
public String getFunding() {
return funding;
}
/**
* @return the {@link #country} of this card
*/
public String getCountry() {
return country;
}
private Card(Builder builder) {
this.number = StripeTextUtils.nullIfBlank(normalizeCardNumber(builder.number));
this.expMonth = builder.expMonth;
this.expYear = builder.expYear;
this.cvc = StripeTextUtils.nullIfBlank(builder.cvc);
this.name = StripeTextUtils.nullIfBlank(builder.name);
this.addressLine1 = StripeTextUtils.nullIfBlank(builder.addressLine1);
this.addressLine2 = StripeTextUtils.nullIfBlank(builder.addressLine2);
this.addressCity = StripeTextUtils.nullIfBlank(builder.addressCity);
this.addressState = StripeTextUtils.nullIfBlank(builder.addressState);
this.addressZip = StripeTextUtils.nullIfBlank(builder.addressZip);
this.addressCountry = StripeTextUtils.nullIfBlank(builder.addressCountry);
this.last4 = StripeTextUtils.nullIfBlank(builder.last4) == null
? getLast4()
: builder.last4;
this.brand = StripeTextUtils.asCardBrand(builder.brand) == null
? getBrand()
: builder.brand;
this.fingerprint = StripeTextUtils.nullIfBlank(builder.fingerprint);
this.funding = StripeTextUtils.asFundingType(builder.funding);
this.country = StripeTextUtils.nullIfBlank(builder.country);
this.currency = StripeTextUtils.nullIfBlank(builder.currency);
}
private String normalizeCardNumber(String number) {
if (number == null) {
return null;
}
return number.trim().replaceAll("\\s+|-", "");
}
}
|
package snowballmadness;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.inventory.*;
import org.bukkit.util.*;
/**
*
* @author DanJ
*/
public class ArrowSnowballLogic extends SnowballLogic {
private final int arrowCount;
public ArrowSnowballLogic(ItemStack arrow) {
this.arrowCount = Math.max(1, arrow.getAmount() / 8);
}
@Override
public void launch(Snowball snowball, SnowballInfo info) {
super.launch(snowball, info);
World world = snowball.getWorld();
Location location = snowball.getLocation().clone();
Vector velocity = snowball.getVelocity();
// little tweak- move the arrow a little futher out so it
// does not interact with the shooter's hitbox on the client
// side. If that happens, the client sees the arrow drop to
// the ground.
location.add(velocity.normalize().multiply(1.5));
//adjusting shot position so you can't run into it while firing
float speed = (float) (info.speed);
if (speed > 1.7) {
snowball.getWorld().playEffect(location, Effect.BOW_FIRE, null, 128);
if (speed > 3.2) {
snowball.getWorld().playEffect(location, Effect.BOW_FIRE, null, 128);
if (speed > 4.7) {
snowball.getWorld().playEffect(location, Effect.BOW_FIRE, null, 128);
if (speed > 8.9) {
snowball.getWorld().playEffect(location, Effect.BOW_FIRE, null, 128);
}
}
}
//bow or better. Sound effect.
//by doing it this way, we are stacking bow shots on top of each other.
//that overrides the limitations on how loud it can be in Minecraft, producing
//a gunshot-like effect.
}
if (info.power > 1) {
snowball.getWorld().playEffect(location, Effect.MOBSPAWNER_FLAMES, null, 128);
//any power that causes arrows to be on fire
}
//special effects give feedback when the arrow is extreme: fast, or highpowered
if (info.power > 1.0) {
for (int i = 0; i < arrowCount; ++i) {
float spread = (float) ((arrowCount * 8) / info.power);
Arrow arrow = world.spawnArrow(location, velocity, speed, spread);
arrow.setShooter(snowball.getShooter());
arrow.setFireTicks((int) (info.power * 50));
}
} else {
Arrow arrow = world.spawnArrow(location, velocity, speed, 0);
arrow.setShooter(snowball.getShooter());
}
snowball.remove();
}
}
/* @Override
public void onProjectileHit(ProjectileHitEvent event) {
Entity entity = event.getEntity();
if (entity.getType() == EntityType.ARROW) {
entity.remove();
}
} //this is outside what I understand, but was somebody's code for
// removing arrows stuck in the ground. I'd like our arrows to not
// leave tile entities stuck to blocks. More anti-lag cleanup.
}
} */
|
package com.eyekabob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class Main {
private static final String API = "api";
private static final String ARTIST = "artist";
private static final String ARTIST_ADD = "addArtist";
private static final String ARTIST_SEARCH = "search";
private static final String METHOD = "method";
private static final String QUERY = "query";
private static final String GET = "GET";
private static final String POST = "POST";
public static JSONObject processRequest(HttpServletRequest request) {
JSONObject result = null;
try {
result = new JSONObject();
String method = request.getParameter(METHOD);
String apiParam = request.getParameter(API);
Connection conn = null;
try {
conn = getConnection();
}
catch (SQLException e) {
result.put("error", "Could not establish a database connection. See server logs.");
e.printStackTrace();
}
if (ARTIST.equals(apiParam)) {
if (ARTIST_ADD.equals(method)) {
String genre = request.getParameter("genre");
String name = request.getParameter("name");
String url = request.getParameter("url");
String bio = request.getParameter("bio");
String query = "INSERT INTO artist (genre, name, url, bio) VALUES ('" + genre + "', '" + name + "', '" + url + "', '" + bio + "')";
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(query);
}
catch (SQLException e ) {
result.put("error", e.getMessage());
e.printStackTrace();
}
finally {
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
result.put("error", e.getMessage());
e.printStackTrace();
}
}
}
}
else if (ARTIST_SEARCH.equals(method)) {
String queryParam = request.getParameter(QUERY);
Statement stmt = null;
String query = "SELECT * FROM artist WHERE name LIKE '%" + queryParam + "%'";
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
JSONArray artists = new JSONArray();
while (rs.next()) {
JSONObject artist = new JSONObject();
String name = rs.getString("name");
String mbid = rs.getString("mbid");
String genre = rs.getString("genre");
String bio = rs.getString("bio");
String url = rs.getString("url");
artist.put("name", name);
artist.put("mbid", mbid);
artist.put("genre", genre);
artist.put("bio", bio);
artist.put("url", url);
artists.add(artist);
}
result.put("artists", artists);
}
catch (SQLException e ) {
e.printStackTrace();
}
finally {
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
result.put(API, apiParam);
result.put(METHOD, method);
}
catch (JSONException e) {
try {
result.put("error", "JSONException occured: " + e.getMessage());
}
catch (JSONException ex) {
// Totally boned. Can't do anything about it.
ex.printStackTrace();
}
e.printStackTrace();
}
return result;
}
private static Connection getConnection() throws SQLException {
Properties connectionProps = new Properties();
connectionProps.put("user", "eyekabob");
connectionProps.put("password", "privateeye");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
}
return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/eyekabob?autoReconnect=true", connectionProps);
}
}
|
package cn.cerc.mis.core;
import cn.cerc.core.IHandle;
import cn.cerc.db.core.IAppConfig;
import cn.cerc.mis.config.ApplicationConfig;
import cn.cerc.ui.core.UrlRecord;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@Slf4j
@Deprecated // StartAppDefault
public class StartApp implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
StringBuffer builder = req.getRequestURL();
UrlRecord url = new UrlRecord();
url.setSite(builder.toString());
Map<String, String[]> items = req.getParameterMap();
for (String key : items.keySet()) {
String[] values = items.get(key);
for (String value : values) {
url.putParam(key, value);
}
}
log.info("url {}", url.getUrl());
String uri = req.getRequestURI();
Application.get(req);
if ("/".equals(uri)) {
if (req.getParameter(ClientDevice.APP_CLIENT_ID) != null) {
req.getSession().setAttribute(ClientDevice.APP_CLIENT_ID, req.getParameter(ClientDevice.APP_CLIENT_ID));
}
if (req.getParameter(ClientDevice.APP_DEVICE_TYPE) != null) {
req.getSession().setAttribute(ClientDevice.APP_DEVICE_TYPE,
req.getParameter(ClientDevice.APP_DEVICE_TYPE));
}
IAppConfig conf = Application.getAppConfig();
resp.sendRedirect(String.format("%s%s", ApplicationConfig.App_Path, conf.getFormWelcome()));
return;
} else if ("/MobileConfig".equals(uri) || "/mobileConfig".equals(uri)) {
if (req.getParameter(ClientDevice.APP_CLIENT_ID) != null) {
req.getSession().setAttribute(ClientDevice.APP_CLIENT_ID, req.getParameter(ClientDevice.APP_CLIENT_ID));
}
if (req.getParameter(ClientDevice.APP_DEVICE_TYPE) != null) {
req.getSession().setAttribute(ClientDevice.APP_DEVICE_TYPE,
req.getParameter(ClientDevice.APP_DEVICE_TYPE));
}
try {
IForm form;
if (Application.get(req).containsBean("mobileConfig")) {
form = Application.getBean("mobileConfig", IForm.class);
} else {
form = Application.getBean("MobileConfig", IForm.class);
}
form.setRequest((HttpServletRequest) request);
form.setResponse((HttpServletResponse) response);
IHandle handle = Application.getHandle();
handle.setProperty(Application.sessionId, req.getSession().getId());
form.setHandle(handle);
IPage page = form.execute();
page.execute();
} catch (Exception e) {
resp.getWriter().print(e.getMessage());
}
return;
}
chain.doFilter(req, resp);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
|
package org.sonar.plugins.stash.client;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpClientConfigDefaults;
import com.ning.http.client.Realm;
import com.ning.http.client.Realm.AuthScheme;
import com.ning.http.client.Response;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.sonar.plugins.stash.ContentType;
import org.sonar.plugins.stash.PluginInfo;
import org.sonar.plugins.stash.PluginUtils;
import org.sonar.plugins.stash.StashPlugin;
import org.sonar.plugins.stash.exceptions.StashClientException;
import org.sonar.plugins.stash.exceptions.StashReportExtractionException;
import org.sonar.plugins.stash.issue.StashComment;
import org.sonar.plugins.stash.issue.StashCommentReport;
import org.sonar.plugins.stash.issue.StashDiffReport;
import org.sonar.plugins.stash.issue.StashPullRequest;
import org.sonar.plugins.stash.issue.StashTask;
import org.sonar.plugins.stash.issue.StashUser;
import org.sonar.plugins.stash.issue.collector.StashCollector;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static java.net.HttpURLConnection.HTTP_CREATED;
public class StashClient implements AutoCloseable {
private final String baseUrl;
private final StashCredentials credentials;
private final int stashTimeout;
private AsyncHttpClient httpClient;
private static final String REST_API = "/rest/api/1.0/";
private static final String USER_API = "{0}" + REST_API + "users/{1}";
private static final String REPO_API = "{0}" + REST_API + "projects/{1}/repos/{2}/";
private static final String TASKS_API = REST_API + "tasks";
private static final String API_ALL_PR = REPO_API + "pull-requests/";
private static final String API_ONE_PR = API_ALL_PR + "{3}";
private static final String API_ONE_PR_ALL_COMMENTS = API_ONE_PR + "/comments";
private static final String API_ONE_PR_DIFF = API_ONE_PR + "/diff?withComments=true";
private static final String API_ONE_PR_APPROVAL = API_ONE_PR + "/approve";
private static final String API_ONE_PR_COMMENT_PATH = API_ONE_PR + "/comments?path={4}&start={5}";
private static final String API_ONE_PR_ONE_COMMENT = API_ONE_PR_ALL_COMMENTS + "/{4}?version={5}";
private static final String PULL_REQUEST_APPROVAL_POST_ERROR_MESSAGE = "Unable to change status of pull-request {0}
private static final String PULL_REQUEST_GET_ERROR_MESSAGE = "Unable to retrieve pull-request {0}
private static final String PULL_REQUEST_PUT_ERROR_MESSAGE = "Unable to update pull-request {0}
private static final String USER_GET_ERROR_MESSAGE = "Unable to retrieve user {0}.";
private static final String COMMENT_POST_ERROR_MESSAGE = "Unable to post a comment to {0}
private static final String COMMENT_GET_ERROR_MESSAGE = "Unable to get comment linked to {0}
private static final String COMMENT_DELETION_ERROR_MESSAGE = "Unable to delete comment {0} from pull-request {1}
private static final String TASK_POST_ERROR_MESSAGE = "Unable to post a task on comment {0}.";
private static final String TASK_DELETION_ERROR_MESSAGE = "Unable to delete task {0}.";
private static final ContentType JSON = new ContentType("application", "json", null);
public StashClient(String url, StashCredentials credentials, int stashTimeout, String sonarQubeVersion) {
this.baseUrl = url;
this.credentials = credentials;
this.stashTimeout = stashTimeout;
this.httpClient = createHttpClient(sonarQubeVersion);
}
public void postCommentOnPullRequest(String project, String repository, String pullRequestId, String report)
throws StashClientException {
String request = MessageFormat.format(API_ONE_PR_ALL_COMMENTS, baseUrl, project, repository, pullRequestId);
JSONObject json = new JSONObject();
json.put("text", report);
postCreate(request, json, MessageFormat.format(COMMENT_POST_ERROR_MESSAGE, repository, pullRequestId));
}
public StashCommentReport getPullRequestComments(String project, String repository, String pullRequestId, String path)
throws StashClientException {
StashCommentReport result = new StashCommentReport();
long start = 0;
boolean isLastPage = false;
while (! isLastPage){
try {
String request = MessageFormat.format(API_ONE_PR_COMMENT_PATH, baseUrl, project, repository, pullRequestId, path, start);
JSONObject jsonComments = get(request, MessageFormat.format(COMMENT_GET_ERROR_MESSAGE, repository, pullRequestId));
result.add(StashCollector.extractComments(jsonComments));
// Stash pagination: check if you get all comments linked to the pull-request
isLastPage = StashCollector.isLastPage(jsonComments);
start = StashCollector.getNextPageStart(jsonComments);
} catch (StashReportExtractionException e) {
throw new StashClientException(e);
}
}
return result;
}
public void deletePullRequestComment(String project, String repository, String pullRequestId, StashComment comment)
throws StashClientException {
String request = MessageFormat.format(API_ONE_PR_ONE_COMMENT, baseUrl, project, repository, pullRequestId,
Long.toString(comment.getId()), Long.toString(comment.getVersion()));
delete(request, MessageFormat.format(COMMENT_DELETION_ERROR_MESSAGE, comment.getId(), repository, pullRequestId));
}
public StashDiffReport getPullRequestDiffs(String project, String repository, String pullRequestId)
throws StashClientException {
StashDiffReport result = new StashDiffReport();
try {
String request = MessageFormat.format(API_ONE_PR_DIFF, baseUrl, project, repository, pullRequestId);
JSONObject jsonDiffs = get(request, MessageFormat.format(COMMENT_GET_ERROR_MESSAGE, repository, pullRequestId));
result = StashCollector.extractDiffs(jsonDiffs);
} catch (StashReportExtractionException e) {
throw new StashClientException(e);
}
return result;
}
public StashComment postCommentLineOnPullRequest(String project, String repository, String pullRequestId, String message, String path, long line, String type)
throws StashClientException {
String request = MessageFormat.format(API_ONE_PR_ALL_COMMENTS, baseUrl, project, repository, pullRequestId);
JSONObject anchor = new JSONObject();
if (line != 0L) {
anchor.put("line", line);
anchor.put("lineType", type);
}
String fileType = "TO";
if (StringUtils.equals(type, StashPlugin.CONTEXT_ISSUE_TYPE)){
fileType = "FROM";
}
anchor.put("fileType", fileType);
anchor.put("path", path);
JSONObject json = new JSONObject();
json.put("text", message);
json.put("anchor", anchor);
JSONObject response = postCreate(request, json,
MessageFormat.format(COMMENT_POST_ERROR_MESSAGE, repository, pullRequestId));
return StashCollector.extractComment(response, path, line);
}
public StashUser getUser(String userSlug) throws StashClientException {
String request = MessageFormat.format(USER_API, baseUrl, userSlug);
JSONObject response = get(request, MessageFormat.format(USER_GET_ERROR_MESSAGE, userSlug));
return StashCollector.extractUser(response);
}
public StashPullRequest getPullRequest(String project, String repository, String pullRequestId)
throws StashClientException {
String request = MessageFormat.format(API_ONE_PR, baseUrl, project, repository, pullRequestId);
JSONObject response = get(request, MessageFormat.format(PULL_REQUEST_GET_ERROR_MESSAGE, repository, pullRequestId));
return StashCollector.extractPullRequest(project, repository, pullRequestId, response);
}
public void addPullRequestReviewer(String project, String repository, String pullRequestId, long pullRequestVersion, ArrayList<StashUser> reviewers)
throws StashClientException {
String request = MessageFormat.format(API_ONE_PR, baseUrl, project, repository, pullRequestId);
JSONObject json = new JSONObject();
JSONArray jsonReviewers = new JSONArray();
for (StashUser reviewer: reviewers) {
JSONObject reviewerName = new JSONObject();
reviewerName.put("name", reviewer.getName());
JSONObject user = new JSONObject();
user.put("user", reviewerName);
jsonReviewers.add(user);
}
json.put("reviewers", jsonReviewers);
json.put("id", pullRequestId);
json.put("version", pullRequestVersion);
put(request, json, MessageFormat.format(PULL_REQUEST_PUT_ERROR_MESSAGE, repository, pullRequestId));
}
public void approvePullRequest(String project, String repository, String pullRequestId) throws StashClientException {
String request = MessageFormat.format(API_ONE_PR_APPROVAL, baseUrl, project, repository, pullRequestId);
post(request, null, MessageFormat.format(PULL_REQUEST_APPROVAL_POST_ERROR_MESSAGE, repository, pullRequestId));
}
public void resetPullRequestApproval(String project, String repository, String pullRequestId) throws StashClientException {
String request = MessageFormat.format(API_ONE_PR_APPROVAL, baseUrl, project, repository, pullRequestId);
delete(request, HttpURLConnection.HTTP_OK, MessageFormat.format(PULL_REQUEST_APPROVAL_POST_ERROR_MESSAGE, repository, pullRequestId));
}
public void postTaskOnComment(String message, Long commentId) throws StashClientException {
String request = baseUrl + TASKS_API;
JSONObject anchor = new JSONObject();
anchor.put("id", commentId);
anchor.put("type", "COMMENT");
JSONObject json = new JSONObject();
json.put("anchor", anchor);
json.put("text", message);
postCreate(request, json, MessageFormat.format(TASK_POST_ERROR_MESSAGE, commentId));
}
public void deleteTaskOnComment(StashTask task) throws StashClientException {
String request = baseUrl + TASKS_API + "/" + task.getId();
delete(request, MessageFormat.format(TASK_DELETION_ERROR_MESSAGE, task.getId()));
}
@Override
public void close() {
httpClient.close();
}
private JSONObject get(String url, String errorMessage) throws StashClientException {
return performRequest(httpClient.prepareGet(url), null, HttpURLConnection.HTTP_OK, errorMessage);
}
private JSONObject post(String url, JSONObject body, String errorMessage) throws StashClientException {
return performRequest(httpClient.preparePost(url), body, HttpURLConnection.HTTP_OK, errorMessage);
}
private JSONObject postCreate(String url, JSONObject body, String errorMessage) throws StashClientException {
return performRequest(httpClient.preparePost(url), body, HTTP_CREATED, errorMessage);
}
private JSONObject delete(String url, int expectedStatusCode, String errorMessage) throws StashClientException {
return performRequest(httpClient.prepareDelete(url), null, expectedStatusCode, errorMessage);
}
private JSONObject delete(String url, String errorMessage) throws StashClientException {
return delete(url, HttpURLConnection.HTTP_NO_CONTENT, errorMessage);
}
private JSONObject put(String url, JSONObject body, String errorMessage) throws StashClientException {
return performRequest(httpClient.preparePut(url), body, HttpURLConnection.HTTP_OK, errorMessage);
}
private JSONObject performRequest(BoundRequestBuilder requestBuilder, JSONObject body, int expectedStatusCode, String errorMessage)
throws StashClientException {
if (body != null) {
requestBuilder.setBody(body.toString());
}
Realm realm = new Realm.RealmBuilder().setPrincipal(credentials.getLogin()).setPassword(credentials.getPassword())
.setUsePreemptiveAuth(true).setScheme(AuthScheme.BASIC).build();
requestBuilder.setRealm(realm);
requestBuilder.setFollowRedirects(true);
requestBuilder.addHeader("Content-Type", "application/json");
try {
Response response = requestBuilder.execute().get(stashTimeout, TimeUnit.MILLISECONDS);
validateResponse(response, expectedStatusCode, errorMessage);
return extractResponse(response);
} catch (ExecutionException | TimeoutException | InterruptedException e) {
throw new StashClientException(e);
}
}
private static void validateResponse(Response response, int expectedStatusCode, String message) throws StashClientException {
int responseCode = response.getStatusCode();
if (responseCode != expectedStatusCode) {
throw new StashClientException(message + " Received " + responseCode + ": " + formatStashApiError(response));
}
}
private static JSONObject extractResponse(Response response) throws StashClientException {
String body = null;
try {
body = response.getResponseBody();
} catch (IOException e) {
throw new StashClientException("Could not load response body", e);
}
if (StringUtils.isEmpty(body)) {
return null;
}
String contentType = response.getHeader("Content-Type");
if (!JSON.match(StringUtils.strip(contentType))) {
throw new StashClientException("Received response with type " + contentType + " instead of JSON");
}
try {
Object obj = new JSONParser().parse(body);
return (JSONObject)obj;
} catch (ParseException | ClassCastException e) {
throw new StashClientException("Could not parse JSON response " + e + "('" + body + "')", e);
}
}
private static String formatStashApiError(Response response) throws StashClientException {
JSONArray errors;
JSONObject responseJson = extractResponse(response);
errors = (JSONArray)responseJson.get("errors");
if (errors == null) {
throw new StashClientException("Error response did not contain an errors object '" + responseJson + "'");
}
List<String> errorParts = new ArrayList<>();
for (Object o : errors) {
try {
JSONObject error = (JSONObject)o;
errorParts.add((String)error.get("exceptionName") + ": " + (String)error.get("message"));
} catch (ClassCastException e) {
throw new StashClientException("Error response contained invalid error", e);
}
}
return StringUtils.join(errorParts, ", ");
}
// We can't test this, as the manifest can only be loaded when deployed from a JAR-archive.
// During unit testing this is not the case
private static String getUserAgent(String sonarQubeVersion) {
PluginInfo info = PluginUtils.infoForPluginClass(StashPlugin.class);
String name;
String version;
name = version = "unknown";
if (info != null) {
name = info.getName();
version = info.getVersion();
}
return MessageFormat.format("SonarQube/{0} {1}/{2} {3}",
sonarQubeVersion == null ? "unknown" : sonarQubeVersion,
name,
version,
AsyncHttpClientConfigDefaults.defaultUserAgent());
}
AsyncHttpClient createHttpClient(String sonarQubeVersion){
return new AsyncHttpClient(
new AsyncHttpClientConfig.Builder().setUserAgent(getUserAgent(sonarQubeVersion)).build());
}
}
|
package org.tapestry.controller;
import org.springframework.stereotype.Controller;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.tapestry.dao.UserDao;
import org.tapestry.dao.PatientDao;
import org.tapestry.dao.AppointmentDao;
import org.tapestry.dao.MessageDao;
import org.tapestry.dao.SurveyTemplateDao;
import org.tapestry.dao.PictureDao;
import org.tapestry.dao.ActivityDao;
import org.tapestry.objects.User;
import org.tapestry.objects.Patient;
import org.tapestry.objects.Appointment;
import org.tapestry.objects.Message;
import org.tapestry.objects.SurveyTemplate;
import org.tapestry.objects.Activity;
import java.util.ArrayList;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.util.Map;
import org.springframework.core.io.ClassPathResource;
import javax.annotation.PostConstruct;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* Main controller class
* This class is responsible for interpreting URLs and returning the appropriate pages.
* It is the 'brain' of the application. Each function is tagged with @RequestMapping and
* one of either RequestMethod.GET or RequestMethod.POST, which determines which requests
* the function will be triggered in response to.
* The function returns a string, which is the name of a web page to render. For example,
* the login() function returns "login" when an HTTP request like "HTTP 1.1 GET /login"
* is received. The application then loads the page "login.jsp" (the extension is added
* automatically).
*/
@Controller
public class TapestryController{
private ClassPathResource dbConfigFile;
private Map<String, String> config;
private Yaml yaml;
private UserDao userDao;
private PatientDao patientDao;
private AppointmentDao appointmentDao;
private MessageDao messageDao;
private PictureDao pictureDao;
private SurveyTemplateDao surveyTemplateDao;
private ActivityDao activityDao;
//Mail-related settings;
private Properties props;
private String mailAddress = "";
private Session session;
/**
* Reads the file /WEB-INF/classes/db.yaml and gets the values contained therein
*/
@PostConstruct
public void readConfig(){
String database = "";
String dbUsername = "";
String dbPassword = "";
String mailHost = "";
String mailUser = "";
String mailPassword = "";
String mailPort = "";
String useTLS = "";
String useAuth = "";
try{
dbConfigFile = new ClassPathResource("tapestry.yaml");
yaml = new Yaml();
config = (Map<String, String>) yaml.load(dbConfigFile.getInputStream());
database = config.get("url");
dbUsername = config.get("username");
dbPassword = config.get("password");
mailHost = config.get("mailHost");
mailUser = config.get("mailUser");
mailPassword = config.get("mailPassword");
mailAddress = config.get("mailAddress");
mailPort = config.get("mailPort");
useTLS = config.get("mailUsesTLS");
useAuth = config.get("mailRequiresAuth");
} catch (IOException e) {
System.out.println("Error reading from config file");
System.out.println(e.toString());
}
//Create the DAOs
userDao = new UserDao(database, dbUsername, dbPassword);
patientDao = new PatientDao(database, dbUsername, dbPassword);
appointmentDao = new AppointmentDao(database, dbUsername, dbPassword);
messageDao = new MessageDao(database, dbUsername, dbPassword);
pictureDao = new PictureDao(database, dbUsername, dbPassword);
activityDao = new ActivityDao(database, dbUsername, dbPassword);
//Mail-related settings
final String username = mailUser;
final String password = mailPassword;
props = System.getProperties();
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
surveyTemplateDao = new SurveyTemplateDao(database, dbUsername, dbPassword);
props.setProperty("mail.smtp.host", mailHost);
props.setProperty("mail.smtp.socketFactory.port", mailPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.auth", useAuth);
props.setProperty("mail.smtp.starttls.enable", useTLS);
props.setProperty("mail.user", mailUser);
props.setProperty("mail.password", mailPassword);
}
//Everything below this point is a RequestMapping
@RequestMapping(value="/login", method=RequestMethod.GET)
public String login(@RequestParam(value="usernameChanged", required=false) Boolean usernameChanged, ModelMap model){
if (usernameChanged != null)
model.addAttribute("usernameChanged", usernameChanged);
return "login";
}
@RequestMapping(value={"/", "/loginsuccess"}, method=RequestMethod.GET)
//Note that messageSent is Boolean, not boolean, to allow it to be null
public String welcome(@RequestParam(value="success", required=false) Boolean messageSent, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
if (request.isUserInRole("ROLE_USER")){
String username = request.getUserPrincipal().getName();
User u = userDao.getUserByUsername(username);
ArrayList<Patient> patientsForUser = patientDao.getPatientsForVolunteer(u.getUserID());
ArrayList<Appointment> appointmentsForToday = appointmentDao.getAllAppointmentsForVolunteerForToday(u.getUserID());
ArrayList<Appointment> allAppointments = appointmentDao.getAllAppointmentsForVolunteer(u.getUserID());
ArrayList<Activity> activityLog = activityDao.getLastNActivitiesForVolunteer(u.getUserID(), 5); //Cap recent activities at 5
//ArrayList<String> activityLog = activityDao.getAllActivitiesForVolunteer(u.getUserID());
model.addAttribute("name", u.getName());
model.addAttribute("patients", patientsForUser);
model.addAttribute("appointments_today", appointmentsForToday);
model.addAttribute("appointments_all", allAppointments);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(u.getUserID());
model.addAttribute("unread", unreadMessages);
model.addAttribute("activities", activityLog);
return "volunteer/index";
}
else if (request.isUserInRole("ROLE_ADMIN")){
String name = request.getUserPrincipal().getName();
model.addAttribute("name", name);
ArrayList<User> volunteers = userDao.getAllUsersWithRole("ROLE_USER");
model.addAttribute("volunteers", volunteers);
if (messageSent != null)
model.addAttribute("success", messageSent);
return "admin/index";
}
else{ //This should not happen, but catch any unforseen behavior
return "redirect:/login";
}
}
@RequestMapping(value="/loginfailed", method=RequestMethod.GET)
public String failed(ModelMap model){
model.addAttribute("error", "true");
return "login";
}
@RequestMapping(value="/manage_users", method=RequestMethod.GET)
public String manageUsers(ModelMap model){
ArrayList<User> userList = userDao.getAllUsers();
model.addAttribute("users", userList);
return "admin/manage_users";
}
@RequestMapping(value="/manage_patients", method=RequestMethod.GET)
public String managePatients(ModelMap model){
ArrayList<User> volunteers = userDao.getAllUsersWithRole("ROLE_USER");
model.addAttribute("volunteers", volunteers);
ArrayList<Patient> patientList = patientDao.getAllPatients();
model.addAttribute("patients", patientList);
return "admin/manage_patients";
}
@RequestMapping(value="/add_user", method=RequestMethod.POST)
public String addUser(SecurityContextHolderAwareRequestWrapper request){
//Add a new user
User u = new User();
u.setName(request.getParameter("name"));
u.setUsername(request.getParameter("username"));
u.setRole(request.getParameter("role"));
ShaPasswordEncoder enc = new ShaPasswordEncoder();
String hashedPassword = enc.encodePassword("password", null); //Default
u.setPassword(hashedPassword);
u.setEmail(request.getParameter("email"));
userDao.createUser(u);
activityDao.logActivity("Added user: " + u.getName(), u.getUserID());
if (mailAddress != null){
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailAddress));
message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(u.getEmail()));
message.setSubject("Welcome to Tapestry");
String msg = "";
msg += "Thank you for volunteering with Tapestry. Your accout has successfully been created.\n";
msg += "Your username and password are as follows:\n";
msg += "Username: " + u.getUsername() + "\n";
msg += "Password: password\n";
message.setText(msg);
System.out.println(msg);
System.out.println("Sending...");
Transport.send(message);
System.out.println("Email sent containing credentials to " + u.getEmail());
} catch (MessagingException e) {
System.out.println("Error: Could not send email");
System.out.println(e.toString());
}
}
//Display page again
return "redirect:/manage_users";
}
@RequestMapping(value="/remove_user/{user_id}", method=RequestMethod.GET)
public String removeUser(@PathVariable("user_id") int id){
userDao.removeUserWithId(id);
activityDao.logActivity("Removed user: " + id, id);
return "redirect:/manage_users";
}
@RequestMapping(value="/add_patient", method=RequestMethod.POST)
public String addPatient(SecurityContextHolderAwareRequestWrapper request){
//Add a new patient
Patient p = new Patient();
p.setFirstName(request.getParameter("firstname"));
p.setLastName(request.getParameter("lastname"));
int v = Integer.parseInt(request.getParameter("volunteer"));
p.setVolunteer(v);
p.setColor(request.getParameter("backgroundColor"));
p.setBirthdate(request.getParameter("birthdate"));
p.setGender(request.getParameter("gender"));
patientDao.createPatient(p);
activityDao.logActivity("Added patient: " + p.getDisplayName(), v);
return "redirect:/manage_patients";
}
@RequestMapping(value="/remove_patient/{patient_id}", method=RequestMethod.GET)
public String removePatient(@PathVariable("patient_id") int id){
Patient p = patientDao.getPatientByID(id);
patientDao.removePatientWithId(id);
activityDao.logActivity("Removed patient: " + p.getDisplayName(), p.getVolunteer(), p.getPatientID());
return "redirect:/manage_patients";
}
@RequestMapping(value="/patient/{patient_id}", method=RequestMethod.GET)
public String viewPatient(@PathVariable("patient_id") int id, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
Patient patient = patientDao.getPatientByID(id);
//Find the name of the current user
User u = userDao.getUserByUsername(request.getUserPrincipal().getName());
String loggedInUser = u.getName();
//Make sure that the user is actually responsible for the patient in question
int volunteerForPatient = patient.getVolunteer();
if (!(u.getUserID() == patient.getVolunteer())){
model.addAttribute("loggedIn", loggedInUser);
model.addAttribute("patientOwner", volunteerForPatient);
return "redirect:/403";
}
model.addAttribute("patient", patient);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(u.getUserID());
model.addAttribute("unread", unreadMessages);
return "/patient";
}
@RequestMapping(value="/book_appointment", method=RequestMethod.POST)
public String addAppointment(SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User u = userDao.getUserByUsername(request.getUserPrincipal().getName());
int loggedInUser = u.getUserID();
Appointment a = new Appointment();
a.setVolunteer(loggedInUser);
int pid = Integer.parseInt(request.getParameter("patient"));
a.setPatientID(pid);
a.setDate(request.getParameter("appointmentDate"));
a.setTime(request.getParameter("appointmentTime"));
appointmentDao.createAppointment(a);
Patient p = patientDao.getPatientByID(pid);
activityDao.logActivity("Booked appointment with " + p.getDisplayName(), loggedInUser, pid);
return "redirect:/";
}
@RequestMapping(value="/profile", method=RequestMethod.GET)
public String viewProfile(@RequestParam(value="error", required=false) String errorsPresent, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
model.addAttribute("vol", loggedInUser);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("unread", unreadMessages);
if (errorsPresent != null)
model.addAttribute("errors", errorsPresent);
ArrayList<String> pics = pictureDao.getPicturesForUser(loggedInUser.getUserID());
model.addAttribute("pictures", pics);
return "/volunteer/profile";
}
@RequestMapping(value="/inbox", method=RequestMethod.GET)
public String viewInbox(SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
ArrayList<Message> messages = messageDao.getAllMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("messages", messages);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("unread", unreadMessages);
return "/volunteer/inbox";
}
@RequestMapping(value="/view_message/{msgID}", method=RequestMethod.GET)
public String viewMessage(@PathVariable("msgID") int id, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
Message m = messageDao.getMessageByID(id);
if (!(m.getRecipient() == loggedInUser.getUserID()))
return "redirect:/403";
if (!(m.isRead()))
messageDao.markAsRead(id);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("unread", unreadMessages);
model.addAttribute("message", m);
return "/volunteer/view_message";
}
@RequestMapping(value="/send_message", method=RequestMethod.POST)
public String sendMessage(SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
Message m = new Message();
m.setSender(loggedInUser.getName());
m.setRecipient(Integer.parseInt(request.getParameter("recipient")));
m.setText(request.getParameter("msgBody"));
m.setSubject(request.getParameter("msgSubject"));
messageDao.sendMessage(m);
return "redirect:/?success=true";
}
@RequestMapping(value="/delete_message/{msgID}", method=RequestMethod.GET)
public String deleteMessage(@PathVariable("msgID") int id, ModelMap model){
messageDao.deleteMessage(id);
return "redirect:/inbox";
}
//Error pages
@RequestMapping(value="/403", method=RequestMethod.GET)
public String forbiddenError(){
return "error-forbidden";
}
@RequestMapping(value="/update_user", method=RequestMethod.POST)
public String updateUser(SecurityContextHolderAwareRequestWrapper request){
String currentUsername = request.getUserPrincipal().getName();
User loggedInUser = userDao.getUserByUsername(currentUsername);
User u = new User();
u.setUserID(loggedInUser.getUserID());
u.setUsername(request.getParameter("volUsername"));
u.setName(request.getParameter("volName"));
u.setEmail(request.getParameter("volEmail"));
userDao.modifyUser(u);
activityDao.logActivity("Updated user information", loggedInUser.getUserID());
if (!(currentUsername.equals(u.getUsername())))
return "redirect:/login?usernameChanged=true";
else
return "redirect:/profile";
}
@RequestMapping(value="/manage_survey_templates", method=RequestMethod.GET)
public String manageSurveyTemplates(ModelMap model){
ArrayList<SurveyTemplate> surveyTemplateList = surveyTemplateDao.getAllSurveyTemplates();
model.addAttribute("survey_templates", surveyTemplateList);
return "admin/manage_survey_templates";
}
@RequestMapping(value="/change_password", method=RequestMethod.POST)
public String changePassword(SecurityContextHolderAwareRequestWrapper request){
String currentUsername = request.getUserPrincipal().getName();
User loggedInUser = userDao.getUserByUsername(currentUsername);
String currentPassword = request.getParameter("currentPassword");
String newPassword = request.getParameter("newPassword");
String confirmPassword = request.getParameter("confirmPassword");
if (!newPassword.equals(confirmPassword)){
return "redirect:/profile?error=confirm";
}
if (!userDao.userHasPassword(loggedInUser.getUserID(), currentPassword)){
return "redirect:/profile?error=current";
}
ShaPasswordEncoder enc = new ShaPasswordEncoder();
String hashedPassword = enc.encodePassword(newPassword, null);
userDao.setPasswordForUser(loggedInUser.getUserID(), hashedPassword);
activityDao.logActivity("Changed password", loggedInUser.getUserID());
return "redirect:/profile";
}
}
|
package org.testng.internal;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.testng.IConfigurable;
import org.testng.IConfigureCallBack;
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.TestNGException;
import org.testng.internal.InvokeMethodRunnable.TestNGRuntimeException;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.internal.collections.ArrayIterator;
import org.testng.internal.collections.OneToTwoDimArrayIterator;
import org.testng.internal.collections.OneToTwoDimIterator;
import org.testng.internal.collections.Pair;
import org.testng.internal.thread.ThreadExecutionException;
import org.testng.internal.thread.ThreadTimeoutException;
import org.testng.internal.thread.ThreadUtil;
import org.testng.xml.XmlSuite;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Collections of helper methods to help deal with invocation of TestNG methods
*/
public class MethodInvocationHelper {
protected static Object invokeMethodNoCheckedException(
Method thisMethod, Object instance, List<Object> parameters) {
try {
return invokeMethod(thisMethod, instance, parameters);
} catch (InvocationTargetException | IllegalAccessException e) {
// Don't throw TestNGException here or this test won't be reported as a
// skip or failure
throw new RuntimeException(e.getCause());
}
}
protected static void invokeMethodConsideringTimeout(
ITestNGMethod tm,
ConstructorOrMethod method,
Object targetInstance,
Object[] params,
ITestResult testResult)
throws Throwable {
if (MethodHelper.calculateTimeOut(tm) <= 0) {
MethodInvocationHelper.invokeMethod(method.getMethod(), targetInstance, params);
} else {
MethodInvocationHelper.invokeWithTimeout(tm, targetInstance, params, testResult);
if (!testResult.isSuccess()) {
// A time out happened
Throwable ex = testResult.getThrowable();
testResult.setStatus(ITestResult.FAILURE);
testResult.setThrowable(ex.getCause() == null ? ex : ex.getCause());
throw testResult.getThrowable();
}
}
}
protected static Object invokeMethod(Method thisMethod, Object instance, List<Object> parameters)
throws InvocationTargetException, IllegalAccessException {
return invokeMethod(thisMethod, instance, parameters.toArray(new Object[0]));
}
protected static Object invokeMethod(Method thisMethod, Object instance, Object[] parameters)
throws InvocationTargetException, IllegalAccessException {
Utils.checkInstanceOrStatic(instance, thisMethod);
// TESTNG-326, allow IObjectFactory to load from non-standard classloader
// If the instance has a different classloader, its class won't match the
// method's class
if (instance != null && !thisMethod.getDeclaringClass().isAssignableFrom(instance.getClass())) {
// for some reason, we can't call this method on this class
// is it static?
boolean isStatic = Modifier.isStatic(thisMethod.getModifiers());
if (!isStatic) {
// not static, so grab a method with the same name and signature in this case
Class<?> clazz = instance.getClass();
try {
thisMethod = clazz.getMethod(thisMethod.getName(), thisMethod.getParameterTypes());
} catch (Exception e) {
// ignore, the method may be private
boolean found = false;
for (; clazz != null; clazz = clazz.getSuperclass()) {
try {
thisMethod =
clazz.getDeclaredMethod(thisMethod.getName(), thisMethod.getParameterTypes());
found = true;
break;
} catch (Exception e2) {
}
}
if (!found) {
// should we assert here? Or just allow it to fail on invocation?
if (thisMethod.getDeclaringClass().equals(instance.getClass())) {
throw new RuntimeException(
"Can't invoke method " + thisMethod + ", probably due to classloader mismatch");
}
throw new RuntimeException(
"Can't invoke method "
+ thisMethod
+ " on this instance of "
+ instance.getClass()
+ " due to class mismatch");
}
}
}
}
if (!Modifier.isPublic(thisMethod.getModifiers()) || !thisMethod.isAccessible()) {
try {
thisMethod.setAccessible(true);
} catch (SecurityException e) {
throw new TestNGException(thisMethod.getName() + " must be public", e);
}
}
cleanInterruptStatus();
return thisMethod.invoke(instance, parameters);
}
@SuppressWarnings("unchecked")
protected static Iterator<Object[]> invokeDataProvider(
Object instance,
Method dataProvider,
ITestNGMethod method,
ITestContext testContext,
Object fedInstance,
IAnnotationFinder annotationFinder) {
List<Object> parameters =
getParameters(dataProvider, method, testContext, fedInstance, annotationFinder);
Object result = invokeMethodNoCheckedException(dataProvider, instance, parameters);
if (result == null) {
throw new TestNGException("Data Provider " + dataProvider + " returned a null value");
}
// If it returns an Object[][] or Object[], convert it to an Iterator<Object[]>
if (result instanceof Object[][]) {
return new ArrayIterator((Object[][]) result);
} else if (result instanceof Object[]) {
return new OneToTwoDimArrayIterator((Object[]) result);
} else if (result instanceof Iterator) {
Type returnType = dataProvider.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
ParameterizedType contentType = (ParameterizedType) returnType;
Class<?> type = (Class<?>) contentType.getActualTypeArguments()[0];
if (type.isArray()) {
return (Iterator<Object[]>) result;
} else {
return new OneToTwoDimIterator((Iterator<Object>) result);
}
} else {
// Raw Iterator, we expect user provides the expected type
return (Iterator<Object[]>) result;
}
}
throw new TestNGException(
"Data Provider "
+ dataProvider
+ " must return"
+ " either Object[][] or Object[] or Iterator<Object[]> or Iterator<Object>, not "
+ dataProvider.getReturnType());
}
private static List<Object> getParameters(
Method dataProvider,
ITestNGMethod method,
ITestContext testContext,
Object fedInstance,
IAnnotationFinder annotationFinder) {
// Go through all the parameters declared on this Data Provider and
// make sure we have at most one Method and one ITestContext.
// Anything else is an error
List<Object> parameters = new ArrayList<>();
Collection<Pair<Integer, Class<?>>> unresolved = new ArrayList<>();
ConstructorOrMethod com = method.getConstructorOrMethod();
int i = 0;
for (Class<?> cls : dataProvider.getParameterTypes()) {
if (cls.equals(Method.class)) {
parameters.add(com.getMethod());
} else if (cls.equals(Constructor.class)) {
parameters.add(com.getConstructor());
} else if (cls.equals(ConstructorOrMethod.class)) {
parameters.add(com);
} else if (cls.equals(ITestNGMethod.class)) {
parameters.add(method);
} else if (cls.equals(ITestContext.class)) {
parameters.add(testContext);
} else if (cls.equals(Class.class)) {
parameters.add(com.getDeclaringClass());
} else {
boolean isTestInstance = annotationFinder.hasTestInstance(dataProvider, i);
if (isTestInstance) {
parameters.add(fedInstance);
} else {
unresolved.add(new Pair<>(i, cls));
}
}
i++;
}
if (!unresolved.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("Some DataProvider ").append(dataProvider).append(" parameters unresolved: ");
for (Pair<Integer, Class<?>> pair : unresolved) {
sb.append(" at ").append(pair.first()).append(" type ").append(pair.second()).append("\n");
}
throw new TestNGException(sb.toString());
}
return parameters;
}
protected static void invokeHookable(
final Object testInstance,
final Object[] parameters,
final IHookable hookable,
final Method thisMethod,
final ITestResult testResult)
throws Throwable {
final Throwable[] error = new Throwable[1];
IHookCallBack callback =
new IHookCallBack() {
@Override
public void runTestMethod(ITestResult tr) {
try {
invokeMethod(thisMethod, testInstance, parameters);
error[0] = null;
tr.setThrowable(null);
} catch (Throwable t) {
error[0] = t;
tr.setThrowable(t); // make Throwable available to IHookable
}
}
@Override
public Object[] getParameters() {
return parameters;
}
};
hookable.run(callback, testResult);
if (error[0] != null) {
throw error[0];
}
}
/**
* Invokes a method on a separate thread in order to allow us to timeout the invocation. It uses
* as implementation an <code>Executor</code> and a <code>CountDownLatch</code>.
*/
protected static void invokeWithTimeout(
ITestNGMethod tm, Object instance, Object[] parameterValues, ITestResult testResult)
throws InterruptedException, ThreadExecutionException {
invokeWithTimeout(tm, instance, parameterValues, testResult, null);
}
protected static void invokeWithTimeout(
ITestNGMethod tm,
Object instance,
Object[] parameterValues,
ITestResult testResult,
IHookable hookable)
throws InterruptedException, ThreadExecutionException {
if (ThreadUtil.isTestNGThread()
&& testResult.getTestContext().getCurrentXmlTest().getParallel()
!= XmlSuite.ParallelMode.TESTS) {
// We are already running in our own executor, don't create another one (or we will
// lose the time out of the enclosing executor).
invokeWithTimeoutWithNoExecutor(tm, instance, parameterValues, testResult, hookable);
} else {
invokeWithTimeoutWithNewExecutor(tm, instance, parameterValues, testResult, hookable);
}
}
private static void cleanInterruptStatus() {
if (Thread.currentThread().isInterrupted()) {
Thread.interrupted();
}
}
private static void invokeWithTimeoutWithNoExecutor(
ITestNGMethod tm,
Object instance,
Object[] parameterValues,
ITestResult testResult,
IHookable hookable) {
InvokeMethodRunnable imr =
new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult);
long startTime = System.currentTimeMillis();
long realTimeOut = MethodHelper.calculateTimeOut(tm);
boolean notTimedout = true;
AtomicBoolean finished = new AtomicBoolean(false);
AtomicBoolean interruptByThread = new AtomicBoolean(false);
Thread monitorThread = null;
try {
Thread currentThread = Thread.currentThread();
monitorThread = new Thread(() -> {
try {
TimeUnit.MILLISECONDS.sleep(realTimeOut);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (!finished.get()) {
interruptByThread.set(true);
currentThread.interrupt();
}
});
monitorThread.start();
imr.run();
notTimedout = System.currentTimeMillis() <= startTime + realTimeOut;
if (notTimedout) {
testResult.setStatus(ITestResult.SUCCESS);
} else {
ThreadTimeoutException exception =
new ThreadTimeoutException(
"Method "
+ tm.getQualifiedName()
+ "()"
+ " didn't finish within the time-out "
+ realTimeOut);
testResult.setThrowable(exception);
testResult.setStatus(ITestResult.FAILURE);
}
} catch (Exception ex) {
if (notTimedout && !interruptByThread.get()) {
Throwable e = ex.getCause();
if (e instanceof TestNGRuntimeException) {
e = e.getCause();
}
testResult.setThrowable(e);
} else {
ThreadTimeoutException exception =
new ThreadTimeoutException(
"Method "
+ tm.getQualifiedName()
+ "()"
+ " didn't finish within the time-out "
+ realTimeOut);
testResult.setThrowable(exception);
}
testResult.setStatus(ITestResult.FAILURE);
} finally {
finished.set(true);
if (monitorThread != null && monitorThread.isAlive()){
monitorThread.interrupt();
}
}
}
private static void invokeWithTimeoutWithNewExecutor(
ITestNGMethod tm,
Object instance,
Object[] parameterValues,
ITestResult testResult,
IHookable hookable)
throws InterruptedException, ThreadExecutionException {
ExecutorService exec = ThreadUtil.createExecutor(1, tm.getMethodName());
InvokeMethodRunnable imr =
new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult);
Future<Void> future = exec.submit(imr);
exec.shutdown();
long realTimeOut = MethodHelper.calculateTimeOut(tm);
boolean finished = exec.awaitTermination(realTimeOut, TimeUnit.MILLISECONDS);
if (!finished) {
exec.shutdownNow();
ThreadTimeoutException exception =
new ThreadTimeoutException(
"Method "
+ tm.getQualifiedName()
+ "() didn't finish within the time-out "
+ realTimeOut);
testResult.setThrowable(exception);
testResult.setStatus(ITestResult.FAILURE);
} else {
Utils.log(
"Invoker " + Thread.currentThread().hashCode(),
3,
"Method " + tm.getMethodName() + " completed within the time-out " + tm.getTimeOut());
// We don't need the result from the future but invoking get() on it
// will trigger the exception that was thrown, if any
try {
future.get();
} catch (ExecutionException e) {
throw new ThreadExecutionException(e.getCause());
}
testResult.setStatus(ITestResult.SUCCESS); // if no exception till here then SUCCESS.
}
}
protected static void invokeConfigurable(
final Object instance,
final Object[] parameters,
final IConfigurable configurableInstance,
final Method thisMethod,
final ITestResult testResult)
throws Throwable {
final Throwable[] error = new Throwable[1];
IConfigureCallBack callback =
new IConfigureCallBack() {
@Override
public void runConfigurationMethod(ITestResult tr) {
try {
invokeMethod(thisMethod, instance, parameters);
error[0] = null;
tr.setThrowable(null);
} catch (Throwable t) {
error[0] = t;
tr.setThrowable(t); // make Throwable available to IConfigurable
}
}
@Override
public Object[] getParameters() {
return parameters;
}
};
configurableInstance.run(callback, testResult);
if (error[0] != null) {
throw error[0];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.