answer
stringlengths 17
10.2M
|
|---|
package com.haulmont.cuba.gui.components;
import com.haulmont.chile.core.datatypes.Datatypes;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.chile.core.model.utils.InstanceUtils;
import com.haulmont.cuba.core.app.LockService;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.gui.ComponentsHelper;
import com.haulmont.cuba.gui.data.DataService;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.data.DsContext;
import com.haulmont.cuba.gui.data.impl.*;
import com.haulmont.cuba.security.entity.EntityOp;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
/**
* <p>$Id$</p>
*
* @author krivopustov
*/
public class EditorWindowDelegate extends WindowDelegate {
protected Entity item;
protected boolean justLocked;
protected boolean commitActionPerformed;
protected boolean commitAndCloseButtonExists;
protected Metadata metadata = AppBeans.get(Metadata.class);
protected Messages messages = AppBeans.get(Messages.class);
protected UserSessionSource userSessionSource = AppBeans.get(UserSessionSource.class);
protected LockService lockService = AppBeans.get(LockService.class);
public EditorWindowDelegate(Window window) {
super(window);
}
public Window wrapBy(Class<Window> wrapperClass) {
final Window.Editor editor = (Window.Editor) super.wrapBy(wrapperClass);
final Component commitAndCloseButton = ComponentsHelper.findComponent(editor, Window.Editor.WINDOW_COMMIT_AND_CLOSE);
if (commitAndCloseButton != null) {
commitAndCloseButtonExists = true;
this.window.addAction(
new AbstractAction(Window.Editor.WINDOW_COMMIT_AND_CLOSE) {
@Override
public String getCaption() {
return messages.getMainMessage("actions.OkClose");
}
public void actionPerform(Component component) {
editor.commitAndClose();
}
}
);
}
this.window.addAction(
new AbstractAction(Window.Editor.WINDOW_COMMIT) {
@Override
public String getCaption() {
return messages.getMainMessage("actions.Ok");
}
public void actionPerform(Component component) {
if (!commitAndCloseButtonExists) {
editor.commitAndClose();
} else {
if (editor.commit()) {
commitActionPerformed = true;
}
}
}
}
);
this.window.addAction(
new AbstractAction(Window.Editor.WINDOW_CLOSE) {
@Override
public String getCaption() {
return messages.getMainMessage("actions.Cancel");
}
public void actionPerform(Component component) {
editor.close(commitActionPerformed ? Window.COMMIT_ACTION_ID : getId());
}
}
);
return editor;
}
public Entity getItem() {
return item;
}
public void setItem(Entity item) {
final Datasource ds = getDatasource();
if (ds.getCommitMode().equals(Datasource.CommitMode.PARENT)) {
Datasource parentDs = ((DatasourceImpl) ds).getParent();
//We have to reload items in parent datasource because when item in child datasource is commited,
//item in parant datasource must already have all item fields loaded.
if (parentDs != null) {
Collection justChangedItems = new HashSet(((AbstractDatasource) parentDs).getItemsToCreate());
justChangedItems.addAll(((AbstractDatasource) parentDs).getItemsToUpdate());
DataService dataservice = ds.getDataService();
if ((parentDs instanceof CollectionDatasourceImpl) && !(justChangedItems.contains(item)) && ((CollectionDatasourceImpl) parentDs).containsItem(item)) {
item = dataservice.reload(item, ds.getView(), ds.getMetaClass());
((CollectionDatasourceImpl) parentDs).updateItem(item);
} else if ((parentDs instanceof LazyCollectionDatasource) && !(justChangedItems.contains(item)) && ((LazyCollectionDatasource) parentDs).containsItem(item)) {
item = dataservice.reload(item, ds.getView(), ds.getMetaClass());
((LazyCollectionDatasource) parentDs).updateItem(item);
} else if ((parentDs instanceof CollectionPropertyDatasourceImpl) && !(justChangedItems.contains(item)) && ((CollectionPropertyDatasourceImpl) parentDs).containsItem(item)) {
item = dataservice.reload(item, ds.getView(), ds.getMetaClass());
((CollectionPropertyDatasourceImpl) parentDs).replaceItem(item);
}
}
item = (Entity) InstanceUtils.copy(item);
} else {
if (!PersistenceHelper.isNew(item)) {
String useSecurityConstraintsParam = (String) window.getContext().getParams().get("useSecurityConstraints");
boolean useSecurityConstraints = !("false".equals(useSecurityConstraintsParam));
final DataService dataservice = ds.getDataService();
item = dataservice.reload(item, ds.getView(), ds.getMetaClass(), useSecurityConstraints);
}
}
if (item == null) {
throw new EntityAccessException();
}
if (PersistenceHelper.isNew(item)
&& !ds.getMetaClass().equals(item.getMetaClass()))
{
Entity newItem = ds.getDataService().newInstance(ds.getMetaClass());
InstanceUtils.copy(item, newItem);
item = newItem;
}
this.item = item;
//noinspection unchecked
ds.setItem(item);
((DatasourceImplementation) ds).setModified(false);
if (userSessionSource.getUserSession().isEntityOpPermitted(ds.getMetaClass(), EntityOp.UPDATE)) {
LockInfo lockInfo = lockService.lock(getMetaClassForLocking(ds).getName(), item.getId().toString());
if (lockInfo == null) {
justLocked = true;
} else if (!(lockInfo instanceof LockNotSupported)) {
window.getWindowManager().showNotification(
messages.getMainMessage("entityLocked.msg"),
String.format(messages.getMainMessage("entityLocked.desc"),
lockInfo.getUser().getLogin(),
Datatypes.get(Date.class).format(lockInfo.getSince(), userSessionSource.getLocale())
),
IFrame.NotificationType.HUMANIZED
);
Action action = window.getAction(Window.Editor.WINDOW_COMMIT);
if (action != null)
action.setEnabled(false);
action = window.getAction(Window.Editor.WINDOW_COMMIT_AND_CLOSE);
if (action != null)
action.setEnabled(false);
}
}
}
public void setParentDs(Datasource parentDs) {
Datasource ds = getDatasource();
((DatasourceImplementation) ds).setParent(parentDs);
}
public boolean commit(boolean close) {
if (wrapper instanceof AbstractEditor && !((AbstractEditor) wrapper).preCommit())
return false;
boolean committed;
final DsContext context = window.getDsContext();
if (context != null) {
committed = context.commit();
item = getDatasource().getItem();
} else {
if (item instanceof Datasource) {
final Datasource ds = (Datasource) item;
ds.commit();
} else {
DataService service = getDataService();
item = service.commit(item, null);
}
committed = true;
}
return !(wrapper instanceof AbstractEditor) || ((AbstractEditor) wrapper).postCommit(committed, close);
}
protected DataService getDataService() {
final DsContext context = window.getDsContext();
if (context == null) {
throw new UnsupportedOperationException();
} else {
return context.getDataService();
}
}
public boolean isLocked() {
return !justLocked;
}
public void releaseLock() {
if (justLocked) {
Datasource ds = getDatasource();
Entity entity = ds.getItem();
if (entity != null) {
lockService.unlock(getMetaClassForLocking(ds).getName(), entity.getId().toString());
}
}
}
protected MetaClass getMetaClassForLocking(Datasource ds) {
// lock original metaClass, if any, because by convention all the configuration is based on original entities
MetaClass metaClass = metadata.getExtendedEntities().getOriginalMetaClass(ds.getMetaClass());
if (metaClass == null) {
metaClass = ds.getMetaClass();
}
return metaClass;
}
}
|
package markehme.factionsplus.config;
import java.io.*;
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.nio.*;
import java.util.*;
import java.util.Map.Entry;
import markehme.factionsplus.*;
import java.util.Map.Entry;
import markehme.factionsplus.*;
import markehme.factionsplus.FactionsBridge.*;
import markehme.factionsplus.config.sections.*;
import markehme.factionsplus.config.yaml.*;
import markehme.factionsplus.events.*;
import markehme.factionsplus.extras.*;
import markehme.factionsplus.util.*;
import org.bukkit.*;
import org.bukkit.configuration.*;
import org.bukkit.configuration.file.*;
import org.bukkit.event.*;
import org.bukkit.plugin.*;
import org.yaml.snakeyaml.*;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import com.avaje.ebean.enhance.agent.*;
public abstract class Config {// not named Conf so to avoid conflicts with com.massivecraft.factions.Conf
// do not use Plugin.getDataFolder() here, it will NPE, unless you call it in/after onEnable()
public static final File folderBase = new File( "plugins" + File.separator + "FactionsPlus" );
public static final File folderWarps = new File( folderBase, "warps" );
public static final File folderJails = new File( folderBase, "jails" );
public static final File folderAnnouncements = new File( folderBase, "announcements" );
public static final File folderFRules = new File( folderBase, "frules" );
public static final File folderFBans = new File( folderBase, "fbans" );
public static final File fileDisableInWarzone = new File( folderBase, "disabled_in_warzone.txt" );
public static File templatesFile = new File( folderBase, "templates.yml" );
public static FileConfiguration templates;
// and it contains the defaults, so that they are no longer hardcoded in java code
public final static File fileConfig = new File( Config.folderBase, "config.yml" );
// never change this, it's yaml compatible:
public static final char DOT = '.';
// Begin Config Pointers
/**
* Caveats: YOU CAN rename all the fields, it won't affect config.yml because it uses the name inside the annotation above
* the field
* if you rename the realAlias inside the annotation then you'll have to be adding oldaliases to each of the section's fields
* (children) and to their child @Section 's fields and so on; unless it's not a @Section
* cantfix: adding old aliases for (sub)sections should not be doable, because I cannot decide which parent's oldAlias would
* apply to the child's alias when computing the dotted format of the child
*
* you may change order of these fields (or section's fields) but this won't have any effect if config.yml already existed,
* only if new one is about to be created<br>
* <br>
* fields could be named _something so that when you type Config._ and code completion with Ctrl+Space you can see only the
* relevant fields<br>
*/
@Section(
realAlias_neverDotted = "jails" )
public static final Section_Jails _jails = new Section_Jails();
@Section(
realAlias_neverDotted = "warps" )
public static final Section_Warps _warps = new Section_Warps();
@Section(
realAlias_neverDotted = "banning" )
public static final Section_Banning _banning = new Section_Banning();
@Section(
realAlias_neverDotted = "rules" )
public static final Section_Rules _rules = new Section_Rules();
@Section(
realAlias_neverDotted = "peaceful" )
public static final Section_Peaceful _peaceful = new Section_Peaceful();
@Section(
realAlias_neverDotted = "powerboosts" )
public static final Section_PowerBoosts _powerboosts = new Section_PowerBoosts();
@Section(
realAlias_neverDotted = "announce" )
public static final Section_Announce _announce = new Section_Announce();
@Section(
realAlias_neverDotted = "economy" )
public static final Section_Economy _economy = new Section_Economy();
@Section(
comments = {
"some comment here, if any", "second line of comment"
}, realAlias_neverDotted = "Teleports" )
public static final Section_Teleports _teleports = new Section_Teleports();
@Section(
realAlias_neverDotted = "extras" )
public final static Section_Extras _extras = new Section_Extras();
@Option(
realAlias_inNonDottedFormat = "DoNotChangeMe" )
// this is now useless, FIXME: remove this field, OR rename and increment it every time something changes in the config ie.
// coder adds new options or removes or changes/renames config options but not when just changes their values (id: value)
public static final _int doNotChangeMe = new _int( 11 );
// the root class that contains the @Section and @Options to scan for
private static final Class configClass = Config.class;
// End Config
private static File currentFolder_OnPluginClassInit;
private static File currentFolder_OnEnable = null;
private static boolean inited = false;
private static boolean loaded= false;
/**
* call this one time onEnable() never on onLoad() due to its evilness;)<br>
*/
public final static void init() {
assert !isLoaded();
setInited( false );
boolean failed = false;
// try {
if ( Q.isInconsistencyFileBug() ) {
throw FactionsPlusPlugin.bailOut( "Please do not have `user.dir` property set, it will mess up so many things"
+ "(or did you use native functions to change current folder from the one that was on jvm startup?!)" );
}
if ( hasFileFieldsTrap() ) {
throw FactionsPlusPlugin.bailOut( "there is a coding trap which will likely cause unexpected behaviour "
+ "in places that use files, tell plugin author to fix" );
}
// first make sure the (hard)coded options are valid while at the same time build a list of all obsolete+new
// option
// names
Typeo.sanitize_AndUpdateClassMapping( configClass );
setInited( true);
}
/**
* make sure all the File fields in this class that are likely used somewhere else in constructors like new File(field,
* myfile);
* are non-empty to avoid 'myfile' being in root of drive instead of just current folder as expected<br>
* this would cause some evil inconsistencies if any of those fields would resolve to empty paths<br>
*/
private static boolean hasFileFieldsTrap() {
Class classToCheckFor_FileFields = Config.class;
Field[] allFields = classToCheckFor_FileFields.getFields();
for ( Field field : allFields ) {
if ( File.class.equals( field.getType() ) ) {
// got one File field to check
try {
File instance = (File)field.get( classToCheckFor_FileFields );
if ( instance.getPath().isEmpty() ) {
// oops, found one, to avoid traps where you expect new File( instance, yourfile);
// to have 'yourfile' in root folder of that drive ie. '\yourfile' instead of what you might
// expect "yourfile" to be just in current folder just like a new File(yourfile) would do
return true;
}
} catch ( IllegalArgumentException e ) {
Q.rethrow( e );
} catch ( IllegalAccessException e ) {
Q.rethrow( e );
}
}
}
return false;
}
/**
* called on plugin.onEnable() and every time you want the config to reload<br>
* aka reload all (well, config and templates)<br>
*/
public synchronized final static void reload() {
Config.setLoaded( false );// must be here to cause config to reload on every plugin(s) reload from console
Config.templates = null;
boolean failed = false;
try {
Config.ensureFoldersExist();
reloadConfig();
reloadTemplates();
// last:
Config.setLoaded( true );
// Create the event here
Event event = new FPConfigLoadedEvent();
// Call the event
// throw null;//this will be caught
Bukkit.getServer().getPluginManager().callEvent(event);
//exceptions from inside the hooked event cannot be caught here for they are not let thru
} catch ( Throwable t ) {
// FactionsPlus.warn("caught");
Q.rethrow( t );
} finally {
if ( failed ) {
FactionsPlus.instance.disableSelf();// must make sure we're disabled if something failed if not /plugins would
// show us green
// but mostly, for consistency's sake and stuff we couldn't think of/anticipate now
}
}
}
protected static void ensureFoldersExist() {
File dataF = FactionsPlus.instance.getDataFolder();
if ( !dataF.equals( folderBase ) ) {
throw FactionsPlusPlugin
.bailOut( "Base folder and dataFolder differ, this may not be intended and it may just be a possible bug in the code;"
+ "folderBase=" + folderBase + " dataFolder=" + dataF );
}
try {
addDir( Config.folderBase );
addDir( Config.folderWarps );
addDir( Config.folderJails );
addDir( Config.folderAnnouncements );
addDir( Config.folderFRules );
addDir( Config.folderFBans );
if ( !Config.fileDisableInWarzone.exists() ) {
Config.fileDisableInWarzone.createNewFile();
FactionsPlusPlugin.info( "Created file: " + Config.fileDisableInWarzone );
}
if ( !Config.templatesFile.exists() ) {
FactionsPlusTemplates.createTemplatesFile();
FactionsPlusPlugin.info( "Created file: " + Config.templatesFile );
}
} catch ( Exception e ) {
e.printStackTrace();
throw FactionsPlusPlugin.bailOut( "something failed when ensuring the folders exist" );
}
}
private static final void addDir( File dir ) {
if ( !dir.exists() ) {
if ( dir.getPath().isEmpty() ) {
throw FactionsPlusPlugin.bailOut( "bad coding, this should usually not trigger here, but earlier" );
}
FactionsPlusPlugin.info( "Added directory: " + dir );
dir.mkdirs();
}
}
private final static String bucketOfSpaces = new String( new char[WannabeYaml.maxLevelSpaces] ).replace( '\0', ' ' );
/**
* this works for yaml's .getValues(deep)
*
* @param level
* @param start
* @throws IOException
*/
private final static void parseWrite( int level, Map<String, Object> start ) throws IOException {
for ( Map.Entry<String, Object> entry : start.entrySet() ) {
Object val = entry.getValue();
String key = entry.getKey();
if ( level > 0 ) {
bw.write( bucketOfSpaces, 0, WannabeYaml.spacesPerLevel * level );
}
bw.write( key );
bw.write( WannabeYaml.IDVALUE_SEPARATOR );
if ( !( val instanceof MemorySection ) ) {
bw.write( " " + val );
bw.newLine();
} else {
bw.newLine();
parseWrite( level + 1, ( (MemorySection)val ).getValues( false ) );
}
}
}
private final static void appendSection( int level, WYSection root ) throws IOException {
assert Q.nn( root );
WYItem currentItem = root.getFirst();
while ( null != currentItem ) {
Class<? extends WYItem> cls = currentItem.getClass();
// System.out.println(currentItem+"!");
if ( level > 0 ) {
bw.write( bucketOfSpaces, 0, WannabeYaml.spacesPerLevel * level );
}
if ( currentItem instanceof WYRawButLeveledLine ) {
bw.write( ( (WYRawButLeveledLine)currentItem ).getRawButLeveledLine() );
bw.newLine();
} else {
if ( !( currentItem instanceof WY_IDBased ) ) {
throw FactionsPlus.bailOut( "impossible, coding bug detected" );
}
if ( WYIdentifier.class == cls ) {
WYIdentifier wid = ( (WYIdentifier)currentItem );
// System.out.println(wid.getInAbsoluteDottedForm(virtualRoot));
bw.write( wid.getId() );
bw.write( WannabeYaml.IDVALUE_SEPARATOR );
bw.write( WannabeYaml.space + wid.getValue() );
bw.newLine();
} else {
if ( WYSection.class == cls ) {
WYSection cs = (WYSection)currentItem;
bw.write( ( cs ).getId() + WannabeYaml.IDVALUE_SEPARATOR );
bw.newLine();
appendSection( level + 1, cs );// recurse
} else {
throw FactionsPlus.bailOut( "impossible, coding bug detected" );
}
}
}
currentItem = currentItem.getNext();
}
}
/**
* must be inside: synchronized ( mapField_to_ListOfWYIdentifier )<br>
* this parses the entire representation of the config.yml and marks duplicates and invalid configs<br>
*
* @param root
*/
private final static void parseOneTime_and_CheckForValids( WYSection root, String dottedParentSection ) {
assert Q.nn( root );
WYItem<COMetadata> currentItem = root.getFirst();
boolean isTopLevelSection = ( null == dottedParentSection ) || dottedParentSection.isEmpty();
while ( null != currentItem ) {
Class<? extends WYItem> cls = currentItem.getClass();
if ( WYSection.class == cls ) {
WYSection cs = (WYSection)currentItem;
// sections are not checked for having oldaliases mainly since they are part of the dotted form of a config
// options and thus
// are indirectly checked when config options(aka ids) are checked
String dotted = ( isTopLevelSection ? cs.getId() : dottedParentSection + Config.DOT + cs.getId() );
parseOneTime_and_CheckForValids( cs, dotted );// recurse
} else {
if ( WYIdentifier.class == cls ) {
WYIdentifier<COMetadata> wid = ( (WYIdentifier)currentItem );
String dotted = ( isTopLevelSection ? wid.getId() : dottedParentSection + Config.DOT + wid.getId() );
// String dotted = wid.getID_InAbsoluteDottedForm( virtualRoot );
// System.out.println( dotted );
Field foundAsField = Typeo.getField_correspondingTo_DottedFormat( dotted );
if ( null == foundAsField ) {
// System.out.println("noadd: "+dotted+" "+wid.getID_InAbsoluteDottedForm( virtualRoot ));
// done: invalid config option encountered in config.yml transforms into comment
// WYSection widsParent = wid.getParent();
// assert null ! it just wouldn't ever be null, else bad coding else where heh
COMetadata oldmd = wid.setMetadata( new CO_Invalid( wid, dotted ) );
assert null == oldmd : "should not already have metadata, else we failed somewhere else";
} else {
// System.out.println("add: "+dotted+" "+wid.getID_InAbsoluteDottedForm( virtualRoot ));
// keep track of this dotted+wid in a set for this field ie. field-> {dotted->wid}
WYIdentifier<COMetadata> prevWID = mapFieldToID.shyAddWIDToSet( dotted, wid, foundAsField );
if ( null != prevWID ) {// not added because there was this prev which already existed
// existed? then we found a duplicate between all of those that we parsed from .yml
// ie. same id occurred twice in the .yml
// Typeo.getDottedRealAliasOfField( foundAsField );
int activeLine = prevWID.getLineNumber();
COMetadata oldmd = wid.setMetadata( new CO_Duplicate( wid, dotted, prevWID ) );
assert null == oldmd : "should not already have metadata, else we failed somewhere else";
} else {
// this wid was new so we associate it with the field, the field was already associated with it
// above
wid.setMetadata( new CO_FieldPointer( foundAsField, wid ) );
}
}// end of else found
} else {// non id
assert ( currentItem instanceof WYRawButLeveledLine );
// ignore raw lines like comments or empty lines, for now
}
}// else
currentItem = currentItem.getNext();
}// inner while
}
private static BufferedWriter bw;
public final static void saveConfig() {
try {
// FIXME: actually meld the class options/values into the WYIdentifiers here in the represented yml file
// before you write virtualRoot
FileOutputStream fos = null;
OutputStreamWriter osw = null;
bw = null;
try {
//for tests:new File( Config.fileConfig.getParent(), "config2.yml" ) );
fos = new FileOutputStream( Config.fileConfig);
osw = new OutputStreamWriter( fos, Q.UTF8 );
bw = new BufferedWriter( osw );
// parseWrite( 0, config.getValues( false ) );
appendSection( 0, virtualRoot );
} catch ( IOException e ) {
Q.rethrow( e );
} finally {
if ( null != bw ) {
try {
bw.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
if ( null != osw ) {
try {
osw.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
if ( null != fos ) {
try {
fos.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
}
// for ( Map.Entry<String, Object> entry : config.getValues( true).entrySet() ) {
// Object val = entry.getValue();
// if ( !( val instanceof MemorySection ) ) {//ignore sections, parse only "var: value" tuples else it won't carry
// over
// String key = entry.getKey();
// root.put(key,val);
// }else {
// MemorySection msVal=(MemorySection)val;
// msVal.getValues( true );
// DumperOptions opt = new DumperOptions();
// opt.setDefaultFlowStyle( DumperOptions.FlowStyle.BLOCK );
// final Yaml yaml = new Yaml( opt );
// FileOutputStream x = null;
// OutputStreamWriter y=null;
// try {
// x=new FileOutputStream( Config.fileConfig );
// y = new OutputStreamWriter( x, "UTF-8" );
// yaml.dump(root,y );
// } finally {
// if ( null != x ) {
// x.close();
// getConfig().save( Config.fileConfig );
} catch ( RethrownException e ) {
e.printStackTrace();
throw FactionsPlusPlugin.bailOut( "could not save config file: " + Config.fileConfig.getAbsolutePath() );
}
}
protected static WYSection virtualRoot = null;
// one to many
private static final HM1 mapFieldToID = new HM1();
public synchronized final static boolean reloadConfig() {
if ( Config.fileConfig.exists() ) {
if ( !Config.fileConfig.isFile() ) {
throw FactionsPlusPlugin.bailOut( "While '" + Config.fileConfig.getAbsolutePath()
+ "' exists, it is not a file!" );
}
}else {
//FIXME: evil hack, creating empty file and allowing the following code(which is meant just for when file is not empty) to actually fill it up
// x: what to do when config doesn't exit, probably just saveConfig() or fill up virtualRoot
// will have to fill the root with the fields and their comments
// throw FactionsPlus.bailOut( "inexistent config" );
try {
Config.fileConfig.createNewFile();
} catch ( IOException e ) {
FactionsPlus.bailOut(e, "Cannot create config file "+Config.fileConfig.getAbsolutePath() );
}
// virtualRoot=createWYRootFromFields();
}
// config file exists
try {
// now read the existing config
virtualRoot = WannabeYaml.read( fileConfig );
// now check to see if we have any old config options or invalid ones in the config
// remove invalids (move them to config_invalids.yml and carry over the old config values to the new ones, then
// remove old
// but only if new values are not already set
synchronized ( mapFieldToID ) {
synchronized ( Typeo.lock1 ) {
mapFieldToID.clear();
parseOneTime_and_CheckForValids( virtualRoot, null );
// FIXME: still have to make sure the fields have their comments above them!!!!!!!!!!!!!!!!!!
parseSecondTime_and_sortOverrides( virtualRoot );// from mapField_to_ListOfWYIdentifier
// now we need to use mapField_to_ListOfWYIdentifier to see which values (first in list) will have effect
// and notify admin on console only if the below values which were overridden have had a different value
// coalesceOverrides( virtualRoot );
// addMissingFieldsToConfig( virtualRoot );
// cleanram: when done:
mapFieldToID.clear();// free up memory for gc
}// sync
}
} catch ( IOException e ) {
// e.printStackTrace();
throw FactionsPlusPlugin.bailOut(e, "failed to load existing config file '" + Config.fileConfig.getAbsolutePath()
+ "'" );
}
applyChanges();
saveConfig();
//bechmarked: 274339 lines in an 11.6MB config.yml file at under 5 seconds with 300 info/warns shown on console
//that yielded a 15.6 MB file which on f reloadfp was parsed w/o info/warns in under 570ms
// 2.3 seconds if all info/warn are suppressed
//last:
if (encountered>SKIP_AFTER_ENCOUNTERED) {
FactionsPlus.warn( "Skipped "+ChatColor.RED+(encountered-SKIP_AFTER_ENCOUNTERED)+ChatColor.RESET
+" more messages due to being over the limit of "+SKIP_AFTER_ENCOUNTERED );
}
encountered=0;
virtualRoot=null;//to allow gc to reclaim this memory, whenever
return true;
}
private static WYSection createWYRootFromFields() {
Q.ni();
return virtualRoot;
}
private static void applyChanges() {
virtualRoot.recalculateLineNumbers();
parseAndApplyChanges( virtualRoot );
// that will set lines as comments due to duplicates/invalid/overridden
// and most importantly will apply the values from the config into the Fields
}
private static void parseAndApplyChanges( WYSection root ) {// , String dottedParentSection) {
assert Q.nn( root );
WYItem<COMetadata> currentItem = root.getFirst();
// boolean isTopLevelSection = ( null == dottedParentSection ) || dottedParentSection.isEmpty();
while ( null != currentItem ) {
WYItem nextItem = currentItem.getNext();//this is because currentItem will change and have it's next not point to old next:)
Class<? extends WYItem> cls = currentItem.getClass();
if ( WYSection.class == cls ) {
WYSection cs = (WYSection)currentItem;
// String dotted = ( isTopLevelSection ? cs.getId() : dottedParentSection + Config.DOT + cs.getId() );
assert null == cs.getMetadata() : "this should not have metadata, unless we missed something";
parseAndApplyChanges( cs );// , dotted );// recurse
} else {
if ( WYIdentifier.class == cls ) {
WYIdentifier<COMetadata> wid = ( (WYIdentifier)currentItem );
// String dotted = ( isTopLevelSection ? wid.getId() : dottedParentSection + Config.DOT + wid.getId() );
COMetadata meta = wid.getMetadata();
if ( null != meta ) {
// ok this one has meta, ie. it's one of duplicate/invalid/overridden
meta.apply();
// if you need the applied/new item, the nextItem.getPrev() would be it
}
} else {// non id
assert ( currentItem instanceof WYRawButLeveledLine );
// ignore raw lines like comments or empty lines, for now
}
}// else
currentItem = nextItem;
}// while
}
private static void parseSecondTime_and_sortOverrides( WYSection vroot ) {
synchronized ( mapFieldToID ) {
synchronized ( Typeo.lock1 ) {
// parse all found config options in .yml , only those found! and sort the list for their overrides
// which means, we'll now know what option overrides which one if more than 1 was found in .yml for a specific
// config field
// realAlias if found in .yml always overrides any old aliases found, else if no realAlias found, then
// the top oldAliases override the bottom ones when looking at the @Option annotation
Field field = null;
// SetOfIDs pointerToLastFoundSet=null;//the last field which had a WYIdentifier connection to .yml
// Field pointerToLastFoundField=null;
// String pointerToLastDottedRealAliasOfFoundField=null;
// WYIdentifier<COMetadata> lastGoodOverriderWID = null;
for ( Iterator iterator = Typeo.orderedListOfFields.iterator(); iterator.hasNext(); ) {
field = (Field)iterator.next();
// Option anno = field.getAnnotation( Option.class );
String[] orderOfAliases = Typeo.getListOfOldAliases( field );
String dottedRealAlias = Typeo.getDottedRealAliasOfField( field );// anno.realAlias_inNonDottedFormat();
assert null != orderOfAliases;// due to the way annotation works
SetOfIDs aSet = mapFieldToID.get( field );
if ( null == aSet ) {
// this config option was not yet defined in .yml so it means we have to add it
// previousField
// TODO: make sure this field added has the comment above them, and if it's already there don't prepend
// it again
WYIdentifier x = putFieldValueInTheRightWYPlace( vroot, Typeo.getFieldValue( field ), dottedRealAlias );
assert null != x;
//these should always be shown, mainly because they cannot be THAT many to be requiring skipping
FactionsPlus.info( "Adding new config option\n`" +COMetadata.COLOR_FOR_NEW_OPTIONS_ADDED+ dottedRealAlias + ChatColor.RESET+"`" );
continue;
}
// else, the option was defined, so
// multiple names for it may have been found in the config, and we need to decide which one overrides which
// other one
// where noting that the realAlias always overrides the oldAliases if both are found
// find who is the overrider:
// assume from start it's realAlias, the overrider
String dottedOverrider = null;
WYIdentifier<COMetadata> overriderWID = aSet.get( dottedRealAlias );
if ( null == overriderWID ) {
//so there were some options but none was the real Alias!
// FactionsPlus.info( dottedRealAlias);
// for ( Entry<String, WYIdentifier<COMetadata>> string : aSet.entrySet() ) {
// System.out.println("!"+string.getKey()+" "+string.getValue().getID_InAbsoluteDottedForm(virtualRoot));
// the realAlias is not the overriding one, so we parse oldAliases to find the topmost found one to be
// our supreme overrider which means all others found are marked as overriden
for ( int i = 0; i < orderOfAliases.length; i++ ) {
overriderWID = aSet.get( orderOfAliases[i] );
if ( null != overriderWID ) {
dottedOverrider = orderOfAliases[i];
break;// for, because the first one we find, overrides all the below ones
}
}
assert ( null != overriderWID ) : "if the real alias wasn't in list, then at least "
+ "one oldalias that is not .equals to realAlias would've been found and set";
} else {
// the real alias overrides any of the old aliases
dottedOverrider = dottedRealAlias;
}
// so we have our overrider
// now we have to parse the aSet and mark all that are not overriderWID as overridden by overriderWID
assert ( null != overriderWID );
assert ( null != dottedOverrider );
// there is always 1 overrider
Set<Entry<String, WYIdentifier<COMetadata>>> iter = aSet.entrySet();
for ( Entry<String, WYIdentifier<COMetadata>> entry : iter ) {
WYIdentifier<COMetadata> wid = entry.getValue();
if ( overriderWID != wid ) {
// mark as overridden
String widDotted = entry.getKey();
COMetadata previousMD =
wid.setMetadata( new CO_Overridden( wid, widDotted, overriderWID, dottedOverrider ) );
// it has to have been associated with the field, if it has a prev metadata
assert ( CO_FieldPointer.class.isAssignableFrom( previousMD.getClass() ) ) : "this should be the only way"
+ "that the wid we got here had a previously associated metadata with it, aka it has to have the"
+ "pointer to the Field";
CO_FieldPointer fp = (CO_FieldPointer)previousMD;
Field pfield = fp.getField();
assert null != pfield;
assert pfield.equals( field ) : "should've been the same field, else code logic failed";
// boolean contained = iter.remove( entry );this won't work, ConcurrentModificationException
// assert contained;
}
}
assert !aSet.isEmpty();
aSet.clear();// cleaning some ram
assert null != overriderWID;
if (!dottedOverrider.equals(dottedRealAlias)) {
//IF the overrider is not the realAlias then we transform it to the real alias
@SuppressWarnings( "null" )
String valueToCarry = overriderWID.getValue();
WYIdentifier<COMetadata> old = overriderWID;
//this is gonna be tricky to replace and removing it's parentSections if they're empty
overriderWID=putFieldValueInTheRightWYPlace( vroot, valueToCarry, dottedRealAlias );
COMetadata previousMD = old.setMetadata( new CO_Upgraded( old, dottedOverrider, field, overriderWID, dottedRealAlias ) );
dottedOverrider=dottedRealAlias;
// it has to have been associated with the field, if it has a prev metadata
assert ( CO_FieldPointer.class.isAssignableFrom( previousMD.getClass() ) ) : "this should be the only way"
+ "that the wid we got here had a previously associated metadata with it, aka it has to have the"
+ "pointer to the Field";
CO_FieldPointer fp = (CO_FieldPointer)previousMD;
Field pfield = fp.getField();
assert null != pfield;
assert pfield.equals( field ) : "should've been the same field, else code logic failed";
// boolean contained = iter.remove( entry );this won't work, ConcurrentModificationException
// assert contained;
}
assert null != overriderWID;
assert Typeo.isValidAliasFormat( dottedOverrider );
aSet.put( dottedOverrider, overriderWID );
assert aSet.size() == 1;
//DONT: comment out any empty Sections before write, in #applyChanges(), because the commented
//dup/invalid/overridden ones will be orphaned and reader would not know who the parent was
}
}// sync2
}// sync1
}
private static WYIdentifier putFieldValueInTheRightWYPlace( WYSection vroot, String value, String dottedRealAlias ) {
assert Q.nn( vroot );
assert Q.nn( value );
assert Typeo.isValidAliasFormat( dottedRealAlias );
// FactionsPlus.info( "putFieldValueInTheRightWYPlace " + dottedRealAlias );
WYSection foundParentSection = parseCreateAndReturnParentSectionFor( vroot, dottedRealAlias );
assert null != foundParentSection : "impossible, it should've created and returned a parent even if it didn't exist";
int index = dottedRealAlias.lastIndexOf( Config.DOT );
if ( index >= 0 ) {// well not really 0
dottedRealAlias = dottedRealAlias.substring( 1 + index );
}
assert Typeo.isValidAliasFormat( dottedRealAlias ) : dottedRealAlias;
WYIdentifier leaf = new WYIdentifier<COMetadata>( 0, dottedRealAlias, value );
// leaf.setMetadata( metadata )
// XXX: new(unencountered) config options (in config.yml) are added as last in the subsection where the `id: value` is
// for now, ideally TODO: add new config options in the right place in the Fields order
foundParentSection.append( leaf );
// System.out.println( foundParentSection.getInAbsoluteDottedForm() );
return leaf;
}
/**
* attempts to create all parents for the passed ID
*
* @param root
* @param field
* @param dottedID
* ie. extras.lwc.disableSomething
* @return
*/
private static WYSection parseCreateAndReturnParentSectionFor( WYSection root, String dottedID ) {
assert Q.nn( root );
WYItem<COMetadata> currentItem = root.getFirst();
int index = dottedID.indexOf( Config.DOT );
if ( index < 0 ) {
// we're just at the id
return root;
}
// else not yet reached
String findCurrent = dottedID.substring( 0, index );
while ( null != currentItem ) {
Class<? extends WYItem> cls = currentItem.getClass();
if ( WYSection.class == cls ) {
WYSection cs = (WYSection)currentItem;
if ( findCurrent.equals( cs.getId() ) ) {
return parseCreateAndReturnParentSectionFor( cs, dottedID.substring( 1 + index ) );// recurse
}
} else {
if ( WYIdentifier.class == cls ) {
WYIdentifier<COMetadata> wid = ( (WYIdentifier)currentItem );
if ( findCurrent.equals( wid.getId() ) ) {
throw new RuntimeException(
"bad parameters for this method, because you searched for parent aka section, and we found it as an id" );
// return root;
}
} else {// non id
assert ( currentItem instanceof WYRawButLeveledLine );
// ignore raw lines like comments or empty lines, for now
}
}// else
currentItem = currentItem.getNext();
}// inner while
// if not found
// make parent section, without completing the line number (which will be recalculated later anyway)
WYSection<COMetadata> parent = new WYSection<COMetadata>( 0, findCurrent );
root.append( parent );
return parseCreateAndReturnParentSectionFor( parent, dottedID.substring( 1 + index ) );
}
public static boolean isInited() {
return inited;
}
private static void setInited( boolean nowState ) {
inited = nowState;
}
private static void setLoaded( boolean nowState ) {
loaded = nowState;
}
public static boolean isLoaded() {
return loaded;
}
public final synchronized static boolean reloadTemplates() {
if (!Config.isInited()) {
return false;
}else {
Config.templates = YamlConfiguration.loadConfiguration( Config.templatesFile );
return null != Config.templates;
}
}
public static void deInit() {
if (isInited()) {
if (isLoaded()) {
setLoaded( false );
}
setInited( false );
}
}
private static final int SKIP_AFTER_ENCOUNTERED=300;
private static int encountered=0;
//these are to be used only when reporting config options while parsing config.yml
protected static void info(String msg) {
encountered++;
if ( encountered <= SKIP_AFTER_ENCOUNTERED ) {
FactionsPlus.info( msg );
}
}
protected static void warn(String msg) {
encountered++;
if ( encountered <= SKIP_AFTER_ENCOUNTERED ) {
FactionsPlus.warn(msg);
}
}
}
|
package io.fisache.firebase_auth.ui.login;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.fisache.firebase_auth.R;
import io.fisache.firebase_auth.base.BaseActivity;
import io.fisache.firebase_auth.base.BaseApplication;
import io.fisache.firebase_auth.data.model.User;
import io.fisache.firebase_auth.ui.main.MainActivity;
public class LoginActivity extends BaseActivity {
public static final int REQUEST_SIGN_GOOGLE = 9001;
@Bind(R.id.btnGl)
Button btnGl;
@Bind(R.id.pbLoading)
ProgressBar pbLoading;
@Inject
LoginPresenter presenter;
@Inject
AlertDialog.Builder addAlertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
}
@Override
protected void onResume() {
super.onResume();
presenter.subscribe();
}
@Override
protected void onStop() {
super.onStop();
presenter.unsubscribe();
}
@Override
protected void setupActivityComponent() {
BaseApplication.get(this).getAppComponent()
.plus(new LoginActivityModule(this))
.inject(this);
}
@OnClick(R.id.btnGl)
public void onBtnLoginWithGoogle() {
Intent intent = presenter.loginWithGoogle();
startActivityForResult(intent, REQUEST_SIGN_GOOGLE);
}
public void showLoginFail() {
Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
}
public void showLoginSuccess(User user) {
MainActivity.startWithUser(this, user);
}
public void showLoading(boolean loading) {
pbLoading.setVisibility(loading ? View.VISIBLE : View.GONE);
}
public void showInsertUsername(final User user) {
addAlertDialog.setTitle("Insert your username");
addAlertDialog.setMessage("Be sure to enter");
final EditText etUsername = new EditText(this);
etUsername.setSingleLine();
addAlertDialog.setView(etUsername);
addAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String username = etUsername.getText().toString();
dialog.dismiss();
presenter.createUser(user, username);
}
});
addAlertDialog.show();
}
public void showExistUsername(User user, String username) {
Toast.makeText(this, "Exist username" + username, Toast.LENGTH_LONG).show();
showInsertUsername(user);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// google
if(requestCode == REQUEST_SIGN_GOOGLE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
presenter.getAuthWithGoogle(result);
}
}
}
|
package name.abuchen.portfolio.math;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.number.IsCloseTo.closeTo;
import static org.junit.Assert.assertThat;
import java.time.LocalDate;
import java.util.Arrays;
import name.abuchen.portfolio.math.Risk.Drawdown;
import name.abuchen.portfolio.math.Risk.Volatility;
import org.junit.Test;
public class RiskTest
{
private LocalDate[] getDates(int size)
{
LocalDate[] dates = new LocalDate[size];
for (int i = 0; i < size; i++)
dates[i] = LocalDate.of(2015, 1, i + 1);
return dates;
}
@Test
public void testDrawdown()
{
int size = 10;
LocalDate[] dates = getDates(size);
double[] values = new double[size];
for (int i = 0; i < size; i++)
values[i] = i;
Drawdown drawdown = new Drawdown(values, dates, 0);
// Every new value is a new peak, so there never is a drawdown and
// therefore the magnitude is 0
assertThat(drawdown.getMaxDrawdown(), is(0d));
// Drawdown duration is the longest duration between peaks. Every value
// is a peak, so 1 day is every time the duration. The fact that there
// is never a drawdown does not negate the duration
assertThat(drawdown.getMaxDrawdownDuration().getDays(), is(1l));
drawdown = new Drawdown(new double[] { 1, 1, -0.5, 1, 1, 2, 3, 4, 5, 6 }, dates, 0);
// the drawdown is from 2 to 0.5 which is 1.5 or 75% of 2
assertThat(drawdown.getMaxDrawdown(), is(0.75d));
// the first peak is the first 2. The second 2 is not a peak, the next
// peak is the 3, which is 5 days later
assertThat(drawdown.getMaxDrawdownDuration().getDays(), is(5l));
drawdown = new Drawdown(new double[] { 0, 0.1, 0.2, -1.4 }, getDates(4), 0);
// The drawdown is from 1.2 to -0.4 or 1.6, which is 4/3 from 1.2
assertThat(drawdown.getMaxDrawdown(), closeTo(4d / 3, 0.1e-10));
}
@Test(expected = IllegalArgumentException.class)
public void testDrawdownInputArgumentsLengthNotTheSame()
{
new Drawdown(new double[] { 0, 0.1, 0.2, -1.4 }, getDates(3), 0);
}
@Test(expected = IllegalArgumentException.class)
public void testDrawdownStartAtIllegalPosition()
{
new Drawdown(new double[] { 0, 0.1, 0.2, -1.4 }, getDates(4), 4);
}
@Test
public void testVolatility()
{
double[] delta = new double[] { 0.005, -1 / 300d, -0.005, 0.01, 0.01, -0.005 };
Volatility volatility = new Volatility(delta, index -> true);
// calculated reference values with excel
assertThat(volatility.getStandardDeviation(), closeTo(0.017736692475, 0.1e-10));
assertThat(volatility.getSemiDeviation(), closeTo(0.012188677034, 0.1e-10));
}
@Test
public void testVolatilityWithSkip()
{
double[] delta = new double[] { 0, 0.005, -1 / 300d, -0.005, 0.01, 0.01, -0.005 };
Volatility volatility = new Volatility(delta, index -> index > 0);
assertThat(volatility.getStandardDeviation(), closeTo(0.017736692475, 0.1e-10));
assertThat(volatility.getSemiDeviation(), closeTo(0.012188677034, 0.1e-10));
}
@Test
public void testVolatilityWithConstantReturns()
{
double[] returns = new double[20];
Arrays.fill(returns, 0.1);
Volatility volatility = new Volatility(returns, index -> true);
assertThat(volatility.getStandardDeviation(), closeTo(0d, 0.1e-10));
assertThat(volatility.getSemiDeviation(), closeTo(0d, 0.1e-10));
}
@Test
public void testVolatilityWithSingleValue()
{
double[] returns = new double[1];
Arrays.fill(returns, 0.1);
Volatility volatility = new Volatility(returns, index -> true);
assertThat(volatility.getStandardDeviation(), is(0d));
assertThat(volatility.getSemiDeviation(), is(0d));
}
}
|
package org.chromium.net;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;
import org.chromium.base.ActivityStatus;
public class NetworkChangeNotifierAutoDetect extends BroadcastReceiver
implements ActivityStatus.StateListener {
/** Queries the ConnectivityManager for information about the current connection. */
static class ConnectivityManagerDelegate {
private final ConnectivityManager mConnectivityManager;
ConnectivityManagerDelegate(Context context) {
mConnectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
// For testing.
ConnectivityManagerDelegate() {
// All the methods below should be overridden.
mConnectivityManager = null;
}
boolean activeNetworkExists() {
return mConnectivityManager.getActiveNetworkInfo() != null;
}
boolean isConnected() {
return mConnectivityManager.getActiveNetworkInfo().isConnected();
}
int getNetworkType() {
return mConnectivityManager.getActiveNetworkInfo().getType();
}
int getNetworkSubtype() {
return mConnectivityManager.getActiveNetworkInfo().getSubtype();
}
}
private static final String TAG = "NetworkChangeNotifierAutoDetect";
private final NetworkConnectivityIntentFilter mIntentFilter =
new NetworkConnectivityIntentFilter();
private final Observer mObserver;
private final Context mContext;
private ConnectivityManagerDelegate mConnectivityManagerDelegate;
private boolean mRegistered;
private int mConnectionType;
/**
* Observer notified on the UI thread whenever a new connection type was detected.
*/
public static interface Observer {
public void onConnectionTypeChanged(int newConnectionType);
}
public NetworkChangeNotifierAutoDetect(Observer observer, Context context) {
mObserver = observer;
mContext = context.getApplicationContext();
mConnectivityManagerDelegate = new ConnectivityManagerDelegate(context);
mConnectionType = getCurrentConnectionType();
ActivityStatus.registerStateListener(this);
}
/**
* Allows overriding the ConnectivityManagerDelegate for tests.
*/
void setConnectivityManagerDelegateForTests(ConnectivityManagerDelegate delegate) {
mConnectivityManagerDelegate = delegate;
}
public void destroy() {
unregisterReceiver();
}
/**
* Register a BroadcastReceiver in the given context.
*/
private void registerReceiver() {
if (!mRegistered) {
mRegistered = true;
mContext.registerReceiver(this, mIntentFilter);
}
}
/**
* Unregister the BroadcastReceiver in the given context.
*/
private void unregisterReceiver() {
if (mRegistered) {
mRegistered = false;
mContext.unregisterReceiver(this);
}
}
public int getCurrentConnectionType() {
// Track exactly what type of connection we have.
if (!mConnectivityManagerDelegate.activeNetworkExists() ||
!mConnectivityManagerDelegate.isConnected()) {
return NetworkChangeNotifier.CONNECTION_NONE;
}
switch (mConnectivityManagerDelegate.getNetworkType()) {
case ConnectivityManager.TYPE_ETHERNET:
return NetworkChangeNotifier.CONNECTION_ETHERNET;
case ConnectivityManager.TYPE_WIFI:
return NetworkChangeNotifier.CONNECTION_WIFI;
case ConnectivityManager.TYPE_WIMAX:
return NetworkChangeNotifier.CONNECTION_4G;
case ConnectivityManager.TYPE_MOBILE:
// Use information from TelephonyManager to classify the connection.
switch (mConnectivityManagerDelegate.getNetworkSubtype()) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return NetworkChangeNotifier.CONNECTION_2G;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return NetworkChangeNotifier.CONNECTION_3G;
case TelephonyManager.NETWORK_TYPE_LTE:
return NetworkChangeNotifier.CONNECTION_4G;
default:
return NetworkChangeNotifier.CONNECTION_UNKNOWN;
}
default:
return NetworkChangeNotifier.CONNECTION_UNKNOWN;
}
}
// BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent) {
connectionTypeChanged();
}
// ActivityStatus.StateListener
@Override
public void onActivityStateChange(int state) {
if (state == ActivityStatus.RESUMED) {
// Note that this also covers the case where the main activity is created. The CREATED
// event is always followed by the RESUMED event. This is a temporary "hack" until
// since its notification is deferred. This means that it can immediately follow a
// DESTROYED/STOPPED/... event which is problematic.
connectionTypeChanged();
registerReceiver();
} else if (state == ActivityStatus.PAUSED) {
unregisterReceiver();
}
}
private void connectionTypeChanged() {
int newConnectionType = getCurrentConnectionType();
if (newConnectionType == mConnectionType) return;
mConnectionType = newConnectionType;
Log.d(TAG, "Network connectivity changed, type is: " + mConnectionType);
mObserver.onConnectionTypeChanged(newConnectionType);
}
private static class NetworkConnectivityIntentFilter extends IntentFilter {
NetworkConnectivityIntentFilter() {
addAction(ConnectivityManager.CONNECTIVITY_ACTION);
}
}
}
|
package de.geeksfactory.opacclient.apis;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.geeksfactory.opacclient.NotReachableException;
import de.geeksfactory.opacclient.SSLSecurityException;
import de.geeksfactory.opacclient.apis.OpacApi.MultiStepResult.Status;
import de.geeksfactory.opacclient.i18n.StringProvider;
import de.geeksfactory.opacclient.networking.HttpUtils;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailledItem;
import de.geeksfactory.opacclient.objects.Filter;
import de.geeksfactory.opacclient.objects.Filter.Option;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.SearchRequestResult;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.objects.SearchResult.MediaType;
import de.geeksfactory.opacclient.searchfields.DropdownSearchField;
import de.geeksfactory.opacclient.searchfields.SearchField;
import de.geeksfactory.opacclient.searchfields.SearchQuery;
import de.geeksfactory.opacclient.searchfields.TextSearchField;
public class Adis extends BaseApi implements OpacApi {
protected static HashMap<String, MediaType> types = new HashMap<>();
protected static HashSet<String> ignoredFieldNames = new HashSet<>();
static {
types.put("Buch", MediaType.BOOK);
types.put("Band", MediaType.BOOK);
types.put("DVD-ROM", MediaType.CD_SOFTWARE);
types.put("CD-ROM", MediaType.CD_SOFTWARE);
types.put("Medienkombination", MediaType.PACKAGE);
types.put("DVD-Video", MediaType.DVD);
types.put("Noten", MediaType.SCORE_MUSIC);
types.put("Konsolenspiel", MediaType.GAME_CONSOLE);
types.put("CD", MediaType.CD);
types.put("Zeitschrift", MediaType.MAGAZINE);
types.put("Zeitschriftenheft", MediaType.MAGAZINE);
types.put("Zeitung", MediaType.NEWSPAPER);
types.put("Beitrag E-Book", MediaType.EBOOK);
types.put("Elektronische Ressource", MediaType.EBOOK);
types.put("E-Book", MediaType.EBOOK);
types.put("Karte", MediaType.MAP);
// TODO: The following fields from Berlin make no sense and don't work
// when they are displayed alone.
// We can only include them if we automatically deselect the "Verbund"
// checkbox
// when one of these dropdowns has a value other than "".
ignoredFieldNames.add("oder Bezirk");
ignoredFieldNames.add("oder Bibliothek");
}
protected String opac_url = "";
protected JSONObject data;
protected Library library;
protected int s_requestCount = 0;
protected String s_service;
protected String s_sid;
protected String s_exts;
protected String s_alink;
protected List<NameValuePair> s_pageform;
protected int s_lastpage;
protected Document s_reusedoc;
protected boolean s_accountcalled;
public static Map<String, List<String>> getQueryParams(String url) {
try {
Map<String, List<String>> params = new HashMap<>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String[] pair = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<>();
params.put(key, values);
}
values.add(value);
}
}
return params;
} catch (UnsupportedEncodingException ex) {
throw new AssertionError(ex);
}
}
public Document htmlGet(String url) throws
IOException {
if (!url.contains("requestCount")) {
url = url + (url.contains("?") ? "&" : "?") + "requestCount="
+ s_requestCount;
}
HttpGet httpget = new HttpGet(cleanUrl(url));
HttpResponse response;
try {
response = http_client.execute(httpget);
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
throw new SSLSecurityException();
} catch (javax.net.ssl.SSLException e) {
// Can be "Not trusted server certificate" or can be a
// aborted/interrupted handshake/connection
if (e.getMessage().contains("timed out")
|| e.getMessage().contains("reset by")) {
e.printStackTrace();
throw new NotReachableException();
} else {
throw new SSLSecurityException();
}
} catch (InterruptedIOException e) {
e.printStackTrace();
throw new NotReachableException();
} catch (IOException e) {
if (e.getMessage() != null && e.getMessage().contains("Request aborted")) {
e.printStackTrace();
throw new NotReachableException();
} else {
throw e;
}
}
if (response.getStatusLine().getStatusCode() >= 400) {
throw new NotReachableException();
}
String html = convertStreamToString(response.getEntity().getContent(),
getDefaultEncoding());
HttpUtils.consume(response.getEntity());
Document doc = Jsoup.parse(html);
Pattern patRequestCount = Pattern.compile("requestCount=([0-9]+)");
for (Element a : doc.select("a")) {
Matcher objid_matcher = patRequestCount.matcher(a.attr("href"));
if (objid_matcher.matches()) {
s_requestCount = Integer.parseInt(objid_matcher.group(1));
}
}
doc.setBaseUri(url);
return doc;
}
public Document htmlPost(String url, List<NameValuePair> data)
throws IOException {
HttpPost httppost = new HttpPost(cleanUrl(url));
boolean rcf = false;
for (NameValuePair nv : data) {
if (nv.getName().equals("requestCount")) {
rcf = true;
break;
}
}
if (!rcf) {
data.add(new BasicNameValuePair("requestCount", s_requestCount + ""));
}
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response;
try {
response = http_client.execute(httppost);
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
throw new SSLSecurityException();
} catch (javax.net.ssl.SSLException e) {
// Can be "Not trusted server certificate" or can be a
// aborted/interrupted handshake/connection
if (e.getMessage().contains("timed out")
|| e.getMessage().contains("reset by")) {
e.printStackTrace();
throw new NotReachableException();
} else {
throw new SSLSecurityException();
}
} catch (InterruptedIOException e) {
e.printStackTrace();
throw new NotReachableException();
} catch (IOException e) {
if (e.getMessage() != null && e.getMessage().contains("Request aborted")) {
e.printStackTrace();
throw new NotReachableException();
} else {
throw e;
}
}
if (response.getStatusLine().getStatusCode() >= 400) {
throw new NotReachableException();
}
String html = convertStreamToString(response.getEntity().getContent(),
getDefaultEncoding());
HttpUtils.consume(response.getEntity());
Document doc = Jsoup.parse(html);
Pattern patRequestCount = Pattern
.compile(".*requestCount=([0-9]+)[^0-9].*");
for (Element a : doc.select("a")) {
Matcher objid_matcher = patRequestCount.matcher(a.attr("href"));
if (objid_matcher.matches()) {
s_requestCount = Integer.parseInt(objid_matcher.group(1));
}
}
doc.setBaseUri(url);
return doc;
}
@Override
public void start() throws IOException {
s_accountcalled = false;
try {
Document doc = htmlGet(opac_url + "?"
+ data.getString("startparams"));
Pattern padSid = Pattern
.compile(".*;jsessionid=([0-9A-Fa-f]+)[^0-9A-Fa-f].*");
for (Element navitem : doc.select("#unav li a")) {
if (navitem.attr("href").contains("service=")) {
s_service = getQueryParams(navitem.attr("href")).get(
"service").get(0);
}
if (navitem.text().contains("Erweiterte Suche")) {
s_exts = getQueryParams(navitem.attr("href")).get("sp")
.get(0);
}
Matcher objid_matcher = padSid.matcher(navitem.attr("href"));
if (objid_matcher.matches()) {
s_sid = objid_matcher.group(1);
}
}
if (s_exts == null) {
s_exts = "SS6";
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
super.start();
}
@Override
protected String getDefaultEncoding() {
return "UTF-8";
}
@Override
public SearchRequestResult search(List<SearchQuery> queries)
throws IOException, OpacErrorException {
start();
// TODO: There are also libraries with a different search form,
// s_exts=SS2 instead of s_exts=SS6
// e.g. munich. Treat them differently!
Document doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service="
+ s_service + "&sp=" + s_exts);
int cnt = 0;
List<NameValuePair> nvpairs = new ArrayList<>();
for (SearchQuery query : queries) {
if (!query.getValue().equals("")) {
if (query.getSearchField() instanceof DropdownSearchField) {
doc.select("select#" + query.getKey())
.val(query.getValue());
continue;
}
cnt++;
if (s_exts.equals("SS2")
|| (query.getSearchField().getData() != null && !query
.getSearchField().getData()
.optBoolean("selectable", true))) {
doc.select("input#" + query.getKey()).val(query.getValue());
} else {
doc.select("select#SUCH01_" + cnt).val(query.getKey());
doc.select("input#FELD01_" + cnt).val(query.getValue());
}
if (cnt > 4) {
throw new OpacErrorException(
stringProvider.getQuantityString(
StringProvider.LIMITED_NUM_OF_CRITERIA, 4, 4));
}
}
}
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
nvpairs.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
nvpairs.add(new BasicNameValuePair("$Toolbar_0.x", "1"));
nvpairs.add(new BasicNameValuePair("$Toolbar_0.y", "1"));
if (cnt == 0) {
throw new OpacErrorException(
stringProvider.getString(StringProvider.NO_CRITERIA_INPUT));
}
Document docresults = htmlPost(opac_url + ";jsessionid=" + s_sid,
nvpairs);
return parse_search(docresults, 1);
}
private SearchRequestResult parse_search(Document doc, int page)
throws OpacErrorException {
if (doc.select(".message h1").size() > 0
&& doc.select("#right #R06").size() == 0) {
throw new OpacErrorException(doc.select(".message h1").text());
}
if (doc.select("#OPACLI").text().contains("nicht gefunden")) {
throw new OpacErrorException(
stringProvider.getString(StringProvider.NO_RESULTS));
}
int total_result_count = -1;
List<SearchResult> results = new ArrayList<>();
if (doc.select("#right #R06").size() > 0) {
Pattern patNum = Pattern
.compile(".*Treffer: .* von ([0-9]+)[^0-9]*");
Matcher matcher = patNum.matcher(doc.select("#right #R06").text()
.trim());
if (matcher.matches()) {
total_result_count = Integer.parseInt(matcher.group(1));
}
}
if (doc.select("#right #R03").size() == 1
&& doc.select("#right #R03").text().trim()
.endsWith("Treffer: 1")) {
s_reusedoc = doc;
throw new OpacErrorException("is_a_redirect");
}
Pattern patId = Pattern
.compile("javascript:.*htmlOnLink\\('([0-9A-Za-z]+)'\\)");
for (Element tr : doc.select("table.rTable_table tbody tr")) {
SearchResult res = new SearchResult();
res.setInnerhtml(tr.select(".rTable_td_text a").first().html());
res.setNr(Integer.parseInt(tr.child(0).text().trim()));
Matcher matcher = patId.matcher(tr.select(".rTable_td_text a")
.first().attr("href"));
if (matcher.matches()) {
res.setId(matcher.group(1));
}
String typetext = tr.select(".rTable_td_img img").first()
.attr("title");
if (types.containsKey(typetext)) {
res.setType(types.get(typetext));
} else if (typetext.contains("+")
&& types.containsKey(typetext.split("\\+")[0].trim())) {
res.setType(types.get(typetext.split("\\+")[0].trim()));
}
results.add(res);
}
s_pageform = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
s_pageform.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
s_lastpage = page;
return new SearchRequestResult(results, total_result_count, page);
}
@Override
public void init(Library library) {
super.init(library);
this.library = library;
this.data = library.getData();
try {
this.opac_url = data.getString("baseurl");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
@Override
public SearchRequestResult filterResults(Filter filter, Option option)
throws IOException {
throw new UnsupportedOperationException();
}
@Override
public SearchRequestResult searchGetPage(int page) throws IOException,
OpacErrorException {
SearchRequestResult res = null;
while (page != s_lastpage) {
List<NameValuePair> nvpairs = s_pageform;
int i = 0;
List<Integer> indexes = new ArrayList<>();
for (NameValuePair np : nvpairs) {
if (np.getName().contains("$Toolbar_")) {
indexes.add(i);
}
i++;
}
for (int j = indexes.size() - 1; j >= 0; j
nvpairs.remove((int) indexes.get(j));
}
int p;
if (page > s_lastpage) {
nvpairs.add(new BasicNameValuePair("$Toolbar_5.x", "1"));
nvpairs.add(new BasicNameValuePair("$Toolbar_5.y", "1"));
p = s_lastpage + 1;
} else {
nvpairs.add(new BasicNameValuePair("$Toolbar_4.x", "1"));
nvpairs.add(new BasicNameValuePair("$Toolbar_4.y", "1"));
p = s_lastpage - 1;
}
Document docresults = htmlPost(opac_url + ";jsessionid=" + s_sid,
nvpairs);
res = parse_search(docresults, p);
}
return res;
}
@Override
public DetailledItem getResultById(String id, String homebranch)
throws IOException, OpacErrorException {
Document doc;
List<NameValuePair> nvpairs;
if (id == null && s_reusedoc != null) {
doc = s_reusedoc;
} else {
nvpairs = s_pageform;
int i = 0;
List<Integer> indexes = new ArrayList<>();
for (NameValuePair np : nvpairs) {
if (np.getName().contains("$Toolbar_")
|| np.getName().contains("selected")) {
indexes.add(i);
}
i++;
}
for (int j = indexes.size() - 1; j >= 0; j
nvpairs.remove((int) indexes.get(j));
}
nvpairs.add(new BasicNameValuePair("selected", "ZTEXT " + id));
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs);
List<NameValuePair> form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))
&& !"selected".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
form.add(new BasicNameValuePair("selected", "ZTEXT " + id));
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
// Yep, two times.
}
DetailledItem res = new DetailledItem();
if (doc.select("#R001 img").size() == 1) {
res.setCover(doc.select("#R001 img").first().absUrl("src"));
}
for (Element tr : doc.select("#R06 .aDISListe table tbody tr")) {
if (tr.children().size() < 2) {
continue;
}
String title = tr.child(0).text().trim();
String value = tr.child(1).text().trim();
if (value.contains("hier klicken") || value.startsWith("zur ") ||
title.contains("URL")) {
res.addDetail(new Detail(title, tr.child(1).select("a").first().absUrl("href")));
} else {
res.addDetail(new Detail(title, value));
}
if (title.contains("Titel") && res.getTitle() == null) {
res.setTitle(value.split("[:/;]")[0].trim());
}
}
if (doc.select("input[value*=Reservieren], input[value*=Vormerken]")
.size() > 0 && id != null) {
res.setReservable(true);
res.setReservation_info(id);
}
Map<Integer, String> colmap = new HashMap<>();
int i = 0;
for (Element th : doc.select("#R08 table.rTable_table thead tr th")) {
String head = th.text().trim();
if (head.contains("Bibliothek")) {
colmap.put(i, DetailledItem.KEY_COPY_BRANCH);
} else if (head.contains("Standort")) {
colmap.put(i, DetailledItem.KEY_COPY_LOCATION);
} else if (head.contains("Signatur")) {
colmap.put(i, DetailledItem.KEY_COPY_SHELFMARK);
} else if (head.contains("Status") || head.contains("Hinweis")
|| head.matches(".*Verf.+gbarkeit.*")) {
colmap.put(i, DetailledItem.KEY_COPY_STATUS);
}
i++;
}
for (Element tr : doc.select("#R08 table.rTable_table tbody tr")) {
Map<String, String> line = new HashMap<>();
for (Entry<Integer, String> entry : colmap.entrySet()) {
if (entry.getValue().equals(DetailledItem.KEY_COPY_STATUS)) {
String status = tr.child(entry.getKey()).text().trim();
if (status.contains(" am: ")) {
line.put(DetailledItem.KEY_COPY_STATUS,
status.split("-")[0]);
line.put(DetailledItem.KEY_COPY_RETURN,
status.split(": ")[1]);
} else {
line.put(DetailledItem.KEY_COPY_STATUS, status);
}
} else {
line.put(entry.getValue(), tr.child(entry.getKey()).text()
.trim());
}
}
res.addCopy(line);
}
// Reset
s_pageform = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
s_pageform.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
nvpairs = s_pageform;
nvpairs.add(new BasicNameValuePair("$Toolbar_1.x", "1"));
nvpairs.add(new BasicNameValuePair("$Toolbar_1.y", "1"));
parse_search(htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs), 1);
nvpairs = s_pageform;
nvpairs.add(new BasicNameValuePair("$Toolbar_3.x", "1"));
nvpairs.add(new BasicNameValuePair("$Toolbar_3.y", "1"));
parse_search(htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs), 1);
res.setId(""); // null would be overridden by the UI, because there _is_
// an id,< we just can not use it.
return res;
}
@Override
public DetailledItem getResult(int position) throws IOException,
OpacErrorException {
if (s_reusedoc != null) {
return getResultById(null, null);
}
throw new UnsupportedOperationException();
}
@Override
public ReservationResult reservation(DetailledItem item, Account account,
int useraction, String selection) throws IOException {
Document doc;
List<NameValuePair> nvpairs;
ReservationResult res = null;
if (selection != null && selection.equals("")) {
selection = null;
}
if (s_pageform == null) {
return new ReservationResult(Status.ERROR);
}
// Load details
nvpairs = s_pageform;
int i = 0;
List<Integer> indexes = new ArrayList<>();
for (NameValuePair np : nvpairs) {
if (np.getName().contains("$Toolbar_")
|| np.getName().contains("selected")) {
indexes.add(i);
}
i++;
}
for (int j = indexes.size() - 1; j >= 0; j
nvpairs.remove((int) indexes.get(j));
}
nvpairs.add(new BasicNameValuePair("selected", "ZTEXT "
+ item.getReservation_info()));
htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs);
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs); // Yep, two
// times.
List<NameValuePair> form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& (!"submit".equals(input.attr("type"))
|| input.val().contains("Reservieren") || input
.val().contains("Vormerken"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
if (doc.select(".message h1").size() > 0) {
String msg = doc.select(".message h1").text().trim();
res = new ReservationResult(MultiStepResult.Status.ERROR, msg);
form = new ArrayList<>();
for (Element input : doc.select("input")) {
if (!"image".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
} else {
try {
doc = handleLoginForm(doc, account);
} catch (OpacErrorException e1) {
return new ReservationResult(MultiStepResult.Status.ERROR,
e1.getMessage());
}
if (useraction == 0 && selection == null
&& doc.select("#AUSGAB_1").size() == 0) {
res = new ReservationResult(
MultiStepResult.Status.CONFIRMATION_NEEDED);
List<String[]> details = new ArrayList<>();
details.add(new String[]{doc.select("#F23").text()});
res.setDetails(details);
} else if (doc.select("#AUSGAB_1").size() > 0 && selection == null) {
List<Map<String, String>> sel = new ArrayList<>();
for (Element opt : doc.select("#AUSGAB_1 option")) {
if (opt.text().trim().length() > 0) {
Map<String, String> selopt = new HashMap<>();
selopt.put("key", opt.val());
selopt.put("value", opt.text());
sel.add(selopt);
}
}
res = new ReservationResult(
MultiStepResult.Status.SELECTION_NEEDED, doc.select(
"#F23").text());
res.setSelection(sel);
} else if (selection != null || doc.select("#AUSGAB_1").size() == 0) {
if (doc.select("#AUSGAB_1").size() > 0) {
doc.select("#AUSGAB_1").attr("value", selection);
}
if (doc.select(".message h1").size() > 0) {
String msg = doc.select(".message h1").text().trim();
form = new ArrayList<>();
for (Element input : doc.select("input")) {
if (!"image".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"),
input.attr("value")));
}
}
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
if (!msg.contains("Reservation ist erfolgt")) {
res = new ReservationResult(
MultiStepResult.Status.ERROR, msg);
} else {
res = new ReservationResult(MultiStepResult.Status.OK,
msg);
}
} else {
form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"),
input.attr("value")));
}
}
form.add(new BasicNameValuePair("textButton",
"Reservation abschicken"));
res = new ReservationResult(MultiStepResult.Status.OK);
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
if (doc.select(".message h1").size() > 0) {
String msg = doc.select(".message h1").text().trim();
form = new ArrayList<>();
for (Element input : doc.select("input")) {
if (!"image".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input
.attr("name"), input.attr("value")));
}
}
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
if (!msg.contains("Reservation ist erfolgt")) {
res = new ReservationResult(
MultiStepResult.Status.ERROR, msg);
} else {
res = new ReservationResult(
MultiStepResult.Status.OK, msg);
}
} else if (doc.select("#R01").text()
.contains("Informationen zu Ihrer Reservation")) {
String msg = doc.select("#OPACLI").text().trim();
form = new ArrayList<>();
for (Element input : doc.select("input")) {
if (!"image".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input
.attr("name"), input.attr("value")));
}
}
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
if (!msg.contains("Reservation ist erfolgt")) {
res = new ReservationResult(
MultiStepResult.Status.ERROR, msg);
} else {
res = new ReservationResult(
MultiStepResult.Status.OK, msg);
}
}
}
}
}
if (res == null
|| res.getStatus() == MultiStepResult.Status.SELECTION_NEEDED
|| res.getStatus() == MultiStepResult.Status.CONFIRMATION_NEEDED) {
form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
form.add(new BasicNameValuePair("textButton$0", "Abbrechen"));
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
}
// Reset
s_pageform = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
s_pageform.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
try {
nvpairs = s_pageform;
nvpairs.add(new BasicNameValuePair("$Toolbar_1.x", "1"));
nvpairs.add(new BasicNameValuePair("$Toolbar_1.y", "1"));
parse_search(htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs),
1);
nvpairs = s_pageform;
nvpairs.add(new BasicNameValuePair("$Toolbar_3.x", "1"));
nvpairs.add(new BasicNameValuePair("$Toolbar_3.y", "1"));
parse_search(htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs),
1);
} catch (OpacErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
@Override
public ProlongResult prolong(String media, Account account, int useraction,
String selection) throws IOException {
String alink = null;
Document doc;
if (s_accountcalled) {
alink = media.split("\\|")[1].replace("requestCount=", "fooo=");
} else {
start();
doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service="
+ s_service + "&sp=SBK");
try {
doc = handleLoginForm(doc, account);
} catch (OpacErrorException e) {
return new ProlongResult(Status.ERROR, e.getMessage());
}
for (Element tr : doc.select(".rTable_div tr")) {
if (tr.select("a").size() == 1) {
if (tr.select("a").first().absUrl("href")
.contains("sp=SZA")) {
alink = tr.select("a").first().absUrl("href");
}
}
}
if (alink == null) {
return new ProlongResult(Status.ERROR);
}
}
doc = htmlGet(alink);
List<NameValuePair> form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
for (Element tr : doc.select(".rTable_div tr")) {
if (tr.select("input").attr("name").equals(media.split("\\|")[0])
&& tr.select("input").hasAttr("disabled")) {
form.add(new BasicNameValuePair("$Toolbar_0.x", "1"));
form.add(new BasicNameValuePair("$Toolbar_0.y", "1"));
htmlPost(opac_url + ";jsessionid=" + s_sid, form);
return new ProlongResult(Status.ERROR, tr.child(4).text()
.trim());
}
}
form.add(new BasicNameValuePair(media.split("\\|")[0], "on"));
form.add(new BasicNameValuePair("textButton$1",
"Markierte Titel verlängern"));
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
form.add(new BasicNameValuePair("$Toolbar_0.x", "1"));
form.add(new BasicNameValuePair("$Toolbar_0.y", "1"));
htmlPost(opac_url + ";jsessionid=" + s_sid, form);
return new ProlongResult(Status.OK);
}
@Override
public ProlongAllResult prolongAll(Account account, int useraction,
String selection) throws IOException {
String alink = null;
Document doc;
if (s_accountcalled) {
alink = s_alink.replace("requestCount=", "fooo=");
} else {
start();
doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service="
+ s_service + "&sp=SBK");
try {
doc = handleLoginForm(doc, account);
} catch (OpacErrorException e) {
return new ProlongAllResult(Status.ERROR, e.getMessage());
}
for (Element tr : doc.select(".rTable_div tr")) {
if (tr.select("a").size() == 1) {
if (tr.select("a").first().absUrl("href")
.contains("sp=SZA")) {
alink = tr.select("a").first().absUrl("href");
}
}
}
if (alink == null) {
return new ProlongAllResult(Status.ERROR);
}
}
doc = htmlGet(alink);
List<NameValuePair> form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
if ("checkbox".equals(input.attr("type"))
&& !input.hasAttr("disabled")) {
form.add(new BasicNameValuePair(input.attr("name"), "on"));
}
}
form.add(new BasicNameValuePair("textButton$1",
"Markierte Titel verlängern"));
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
List<Map<String, String>> result = new ArrayList<>();
for (Element tr : doc.select(".rTable_div tbody tr")) {
Map<String, String> line = new HashMap<>();
line.put(ProlongAllResult.KEY_LINE_TITLE,
tr.child(3).text().split("[:/;]")[0].trim());
line.put(ProlongAllResult.KEY_LINE_NEW_RETURNDATE, tr.child(1)
.text());
line.put(ProlongAllResult.KEY_LINE_MESSAGE, tr.child(4).text());
result.add(line);
}
form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
form.add(new BasicNameValuePair("$Toolbar_0.x", "1"));
form.add(new BasicNameValuePair("$Toolbar_0.y", "1"));
htmlPost(opac_url + ";jsessionid=" + s_sid, form);
return new ProlongAllResult(Status.OK, result);
}
@Override
public CancelResult cancel(String media, Account account, int useraction,
String selection) throws IOException, OpacErrorException {
String rlink = null;
Document doc;
if (s_accountcalled) {
rlink = media.split("\\|")[1].replace("requestCount=", "fooo=");
} else {
start();
doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service="
+ s_service + "&sp=SBK");
try {
doc = handleLoginForm(doc, account);
} catch (OpacErrorException e) {
return new CancelResult(Status.ERROR, e.getMessage());
}
for (Element tr : doc.select(".rTable_div tr")) {
if (tr.select("a").size() == 1) {
if ((tr.text().contains("Reservationen") || tr.text().contains("Vormerkung"))
&& !tr.child(0).text().trim().equals("")
&& tr.select("a").first().attr("href")
.toUpperCase(Locale.GERMAN)
.contains("SP=SZM")) {
rlink = tr.select("a").first().absUrl("href");
}
}
}
if (rlink == null) {
return new CancelResult(Status.ERROR);
}
}
doc = htmlGet(rlink);
List<NameValuePair> form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
form.add(new BasicNameValuePair(media.split("\\|")[0], "on"));
form.add(new BasicNameValuePair("textButton$0",
"Markierte Titel löschen"));
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
form.add(new BasicNameValuePair("$Toolbar_0.x", "1"));
form.add(new BasicNameValuePair("$Toolbar_0.y", "1"));
htmlPost(opac_url + ";jsessionid=" + s_sid, form);
return new CancelResult(Status.OK);
}
@Override
public AccountData account(Account account) throws IOException,
JSONException, OpacErrorException {
start();
Document doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service="
+ s_service + "&sp=SBK");
doc = handleLoginForm(doc, account);
boolean split_title_author = true;
if (doc.head().html().contains("VOEBB")) {
split_title_author = false;
}
AccountData adata = new AccountData(account.getId());
for (Element tr : doc.select(".aDISListe tr")) {
if (tr.child(0).text().matches(".*F.+llige Geb.+hren.*")) {
adata.setPendingFees(tr.child(1).text().trim());
}
if (tr.child(0).text().matches(".*Ausweis g.+ltig bis.*")) {
adata.setValidUntil(tr.child(1).text().trim());
}
}
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
// Ausleihen
String alink = null;
int anum = 0;
List<Map<String, String>> lent = new ArrayList<>();
for (Element tr : doc.select(".rTable_div tr")) {
if (tr.select("a").size() == 1) {
if (tr.select("a").first().absUrl("href").contains("sp=SZA")) {
alink = tr.select("a").first().absUrl("href");
anum = Integer.parseInt(tr.child(0).text().trim());
}
}
}
if (alink != null) {
Document adoc = htmlGet(alink);
s_alink = alink;
List<NameValuePair> form = new ArrayList<>();
String prolongTest = null;
for (Element input : adoc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
if (input.attr("type").equals("checkbox")
&& !input.hasAttr("value")) {
input.val("on");
}
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
} else if (input.val().matches(".+verl.+ngerbar.+")) {
prolongTest = input.attr("name");
}
}
if (prolongTest != null) {
form.add(new BasicNameValuePair(prolongTest,
"Markierte Titel verlängerbar?"));
adoc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
}
for (Element tr : adoc.select(".rTable_div tbody tr")) {
Map<String, String> line = new HashMap<>();
String text = Jsoup.parse(
tr.child(3).html().replaceAll("(?i)<br[^>]*>", "
.text();
if (text.contains(" / ")) {
// Format "Titel / Autor #Sig#Nr", z.B. normale Ausleihe in Berlin
String[] split = text.split("[/
String title = split[0];
if (split_title_author) {
title = title.replaceFirst("([^:;\n]+)[:;\n](.*)$", "$1");
}
line.put(AccountData.KEY_LENT_TITLE, title.trim());
if (split.length > 1) {
line.put(AccountData.KEY_LENT_AUTHOR,
split[1].replaceFirst("([^:;\n]+)[:;\n](.*)$", "$1").trim());
}
} else {
// Format "Autor: Titel - Verlag - ISBN:... #Nummer", z.B. Fernleihe in Berlin
String[] split = text.split("
String[] aut_tit = split[0].split(": ");
line.put(AccountData.KEY_LENT_AUTHOR,
aut_tit[0].replaceFirst("([^:;\n]+)[:;\n](.*)$", "$1").trim());
if (aut_tit.length > 1) {
line.put(AccountData.KEY_LENT_TITLE,
aut_tit[1].replaceFirst("([^:;\n]+)[:;\n](.*)$", "$1").trim());
}
}
line.put(AccountData.KEY_LENT_DEADLINE, tr.child(1).text()
.trim());
try {
line.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String
.valueOf(sdf.parse(tr.child(1).text().trim())
.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
line.put(AccountData.KEY_LENT_BRANCH, tr.child(2).text().trim());
line.put(AccountData.KEY_LENT_LINK,
tr.select("input[type=checkbox]").attr("name") + "|"
+ alink);
// line.put(AccountData.KEY_LENT_RENEWABLE, tr.child(4).text()
// .matches(".*nicht verl.+ngerbar.*") ? "N" : "Y");
lent.add(line);
}
assert (lent.size() == anum);
form = new ArrayList<>();
for (Element input : adoc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
form.add(new BasicNameValuePair("$Toolbar_0.x", "1"));
form.add(new BasicNameValuePair("$Toolbar_0.y", "1"));
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
} else {
assert (anum == 0);
}
adata.setLent(lent);
List<String[]> rlinks = new ArrayList<>();
int rnum = 0;
List<Map<String, String>> res = new ArrayList<>();
for (Element tr : doc.select(".rTable_div tr")) {
if (tr.select("a").size() == 1) {
if ((tr.text().contains("Reservationen")
|| tr.text().contains("Vormerkung")
|| tr.text().contains("Fernleihbestellung")
|| tr.text().contains("Bereitstellung")
|| tr.text().contains("Bestellw")
|| tr.text().contains("Magazin"))
&& !tr.child(0).text().trim().equals("")) {
rlinks.add(new String[]{
tr.select("a").text(),
tr.select("a").first().absUrl("href"),
});
rnum += Integer.parseInt(tr.child(0).text().trim());
}
}
}
for (String[] rlink : rlinks) {
Document rdoc = htmlGet(rlink[1]);
boolean error = false;
boolean interlib = rdoc.html().contains("Ihre Fernleih-Bestellung");
boolean stacks = rdoc.html().contains("aus dem Magazin");
boolean provision = rdoc.html().contains("Ihre Bereitstellung");
Map<String, Integer> colmap = new HashMap<>();
colmap.put(AccountData.KEY_RESERVATION_TITLE, 2);
colmap.put(AccountData.KEY_RESERVATION_BRANCH, 1);
colmap.put(AccountData.KEY_RESERVATION_EXPIRE, 0);
int i = 0;
for (Element th : rdoc.select(".rTable_div thead tr th")) {
if (th.text().contains("Bis")) {
colmap.put(AccountData.KEY_RESERVATION_EXPIRE, i);
}
if (th.text().contains("Ausgabeort")) {
colmap.put(AccountData.KEY_RESERVATION_BRANCH, i);
}
if (th.text().contains("Titel")) {
colmap.put(AccountData.KEY_RESERVATION_TITLE, i);
}
i++;
}
for (Element tr : rdoc.select(".rTable_div tbody tr")) {
if (tr.children().size() >= 4) {
Map<String, String> line = new HashMap<>();
String text = tr.child(
colmap.get(AccountData.KEY_RESERVATION_TITLE))
.html();
text = Jsoup.parse(text.replaceAll("(?i)<br[^>]*>", ";"))
.text();
if (split_title_author) {
String[] split = text.split("[:/;\n]");
line.put(AccountData.KEY_RESERVATION_TITLE, split[0]
.replaceFirst("([^:;\n]+)[:;\n](.*)$", "$1").trim());
if (split.length > 1) {
line.put(AccountData.KEY_RESERVATION_AUTHOR, split[1]
.replaceFirst("([^:;\n]+)[:;\n](.*)$", "$1")
.trim());
}
} else {
line.put(AccountData.KEY_RESERVATION_TITLE, text);
}
String branch = tr.child(colmap.get(AccountData.KEY_RESERVATION_BRANCH))
.text().trim();
if (interlib) {
branch = stringProvider
.getFormattedString(StringProvider.INTERLIB_BRANCH, branch);
} else if (stacks) {
branch = stringProvider
.getFormattedString(StringProvider.STACKS_BRANCH, branch);
} else if (provision) {
branch = stringProvider
.getFormattedString(StringProvider.PROVISION_BRANCH, branch);
}
line.put(AccountData.KEY_RESERVATION_BRANCH, branch);
if (rlink[0].contains("Abholbereit")) {
// Abholbereite Bestellungen
line.put(AccountData.KEY_RESERVATION_READY, "bereit");
if (tr.child(0).text().trim().length() >= 10) {
line.put(
AccountData.KEY_RESERVATION_EXPIRE,
tr.child(
colmap.get(AccountData.KEY_RESERVATION_EXPIRE))
.text().trim().substring(0, 10));
}
} else {
// Nicht abholbereite
if (tr.select("input[type=checkbox]").size() > 0
&& (rlink[1].toUpperCase(Locale.GERMAN).contains(
"SP=SZM") || rlink[1].toUpperCase(
Locale.GERMAN).contains("SP=SZW"))) {
line.put(AccountData.KEY_RESERVATION_CANCEL, tr
.select("input[type=checkbox]")
.attr("name")
+ "|" + rlink[1]);
}
}
res.add(line);
} else {
// This is a strange bug where sometimes there is only three
// columns
error = true;
}
}
if (error) {
// Maybe we should send a bug report here, but using ACRA breaks
// the unit tests
adata.setWarning("Beim Abrufen der Reservationen ist ein Problem aufgetreten");
}
List<NameValuePair> form = new ArrayList<>();
for (Element input : rdoc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"submit".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
form.add(new BasicNameValuePair("$Toolbar_0.x", "1"));
form.add(new BasicNameValuePair("$Toolbar_0.y", "1"));
htmlPost(opac_url + ";jsessionid=" + s_sid, form);
}
assert (res.size() == rnum);
adata.setReservations(res);
return adata;
}
protected Document handleLoginForm(Document doc, Account account)
throws IOException, OpacErrorException {
if (doc.select("#LPASSW_1").size() == 0) {
return doc;
}
doc.select("#LPASSW_1").val(account.getPassword());
List<NameValuePair> form = new ArrayList<>();
for (Element input : doc.select("input, select")) {
if (!"image".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !input.attr("value").contains("vergessen")
&& !input.attr("value").contains("egistrier")
&& !"".equals(input.attr("name"))) {
if (input.attr("id").equals("L#AUSW_1")
|| input.attr("id").equals("IDENT_1")
|| input.attr("id").equals("LMATNR_1")) {
input.attr("value", account.getName());
}
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
if (doc.select(".message h1").size() > 0) {
String msg = doc.select(".message h1").text().trim();
form = new ArrayList<>();
for (Element input : doc.select("input")) {
if (!"image".equals(input.attr("type"))
&& !"checkbox".equals(input.attr("type"))
&& !"".equals(input.attr("name"))) {
form.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
}
doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form);
if (!msg.contains("Sie sind angemeldet")) {
throw new OpacErrorException(msg);
}
return doc;
} else {
return doc;
}
}
@Override
public List<SearchField> getSearchFields() throws IOException,
JSONException {
if (!initialised) {
start();
}
Document doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service="
+ s_service + "&sp=" + s_exts);
List<SearchField> fields = new ArrayList<>();
// dropdown to select which field you want to search in
for (Element opt : doc.select("#SUCH01_1 option")) {
TextSearchField field = new TextSearchField();
field.setId(opt.attr("value"));
field.setDisplayName(opt.text());
field.setHint("");
fields.add(field);
}
// Save data so that the search() function knows that this
// is not a selectable search field
JSONObject selectableData = new JSONObject();
selectableData.put("selectable", false);
for (Element row : doc.select("div[id~=F\\d+]")) {
if (row.select("input[type=text]").size() == 1
&& row.select("input, select").first().tagName()
.equals("input")) {
// A single text search field
Element input = row.select("input[type=text]").first();
TextSearchField field = new TextSearchField();
field.setId(input.attr("id"));
field.setDisplayName(row.select("label").first().text());
field.setHint("");
field.setData(selectableData);
fields.add(field);
} else if (row.select("select").size() == 1
&& row.select("input[type=text]").size() == 0) {
// Things like language, media type, etc.
Element select = row.select("select").first();
DropdownSearchField field = new DropdownSearchField();
field.setId(select.id());
field.setDisplayName(row.select("label").first().text());
List<Map<String, String>> values = new ArrayList<>();
for (Element opt : select.select("option")) {
Map<String, String> value = new HashMap<>();
value.put("key", opt.attr("value"));
value.put("value", opt.text());
values.add(value);
}
field.setDropdownValues(values);
fields.add(field);
} else if (row.select("select").size() == 0
&& row.select("input[type=text]").size() == 3
&& row.select("label").size() == 3) {
// Three text inputs.
// Year single/from/to or things like Band-/Heft-/Satznummer
String name1 = row.select("label").get(0).text();
String name2 = row.select("label").get(1).text();
String name3 = row.select("label").get(2).text();
Element input1 = row.select("input[type=text]").get(0);
Element input2 = row.select("input[type=text]").get(1);
Element input3 = row.select("input[type=text]").get(2);
if (name2.contains("von") && name3.contains("bis")) {
TextSearchField field1 = new TextSearchField();
field1.setId(input1.id());
field1.setDisplayName(name1);
field1.setHint("");
field1.setData(selectableData);
fields.add(field1);
TextSearchField field2 = new TextSearchField();
field2.setId(input2.id());
field2.setDisplayName(name2.replace("von", "").trim());
field2.setHint("von");
field2.setData(selectableData);
fields.add(field2);
TextSearchField field3 = new TextSearchField();
field3.setId(input3.id());
field3.setDisplayName(name3.replace("bis", "").trim());
field3.setHint("bis");
field3.setHalfWidth(true);
field3.setData(selectableData);
fields.add(field3);
} else {
TextSearchField field1 = new TextSearchField();
field1.setId(input1.id());
field1.setDisplayName(name1);
field1.setHint("");
field1.setData(selectableData);
fields.add(field1);
TextSearchField field2 = new TextSearchField();
field2.setId(input2.id());
field2.setDisplayName(name2);
field2.setHint("");
field2.setData(selectableData);
fields.add(field2);
TextSearchField field3 = new TextSearchField();
field3.setId(input3.id());
field3.setDisplayName(name3);
field3.setHint("");
field3.setData(selectableData);
fields.add(field3);
}
}
}
for (Iterator<SearchField> iterator = fields.iterator(); iterator
.hasNext(); ) {
SearchField field = iterator.next();
if (ignoredFieldNames.contains(field.getDisplayName())) {
iterator.remove();
}
}
return fields;
}
@Override
public boolean isAccountSupported(Library library) {
return true;
}
@Override
public boolean isAccountExtendable() {
return false;
}
@Override
public String getAccountExtendableInfo(Account account) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public String getShareUrl(String id, String title) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getSupportFlags() {
return SUPPORT_FLAG_ACCOUNT_PROLONG_ALL
| SUPPORT_FLAG_ENDLESS_SCROLLING;
}
@Override
public void checkAccountData(Account account) throws IOException,
JSONException, OpacErrorException {
start();
s_accountcalled = true;
Document doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service="
+ s_service + "&sp=SBK");
handleLoginForm(doc, account);
}
@Override
public void setLanguage(String language) {
// TODO Auto-generated method stub
}
@Override
public Set<String> getSupportedLanguages() throws IOException {
// TODO Auto-generated method stub
return null;
}
}
|
package org.eclipse.birt.report.engine.emitter.html;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.model.api.metadata.DimensionValue;
import org.eclipse.birt.report.model.metadata.Choice;
public class AttributeBuilder
{
/**
* Build the relative position of a component. This method is obsolete.
*/
public static String buildPos( DimensionType x, DimensionType y,
DimensionType width, DimensionType height )
{
StringBuffer content = new StringBuffer( );
if ( x != null || y != null )
{
content.append( "position: relative;" ); //$NON-NLS-1$
buildSize( content, HTMLTags.ATTR_LEFT, x );
buildSize( content, HTMLTags.ATTR_TOP, y );
}
buildSize( content, HTMLTags.ATTR_WIDTH, width );
buildSize( content, HTMLTags.ATTR_HEIGHT, height );
return content.toString( );
}
/**
* Output the style content to a given <code>StringBuffer</code> object.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param style
* The style object.
* @param emitter
* The <code>HTMLReportEmitter</code> object which provides
* resource manager and hyperlink builder objects for
* background-image property.
*/
public static void buildStyle( StringBuffer content, IStyle style,
HTMLReportEmitter emitter )
{
if ( style == null )
{
return;
}
buildFont( content, style );
buildText( content, style );
buildBox( content, style );
buildBackground( content, style, emitter );
buildPagedMedia( content, style );
buildVisual( content, style );
/*
* style.getNumberAlign(); style.getID(); style.getName();
*/
}
/**
* Builds the Visual style string.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param style
* The style object.
*/
private static void buildVisual( StringBuffer content, IStyle style )
{
// move display property from css file to html file
// buildProperty( content, "display", style.getDisplay( ) );
buildProperty( content, HTMLTags.ATTR_VERTICAL_ALIGN, style
.getVerticalAlign( ) ); //$NON-NLS-1$
buildProperty( content, HTMLTags.ATTR_LINE_HEIGHT, style
.getLineHeight( ) ); //$NON-NLS-1$
}
/**
* Build the PagedMedia style string.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param style
* The style object.
*/
private static void buildPagedMedia( StringBuffer content,
IStyle style )
{
buildProperty( content, HTMLTags.ATTR_ORPHANS, style.getOrphans( ) );
buildProperty( content, HTMLTags.ATTR_WIDOWS, style.getWidows( ) );
buildProperty( content, HTMLTags.ATTR_PAGE_BREAK_BEFORE, style
.getPageBreakBefore( ) );
buildProperty( content, HTMLTags.ATTR_PAGE_BREAK_AFTER, style
.getPageBreakAfter( ) );
buildProperty( content, HTMLTags.ATTR_PAGE_BREAK_INSIDE, style
.getPageBreakInside( ) );
}
/**
* Build the background style string.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param style
* The style object.
* @param emitter
* The <code>HTMLReportEmitter</code> object which provides
* resource manager and hyperlink builder objects.
*/
private static void buildBackground( StringBuffer content,
IStyle style, HTMLReportEmitter emitter )
{
buildProperty( content, HTMLTags.ATTR_COLOR, style.getColor( ) ); //$NON-NLS-1$
String color = style.getBackgroundColor( );
String image = style.getBackgroundImage( );
String repeat = style.getBackgroundRepeat( );
String attach = style.getBackgroundAttachment( );
String x = style.getBackgroundPositionX( );
String y = style.getBackgroundPositionY( );
if ( color == null && image == null && !"none".equalsIgnoreCase( image ) //$NON-NLS-1$
&& repeat == null && attach == null && x == null && y == null )
{
return;
}
content.append( " background:" ); //$NON-NLS-1$
addPropValue( content, color );
if(!"none".equalsIgnoreCase( image ) ) //$NON-NLS-1$
{
if ( image!=null )
{
image = HTMLBaseEmitter.handleStyleImage(image, emitter);
}
if(image!=null && image.length()>0)
{
addURLValue( content, image );
}
}
addPropValue( content, repeat );
addPropValue( content, attach );
addPropValue( content, x );
addPropValue( content, y );
content.append( ';' );
}
/**
* Build the Box style string.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param style
* The style object.
*/
private static void buildBox( StringBuffer content, IStyle style )
{
buildProperty( content, HTMLTags.ATTR_MARGIN_TOP, style.getMarginTop( ) );
buildProperty( content, HTMLTags.ATTR_MARGIN_RIGHT, style
.getMarginRight( ) );
buildProperty( content, HTMLTags.ATTR_MARGIN_BOTTOM, style
.getMarginBottom( ) );
buildProperty( content, HTMLTags.ATTR_MARGIN_LEFT, style
.getMarginLeft( ) );
buildProperty( content, HTMLTags.ATTR_PADDING_TOP, style
.getPaddingTop( ) );
buildProperty( content, HTMLTags.ATTR_PADDING_RIGHT, style
.getPaddingRight( ) );
buildProperty( content, HTMLTags.ATTR_PADDING_BOTTOM, style
.getPaddingBottom( ) );
buildProperty( content, HTMLTags.ATTR_PADDING_LEFT, style
.getPaddingLeft( ) );
buildBorder( content, HTMLTags.ATTR_BORDER_TOP, style
.getBorderTopWidth( ), style.getBorderTopStyle( ), style
.getBorderTopColor( ) );
buildBorder( content, HTMLTags.ATTR_BORDER_RIGHT, style
.getBorderRightWidth( ), style.getBorderRightStyle( ), style
.getBorderRightColor( ) );
buildBorder( content, HTMLTags.ATTR_BORDER_BOTTOM, style
.getBorderBottomWidth( ), style.getBorderBottomStyle( ), style
.getBorderBottomColor( ) );
buildBorder( content, HTMLTags.ATTR_BORDER_LEFT, style
.getBorderLeftWidth( ), style.getBorderLeftStyle( ), style
.getBorderLeftColor( ) );
}
/**
* Build the Text style string.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param style
* The style object.
*/
private static void buildText( StringBuffer content, IStyle style )
{
buildProperty( content, HTMLTags.ATTR_TEXT_INDENT, style
.getTextIndent( ) );
buildProperty( content, HTMLTags.ATTR_TEXT_ALIGN, style.getTextAlign( ) );
buildTextDecoration( content, style.getTextLineThrough( ), style
.getTextOverline( ), style.getTextUnderline( ) );
buildProperty( content, HTMLTags.ATTR_LETTER_SPACING, style
.getLetterSpacing( ) );
buildProperty( content, HTMLTags.ATTR_WORD_SPACING, style
.getWordSpacing( ) );
buildProperty( content, HTMLTags.ATTR_TEXT_TRANSFORM, style
.getTextTransform( ) );
buildProperty( content, HTMLTags.ATTR_WHITE_SPACE, style
.getWhiteSpace( ) );
}
/**
* Build Font style string.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param style
* The style object.
*/
private static void buildFont( StringBuffer content, IStyle style )
{
buildProperty( content, HTMLTags.ATTR_FONT_FAMILY, style
.getFontFamily( ) );
buildProperty( content, HTMLTags.ATTR_FONT_STYLE, style.getFontStyle( ) );
buildProperty( content, HTMLTags.ATTR_FONT_VARIANT, style
.getFontVariant( ) );
buildProperty( content, HTMLTags.ATTR_FONT_WEIGTH, style
.getFontWeight( ) );
buildProperty( content, HTMLTags.ATTR_FONT_SIZE, style.getFontSize( ) );
}
/**
* Build the Text-Decoration style string.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param linethrough
* The line-through value.
* @param underline
* The underline value.
* @param overline
* The overline value.
*/
private static void buildTextDecoration( StringBuffer content,
String linethrough, String underline, String overline )
{
int flag = 0;
if ( linethrough != null && !"none".equalsIgnoreCase( linethrough ) ) //$NON-NLS-1$
{
flag = 1; // linethrough
}
if ( underline != null && !"none".equalsIgnoreCase( underline ) ) //$NON-NLS-1$
{
flag |= 2; // underline
}
if ( overline != null && !"none".equalsIgnoreCase( overline ) ) //$NON-NLS-1$
{
flag |= 4; // overline
}
if ( flag > 0 )
{
content.append( " text-decoration:" ); //$NON-NLS-1$
if ( ( flag & 1 ) > 0 ) // linethrough
{
addPropValue( content, linethrough );
}
if ( ( flag & 2 ) > 0 ) // underline
{
addPropValue( content, underline );
}
if ( ( flag & 4 ) > 0 ) //overline
{
addPropValue( content, overline );
}
content.append( ';' );
}
}
/**
* Build the border string.
* <li>ignore all the border styles is style is null
* <li>CSS default border-color is the font-color, while BIRT is black
* <li>border-color is not inheritable.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param name
* The proerty name.
* @param width
* The border-width value.
* @param style
* The border-style value.
* @param color
* The border-color value
*/
private static void buildBorder( StringBuffer content, String name,
String width, String style, String color )
{
if ( style == null || style.length( ) <= 0 )
{
return;
}
addPropName( content, name );
addPropValue( content, width );
addPropValue( content, style );
addPropValue( content, color == null ? "black" : color ); //$NON-NLS-1$
content.append( ';' );
}
/**
* Build size style string say, "width: 10.0mm;".
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param name
* The property name
* @param value
* The values of the property
*/
public static void buildSize( StringBuffer content, String name,
DimensionType value )
{
if ( value != null )
{
addPropName( content, name );
addPropValue( content, value.toString( ) );
content.append( ';' );
}
}
/**
* Build the style property.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param name
* The name of the property
* @param value
* The values of the property
*/
private static void buildProperty( StringBuffer content, String name,
String value )
{
if ( value != null )
{
addPropName( content, name );
addPropValue( content, value );
content.append( ';' );
}
}
/**
* Build the style property.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param name
* The name of the property
* @param value
* The values of the property
*/
private static void buildProperty( StringBuffer content, String name,
DimensionValue value )
{
if ( value != null )
{
buildProperty( content, name, value.toString( ) );
}
}
/**
* Build the style property, this method is obsolete.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param name
* The name of the property
* @param value
* The values of the property
*/
private static void buildProperty( StringBuffer content, String name,
Choice value )
{
if ( value != null )
{
buildProperty( content, name, value.getName( ) );
}
}
/**
* Add property name to the Style string.
*
* @param content
* The StringBuffer to which the result should be output.
* @param name
* The property name.
*/
private static void addPropName( StringBuffer content, String name )
{
content.append( ' ' );
content.append( name );
content.append( ':' );
}
/**
* Add property value to the Style content.
*
* @param content -
* specifies the StringBuffer to which the result should be
* output
* @param value -
* specifies the values of the property
*/
private static void addPropValue( StringBuffer content, String value )
{
if ( value != null )
{
content.append( ' ' );
content.append( value );
}
}
/**
* Add URL property name to the Style content.
*
* @param content -
* specifies the StringBuffer to which the result should be
* output
* @param url -
* specifies the values of the property
*/
private static void addURLValue( StringBuffer content, String url )
{
if ( url == null )
{
return;
}
// escape the URL string
StringBuffer escapedUrl = null;
for ( int i = 0, max = url.length( ), delta = 0; i < max; i++ )
{
char c = url.charAt( i );
String replacement = null;
if ( c == '\\' )
{
replacement = "%5c"; //$NON-NLS-1$
}
else if ( c == '
{
replacement = "%23"; //$NON-NLS-1$
}
else if ( c == '%' )
{
replacement = "%25"; //$NON-NLS-1$
}
else if ( c == '\'' )
{
replacement = "%27"; //$NON-NLS-1$
}
else if ( c >= 0x80 )
{
replacement = '%' + Integer.toHexString( c );
}
if ( replacement != null )
{
if ( escapedUrl == null )
{
escapedUrl = new StringBuffer( url );
}
escapedUrl.replace( i + delta, i + delta + 1, replacement );
delta += ( replacement.length( ) - 1 );
}
}
if ( escapedUrl != null )
{
url = escapedUrl.toString( );
}
if ( url.length( ) > 0 )
{
content.append( " url('" ); //$NON-NLS-1$
content.append( url );
content.append( "')" ); //$NON-NLS-1$
}
}
}
|
package de.geeksfactory.opacclient.apis;
import org.apache.http.client.utils.URIBuilder;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.geeksfactory.opacclient.i18n.StringProvider;
import de.geeksfactory.opacclient.networking.HttpClientFactory;
import de.geeksfactory.opacclient.networking.NotReachableException;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.Copy;
import de.geeksfactory.opacclient.objects.CoverHolder;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailedItem;
import de.geeksfactory.opacclient.objects.Filter;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.SearchRequestResult;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.objects.Volume;
import de.geeksfactory.opacclient.searchfields.BarcodeSearchField;
import de.geeksfactory.opacclient.searchfields.CheckboxSearchField;
import de.geeksfactory.opacclient.searchfields.DropdownSearchField;
import de.geeksfactory.opacclient.searchfields.SearchField;
import de.geeksfactory.opacclient.searchfields.SearchQuery;
import de.geeksfactory.opacclient.searchfields.TextSearchField;
import java8.util.concurrent.CompletableFuture;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import static okhttp3.MultipartBody.Part.create;
/**
* API for Bibliotheca+/OPEN OPAC software
*
* @author Johan von Forstner, 29.03.2015
*/
public class Open extends OkHttpBaseApi implements OpacApi {
protected JSONObject data;
protected String opac_url;
protected Document searchResultDoc;
protected static HashMap<String, SearchResult.MediaType> defaulttypes = new HashMap<>();
static {
defaulttypes.put("archv", SearchResult.MediaType.BOOK);
defaulttypes.put("archv-digital", SearchResult.MediaType.EDOC);
defaulttypes.put("artchap", SearchResult.MediaType.ART);
defaulttypes.put("artchap-artcl", SearchResult.MediaType.ART);
defaulttypes.put("artchap-chptr", SearchResult.MediaType.ART);
defaulttypes.put("artchap-digital", SearchResult.MediaType.ART);
defaulttypes.put("audiobook", SearchResult.MediaType.AUDIOBOOK);
defaulttypes.put("audiobook-cd", SearchResult.MediaType.AUDIOBOOK);
defaulttypes.put("audiobook-lp", SearchResult.MediaType.AUDIOBOOK);
defaulttypes.put("audiobook-digital", SearchResult.MediaType.MP3);
defaulttypes.put("book", SearchResult.MediaType.BOOK);
defaulttypes.put("book-braille", SearchResult.MediaType.BOOK);
defaulttypes.put("book-continuing", SearchResult.MediaType.BOOK);
defaulttypes.put("book-digital", SearchResult.MediaType.EBOOK);
defaulttypes.put("book-largeprint", SearchResult.MediaType.BOOK);
defaulttypes.put("book-mic", SearchResult.MediaType.BOOK);
defaulttypes.put("book-thsis", SearchResult.MediaType.BOOK);
defaulttypes.put("compfile", SearchResult.MediaType.PACKAGE);
defaulttypes.put("compfile-digital", SearchResult.MediaType.PACKAGE);
defaulttypes.put("corpprof", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("encyc", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("game", SearchResult.MediaType.BOARDGAME);
defaulttypes.put("game-digital", SearchResult.MediaType.GAME_CONSOLE);
defaulttypes.put("image", SearchResult.MediaType.ART);
defaulttypes.put("image-2d", SearchResult.MediaType.ART);
defaulttypes.put("intmm", SearchResult.MediaType.EVIDEO);
defaulttypes.put("intmm-digital", SearchResult.MediaType.EVIDEO);
defaulttypes.put("jrnl", SearchResult.MediaType.MAGAZINE);
defaulttypes.put("jrnl-issue", SearchResult.MediaType.MAGAZINE);
defaulttypes.put("jrnl-digital", SearchResult.MediaType.EBOOK);
defaulttypes.put("kit", SearchResult.MediaType.PACKAGE);
defaulttypes.put("map", SearchResult.MediaType.MAP);
defaulttypes.put("map-digital", SearchResult.MediaType.EBOOK);
defaulttypes.put("msscr", SearchResult.MediaType.MP3);
defaulttypes.put("msscr-digital", SearchResult.MediaType.MP3);
defaulttypes.put("music", SearchResult.MediaType.MP3);
defaulttypes.put("music-cassette", SearchResult.MediaType.AUDIO_CASSETTE);
defaulttypes.put("music-cd", SearchResult.MediaType.CD_MUSIC);
defaulttypes.put("music-digital", SearchResult.MediaType.MP3);
defaulttypes.put("music-lp", SearchResult.MediaType.LP_RECORD);
defaulttypes.put("news", SearchResult.MediaType.NEWSPAPER);
defaulttypes.put("news-digital", SearchResult.MediaType.EBOOK);
defaulttypes.put("object", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("object-digital", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("paper", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("pub", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("rev", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("snd", SearchResult.MediaType.MP3);
defaulttypes.put("snd-cassette", SearchResult.MediaType.AUDIO_CASSETTE);
defaulttypes.put("snd-cd", SearchResult.MediaType.CD_MUSIC);
defaulttypes.put("snd-lp", SearchResult.MediaType.LP_RECORD);
defaulttypes.put("snd-digital", SearchResult.MediaType.EAUDIO);
defaulttypes.put("toy", SearchResult.MediaType.BOARDGAME);
defaulttypes.put("und", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("video-bluray", SearchResult.MediaType.BLURAY);
defaulttypes.put("video-digital", SearchResult.MediaType.EVIDEO);
defaulttypes.put("video-dvd", SearchResult.MediaType.DVD);
defaulttypes.put("video-film", SearchResult.MediaType.MOVIE);
defaulttypes.put("video-vhs", SearchResult.MediaType.MOVIE);
defaulttypes.put("vis", SearchResult.MediaType.ART);
defaulttypes.put("vis-digital", SearchResult.MediaType.ART);
defaulttypes.put("web", SearchResult.MediaType.URL);
defaulttypes.put("web-digital", SearchResult.MediaType.URL);
defaulttypes.put("art", SearchResult.MediaType.ART);
defaulttypes.put("arturl", SearchResult.MediaType.URL);
defaulttypes.put("bks", SearchResult.MediaType.BOOK);
defaulttypes.put("bksbrl", SearchResult.MediaType.BOOK);
defaulttypes.put("bksdeg", SearchResult.MediaType.BOOK);
defaulttypes.put("bkslpt", SearchResult.MediaType.BOOK);
defaulttypes.put("bksurl", SearchResult.MediaType.EBOOK);
defaulttypes.put("braille", SearchResult.MediaType.BOOK);
defaulttypes.put("com", SearchResult.MediaType.CD_SOFTWARE);
defaulttypes.put("comcgm", SearchResult.MediaType.GAME_CONSOLE);
defaulttypes.put("comcgmurl", SearchResult.MediaType.GAME_CONSOLE);
defaulttypes.put("comimm", SearchResult.MediaType.EVIDEO);
defaulttypes.put("comimmurl", SearchResult.MediaType.EVIDEO);
defaulttypes.put("comurl", SearchResult.MediaType.URL);
defaulttypes.put("int", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("inturl", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("map", SearchResult.MediaType.MAP);
defaulttypes.put("mapurl", SearchResult.MediaType.MAP);
defaulttypes.put("mic", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("micro", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("mix", SearchResult.MediaType.PACKAGE);
defaulttypes.put("mixurl", SearchResult.MediaType.PACKAGE);
defaulttypes.put("rec", SearchResult.MediaType.MP3);
defaulttypes.put("recmsr", SearchResult.MediaType.MP3);
defaulttypes.put("recmsrcas", SearchResult.MediaType.AUDIO_CASSETTE);
defaulttypes.put("recmsrcda", SearchResult.MediaType.CD_MUSIC);
defaulttypes.put("recmsrlps", SearchResult.MediaType.LP_RECORD);
defaulttypes.put("recmsrurl", SearchResult.MediaType.EAUDIO);
defaulttypes.put("recnsr", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("recnsrcas", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("recnsrcda", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("recnsrlps", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("recnsrurl", SearchResult.MediaType.UNKNOWN);
defaulttypes.put("recurl", SearchResult.MediaType.EAUDIO);
defaulttypes.put("sco", SearchResult.MediaType.SCORE_MUSIC);
defaulttypes.put("scourl", SearchResult.MediaType.SCORE_MUSIC);
defaulttypes.put("ser", SearchResult.MediaType.PACKAGE_BOOKS);
defaulttypes.put("sernew", SearchResult.MediaType.PACKAGE_BOOKS);
defaulttypes.put("sernewurl", SearchResult.MediaType.PACKAGE_BOOKS);
defaulttypes.put("serurl", SearchResult.MediaType.PACKAGE_BOOKS);
defaulttypes.put("url", SearchResult.MediaType.URL);
defaulttypes.put("vis", SearchResult.MediaType.ART);
defaulttypes.put("visart", SearchResult.MediaType.ART);
defaulttypes.put("visdvv", SearchResult.MediaType.DVD);
defaulttypes.put("vismot", SearchResult.MediaType.MOVIE);
defaulttypes.put("visngr", SearchResult.MediaType.ART);
defaulttypes.put("visngrurl", SearchResult.MediaType.ART);
defaulttypes.put("visphg", SearchResult.MediaType.BOARDGAME);
defaulttypes.put("vistoy", SearchResult.MediaType.BOARDGAME);
defaulttypes.put("visurl", SearchResult.MediaType.URL);
defaulttypes.put("visvhs", SearchResult.MediaType.MOVIE);
defaulttypes.put("visvid", SearchResult.MediaType.MOVIE);
defaulttypes.put("visvidurl", SearchResult.MediaType.EVIDEO);
defaulttypes.put("web", SearchResult.MediaType.URL);
}
/**
* This parameter needs to be passed to a URL to make sure we are not redirected to the mobile
* site
*/
protected static final String NO_MOBILE = "?nomo=1";
@Override
public void init(Library lib, HttpClientFactory httpClientFactory) {
super.init(lib, httpClientFactory);
this.data = lib.getData();
try {
this.opac_url = data.getString("baseurl");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
@Override
public SearchRequestResult search(List<SearchQuery> queries)
throws IOException, OpacErrorException, JSONException {
String url =
opac_url + "/" + data.getJSONObject("urls").getString("advanced_search") +
NO_MOBILE;
Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding()));
doc.setBaseUri(url);
int selectableCount = 0;
for (SearchQuery query : queries) {
if (query.getValue().equals("") || query.getValue().equals("false")) continue;
if (query.getSearchField() instanceof TextSearchField |
query.getSearchField() instanceof BarcodeSearchField) {
SearchField field = query.getSearchField();
if (field.getData().getBoolean("selectable")) {
selectableCount++;
if (selectableCount > 3) {
throw new OpacErrorException(stringProvider.getQuantityString(
StringProvider.LIMITED_NUM_OF_CRITERIA, 3, 3));
}
String number = numberToText(selectableCount);
Element searchField =
doc.select("select[name$=" + number + "SearchField]").first();
Element searchValue =
doc.select("input[name$=" + number + "SearchValue]").first();
setSelectValue(searchField, field.getId());
searchValue.val(query.getValue());
} else {
Element input = doc.select("input[name=" + field.getId() + "]").first();
input.val(query.getValue());
}
} else if (query.getSearchField() instanceof DropdownSearchField) {
DropdownSearchField field = (DropdownSearchField) query.getSearchField();
Element select = doc.select("select[name=" + field.getId() + "]").first();
setSelectValue(select, query.getValue());
} else if (query.getSearchField() instanceof CheckboxSearchField) {
CheckboxSearchField field = (CheckboxSearchField) query.getSearchField();
Element input = doc.select("input[name=" + field.getId() + "]").first();
input.attr("checked", query.getValue());
}
}
// Submit form
FormElement form = (FormElement) doc.select("form").first();
MultipartBody data = formData(form, "BtnSearch").build();
String postUrl = form.attr("abs:action");
String html = httpPost(postUrl, data, "UTF-8");
Document doc2 = Jsoup.parse(html);
doc2.setBaseUri(postUrl);
return parse_search(doc2, 0);
}
protected void setSelectValue(Element select, String value) {
for (Element opt : select.select("option")) {
if (value.equals(opt.val())) {
opt.attr("selected", "selected");
} else {
opt.removeAttr("selected");
}
}
}
protected CompletableFuture<Void> assignBestCover(final CoverHolder result,
final List<String> queue) {
if (queue.size() > 0) {
final String url = queue.get(0);
queue.remove(0);
return asyncHead(url, false)
.handle((response, throwable) -> {
if (throwable == null) {
result.setCover(url);
} else {
assignBestCover(result, queue).join();
}
return null;
});
} else {
// we don't have any more URLs in the queue
CompletableFuture<Void> future = new CompletableFuture<>();
future.complete(null);
return future;
}
}
protected SearchRequestResult parse_search(Document doc, int page) throws OpacErrorException {
searchResultDoc = doc;
if (doc.select("#Label1, span[id$=LblInfoMessage], .oclc-searchmodule-searchresult > " +
".boldText").size() > 0) {
String message = doc.select("#Label1, span[id$=LblInfoMessage], .boldText").text();
if (message.contains("keine Treffer")) {
return new SearchRequestResult(new ArrayList<>(), 0, 1, page);
} else {
throw new OpacErrorException(message);
}
}
int totalCount;
if (doc.select("span[id$=TotalItemsLabel]").size() > 0) {
totalCount = Integer.parseInt(
doc.select("span[id$=TotalItemsLabel]").first().text().split("[ \\t\\xA0\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000]")[0]);
} else {
throw new OpacErrorException(stringProvider.getString(StringProvider.UNKNOWN_ERROR));
}
Pattern idPattern = Pattern.compile("\\$(mdv|civ|dcv)(\\d+)\\$");
Pattern weakIdPattern = Pattern.compile("(mdv|civ|dcv)(\\d+)[^\\d]");
// Determine portalID value for availability
AvailabilityRestInfo restInfo = getAvailabilityRestInfo(doc);
Elements elements = doc.select("div[id$=divMedium], div[id$=divComprehensiveItem], div[id$=divDependentCatalogue]");
List<SearchResult> results = new ArrayList<>();
int i = 0;
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (Element element : elements) {
final SearchResult result = new SearchResult();
// Cover
if (element.select("input[id$=mediumImage]").size() > 0) {
result.setCover(element.select("input[id$=mediumImage]").first().attr("src"));
} else if (element.select("img[id$=CoverView_Image]").size() > 0) {
assignBestCover(result, getCoverUrlList(element.select("img[id$=CoverView_Image]").first()));
}
Element catalogueContent =
element.select(".catalogueContent, .oclc-searchmodule-mediumview-content, .oclc-searchmodule-comprehensiveitemview-content, .oclc-searchmodule-dependentitemview-content")
.first();
// Media Type
if (catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").size() > 0) {
String mediatype = catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").attr("class");
if (mediatype.startsWith("itemtype ")) {
mediatype = mediatype.substring("itemtype ".length());
}
SearchResult.MediaType defaulttype = defaulttypes.get(mediatype);
if (defaulttype == null) defaulttype = SearchResult.MediaType.UNKNOWN;
if (data.has("mediatypes")) {
try {
result.setType(SearchResult.MediaType
.valueOf(data.getJSONObject("mediatypes").getString(mediatype)));
} catch (JSONException e) {
result.setType(defaulttype);
}
} else {
result.setType(defaulttype);
}
} else {
result.setType(SearchResult.MediaType.UNKNOWN);
}
// Text
String title = catalogueContent
.select("a[id$=LbtnShortDescriptionValue], a[id$=LbtnTitleValue]").text();
String subtitle = catalogueContent.select("span[id$=LblSubTitleValue]").text();
String author = catalogueContent.select("span[id$=LblAuthorValue]").text();
String year = catalogueContent.select("span[id$=LblProductionYearValue]").text();
String mediumIdentifier =
catalogueContent.select("span[id$=LblMediumIdentifierValue]").text();
String series = catalogueContent.select("span[id$=LblSeriesValue]").text();
// Some libraries, such as Bern, have labels but no <span id="..Value"> tags
int j = 0;
for (Element div : catalogueContent.children()) {
if (subtitle.equals("") && div.select("span").size() == 0 && j > 0 && j < 3) {
subtitle = div.text().trim();
}
if (author.equals("") && div.select("span[id$=LblAuthor]").size() == 1) {
author = div.text().trim();
if (author.contains(":")) {
author = author.split(":")[1];
}
}
if (year.equals("") && div.select("span[id$=LblProductionYear]").size() == 1) {
year = div.text().trim();
if (year.contains(":")) {
year = year.split(":")[1];
}
}
j++;
}
StringBuilder text = new StringBuilder();
text.append("<b>").append(title).append("</b>");
if (!subtitle.equals("")) text.append("<br/>").append(subtitle);
if (!author.equals("")) text.append("<br/>").append(author);
if (!mediumIdentifier.equals("")) text.append("<br/>").append(mediumIdentifier);
if (!year.equals("")) text.append("<br/>").append(year);
if (!series.equals("")) text.append("<br/>").append(series);
result.setInnerhtml(text.toString());
Matcher matcher = idPattern.matcher(element.html());
if (matcher.find()) {
result.setId(matcher.group(2));
} else {
matcher = weakIdPattern.matcher(element.html());
if (matcher.find()) {
result.setId(matcher.group(2));
}
}
// Availability
if (result.getId() != null) {
String culture = element.select("input[name$=culture]").val();
String ekzid = element.select("input[name$=ekzid]").val();
boolean ebook = !ekzid.equals("");
String url;
if (ebook) {
url = restInfo.ebookRestUrl != null ? restInfo.ebookRestUrl :
opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.CopConnector/Services" +
"/Onleihe.asmx/GetNcipLookupItem";
} else {
url = restInfo.restUrl != null ? restInfo.restUrl :
opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.SearchModule/" +
"SearchService.asmx/GetAvailability";
}
JSONObject data = new JSONObject();
try {
if (ebook) {
data.put("portalId", restInfo.portalId).put("itemid", ekzid)
.put("language", culture);
} else {
data.put("portalId", restInfo.portalId).put("mednr", result.getId())
.put("culture", culture).put("requestCopyData", false)
.put("branchFilter", "");
}
RequestBody entity = RequestBody.create(MEDIA_TYPE_JSON, data.toString());
futures.add(asyncPost(url, entity, false).handle((response, throwable) -> {
if (throwable != null) return null;
ResponseBody body = response.body();
try {
JSONObject availabilityData = new JSONObject(body.string());
String isAvail;
if (ebook) {
isAvail = availabilityData
.getJSONObject("d").getJSONObject("LookupItem")
.getString("Available");
} else {
isAvail = availabilityData
.getJSONObject("d").getString("IsAvail");
}
switch (isAvail) {
case "true":
result.setStatus(SearchResult.Status.GREEN);
break;
case "false":
result.setStatus(SearchResult.Status.RED);
break;
case "digital":
result.setStatus(SearchResult.Status.UNKNOWN);
break;
}
} catch (JSONException | IOException e) {
e.printStackTrace();
}
body.close();
return null;
}));
} catch (JSONException e) {
e.printStackTrace();
}
}
result.setNr(i);
results.add(result);
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
return new SearchRequestResult(results, totalCount, page);
}
private AvailabilityRestInfo getAvailabilityRestInfo(Document doc) {
AvailabilityRestInfo info = new AvailabilityRestInfo();
info.portalId = 1;
for (Element scripttag : doc.select("script")) {
String scr = scripttag.html();
if (scr.contains("LoadSharedCatalogueViewAvailabilityAsync")) {
Pattern pattern = Pattern.compile(
".*LoadSharedCatalogueViewAvailabilityAsync\\(\"([^,]*)\",\"([^,]*)\"," +
"[^0-9,]*([0-9]+)[^0-9,]*,.*\\).*");
Matcher matcher = pattern.matcher(scr);
if (matcher.find()) {
info.restUrl = getAbsoluteUrl(opac_url, matcher.group(1));
info.ebookRestUrl = getAbsoluteUrl(opac_url, matcher.group(2));
info.portalId = Integer.parseInt(matcher.group(3));
}
}
}
return info;
}
protected static String getAbsoluteUrl(String baseUrl, String url) {
if (!url.contains(":
try {
URIBuilder uriBuilder = new URIBuilder(baseUrl);
url = uriBuilder.setPath(url)
.build()
.normalize().toString();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return url;
}
private class AvailabilityRestInfo {
public int portalId;
public String restUrl;
public String ebookRestUrl;
}
private List<String> getCoverUrlList(Element img) {
String[] parts = img.attr("sources").split("\\|");
// caller=vlbPublic&func=DirectIsbnSearch&isbn=9783868511291&
// nSiteId=11|c|SetNoCover|a|/DesktopModules/OCLC.OPEN.PL.DNN
// .BaseLibrary/StyleSheets/Images/Fallbacks/emptyURL.gif?4.2.0.0|a|
List<String> alternatives = new ArrayList<>();
for (int i = 0; i + 2 < parts.length; i++) {
if (parts[i].equals("SetSimpleCover")) {
String url = parts[i + 2].replace("&", "&");
try {
alternatives.add(new URL(new URL(opac_url), url).toString());
} catch (MalformedURLException ignored) {
}
}
}
if (img.hasAttr("devsources")) {
parts = img.attr("devsources").split("\\|");
for (int i = 0; i + 2 < parts.length; i++) {
if (parts[i].equals("SetSimpleCover")) {
String url = parts[i + 2].replace("&", "&");
try {
alternatives.add(new URL(new URL(opac_url), url).toString());
} catch (MalformedURLException ignored) {
}
}
}
}
return alternatives;
}
private String numberToText(int number) {
switch (number) {
case 1:
return "First";
case 2:
return "Second";
case 3:
return "Third";
default:
return null;
}
}
@Override
public SearchRequestResult filterResults(Filter filter, Filter.Option option)
throws IOException, OpacErrorException {
return null;
}
@Override
public SearchRequestResult searchGetPage(int page)
throws IOException, OpacErrorException, JSONException {
if (searchResultDoc == null) throw new NotReachableException();
Document doc = searchResultDoc;
if (doc.select("span[id$=DataPager1]").size() == 0) {
/*
New style: Page buttons using normal links
We can go directly to the correct page
*/
if (doc.select("a[id*=LinkButtonPageN]").size() > 0) {
String href = doc.select("a[id*=LinkButtonPageN][href*=page]").first().attr("href");
String url = href.replaceFirst("page=\\d+", "page=" + page);
Document doc2 = Jsoup.parse(httpGet(url, getDefaultEncoding()));
doc2.setBaseUri(url);
return parse_search(doc2, page);
} else {
int totalCount;
try {
totalCount = Integer.parseInt(
doc.select("span[id$=TotalItemsLabel]").first().text());
} catch (Exception e) {
totalCount = 0;
}
// Next page does not exist
return new SearchRequestResult(
new ArrayList<SearchResult>(),
0,
totalCount
);
}
} else {
/*
Old style: Page buttons using Javascript
When there are many pages of results, there will only be links to the next 4 and
previous 4 pages, so we will click links until it gets to the correct page.
*/
Elements pageLinks = doc.select("span[id$=DataPager1]").first()
.select("a[id*=LinkButtonPageN], span[id*=LabelPageN]");
int from = Integer.valueOf(pageLinks.first().text());
int to = Integer.valueOf(pageLinks.last().text());
Element linkToClick;
boolean willBeCorrectPage;
if (page < from) {
linkToClick = pageLinks.first();
willBeCorrectPage = false;
} else if (page > to) {
linkToClick = pageLinks.last();
willBeCorrectPage = false;
} else {
linkToClick = pageLinks.get(page - from);
willBeCorrectPage = true;
}
if (linkToClick.tagName().equals("span")) {
// we are trying to get the page we are already on
return parse_search(searchResultDoc, page);
}
Pattern pattern = Pattern.compile("javascript:__doPostBack\\('([^,]*)','([^\\)]*)'\\)");
Matcher matcher = pattern.matcher(linkToClick.attr("href"));
if (!matcher.find()) throw new OpacErrorException(StringProvider.INTERNAL_ERROR);
FormElement form = (FormElement) doc.select("form").first();
MultipartBody data = formData(form, null).addFormDataPart("__EVENTTARGET", matcher.group(1))
.addFormDataPart("__EVENTARGUMENT", matcher.group(2))
.build();
String postUrl = form.attr("abs:action");
String html = httpPost(postUrl, data, "UTF-8");
if (willBeCorrectPage) {
// We clicked on the correct link
Document doc2 = Jsoup.parse(html);
doc2.setBaseUri(postUrl);
return parse_search(doc2, page);
} else {
// There was no correct link, so try to find one again
searchResultDoc = Jsoup.parse(html);
searchResultDoc.setBaseUri(postUrl);
return searchGetPage(page);
}
}
}
@Override
public DetailedItem getResultById(String id, String homebranch)
throws IOException, OpacErrorException {
try {
String url;
if (id.startsWith("https:
url = id;
} else {
url = opac_url + "/" + data.getJSONObject("urls").getString("simple_search") +
NO_MOBILE + "&id=" + id;
}
Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding()));
doc.setBaseUri(url);
return parse_result(doc);
} catch (JSONException e) {
throw new IOException(e.getMessage());
}
}
protected DetailedItem parse_result(Document doc) {
DetailedItem item = new DetailedItem();
// Title and Subtitle
item.setTitle(doc.select("span[id$=LblShortDescriptionValue], span[id$=LblTitleValue]").text());
String subtitle = doc.select("span[id$=LblSubTitleValue]").text();
if (subtitle.equals("") && doc.select("span[id$=LblShortDescriptionValue]").size() > 0) {
// Subtitle detection for Bern
Element next = doc.select("span[id$=LblShortDescriptionValue]").first().parent()
.nextElementSibling();
if (next.select("span").size() == 0) {
subtitle = next.text().trim();
}
}
if (!subtitle.equals("")) {
item.addDetail(new Detail(stringProvider.getString(StringProvider.SUBTITLE), subtitle));
}
// Cover
if (doc.select("input[id$=mediumImage]").size() > 0) {
item.setCover(doc.select("input[id$=mediumImage]").attr("src"));
} else if (doc.select("img[id$=CoverView_Image]").size() > 0) {
assignBestCover(item, getCoverUrlList(doc.select("img[id$=CoverView_Image]").first()));
}
item.setId(doc.select("input[id$=regionmednr]").val());
// Description
if (doc.select("span[id$=ucCatalogueContent_LblAnnotation]").size() > 0) {
String name = doc.select("span[id$=lblCatalogueContent]").text();
String value = doc.select("span[id$=ucCatalogueContent_LblAnnotation]").text();
item.addDetail(new Detail(name, value));
}
// Parent
if (doc.select("a[id$=HyperLinkParent]").size() > 0) {
item.setCollectionId(doc.select("a[id$=HyperLinkParent]").first().attr("href"));
}
// Details
String DETAIL_SELECTOR =
"div[id$=CatalogueDetailView] .spacingBottomSmall:has(span+span)," +
"div[id$=CatalogueDetailView] .spacingBottomSmall:has(span+a), " +
"div[id$=CatalogueDetailView] .oclc-searchmodule-detail-data div:has" +
"(span+span), " +
"div[id$=CatalogueDetailView] .oclc-searchmodule-detail-data div:has" +
"(span+a)";
for (Element detail : doc.select(DETAIL_SELECTOR)) {
String name = detail.select("span").get(0).text().replace(": ", "");
String value = "";
if (detail.select("a").size() > 1) {
int i = 0;
for (Element a : detail.select("a")) {
if (i != 0) {
value += ", ";
}
value += a.text().trim();
i++;
}
} else {
value = detail.select("span, a").get(1).text();
if (value.contains("hier klicken") && detail.select("a").size() > 0) {
value = value + " " + detail.select("a").first().attr("href");
}
}
item.addDetail(new Detail(name, value));
}
// Description
if (doc.select("div[id$=CatalogueContent]").size() > 0) {
String name = doc.select("div[id$=CatalogueContent] .oclc-module-header").text();
String value =
doc.select("div[id$=CatalogueContent] .oclc-searchmodule-detail-annotation")
.text();
item.addDetail(new Detail(name, value));
}
// Copies
Element table = doc.select("table[id$=grdViewMediumCopies]").first();
if (table != null) {
Elements trs = table.select("tr");
List<String> columnmap = new ArrayList<>();
for (Element th : trs.first().select("th")) {
columnmap.add(getCopyColumnKey(th.text()));
}
DateTimeFormatter fmt =
DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN);
for (int i = 1; i < trs.size(); i++) {
Elements tds = trs.get(i).select("td");
Copy copy = new Copy();
for (int j = 0; j < tds.size(); j++) {
if (columnmap.get(j) == null) continue;
String text = tds.get(j).text().replace("\u00a0", "");
if (tds.get(j).select(".oclc-module-label").size() > 0 &&
tds.get(j).select("span").size() == 2) {
text = tds.get(j).select("span").get(1).text();
}
if (text.equals("")) continue;
String colname = columnmap.get(j);
if (copy.get(colname) != null && !copy.get(colname).isEmpty()) {
text = copy.get(colname) + " / " + text;
}
copy.set(colname, text, fmt);
}
item.addCopy(copy);
}
}
// Dependent (e.g. Verden)
if (doc.select("div[id$=DivDependentCatalogue]").size() > 0) {
String url = opac_url +
"/DesktopModules/OCLC.OPEN.PL.DNN.SearchModule/SearchService.asmx/GetDependantCatalogues";
JSONObject postData = new JSONObject();
// Determine portalID value
int portalId = 1;
for (Element scripttag : doc.select("script")) {
String scr = scripttag.html();
if (scr.contains("LoadCatalogueViewDependantCataloguesAsync")) {
Pattern portalIdPattern = Pattern.compile(
".*LoadCatalogueViewDependantCataloguesAsync\\([^,]*,[^,]*," +
"[^,]*,[^,]*,[^,]*,[^0-9,]*([0-9]+)[^0-9,]*,.*\\).*");
Matcher portalIdMatcher = portalIdPattern.matcher(scr);
if (portalIdMatcher.find()) {
portalId = Integer.parseInt(portalIdMatcher.group(1));
}
}
}
try {
postData.put("portalId", portalId).put("mednr", item.getId())
.put("tabUrl", opac_url + "/" + data.getJSONObject("urls").getString("simple_search") + NO_MOBILE + "&id=")
.put("branchFilter", "");
RequestBody entity = RequestBody.create(MEDIA_TYPE_JSON, postData.toString());
String json = httpPost(url, entity, getDefaultEncoding());
JSONObject volumeData = new JSONObject(json);
JSONArray cat = volumeData.getJSONObject("d").getJSONArray("Catalogues");
for (int i = 0; i < cat.length(); i++) {
JSONObject obj = cat.getJSONObject(i);
Map<String, String> params = getQueryParamsFirst(obj.getString("DependantUrl"));
item.addVolume(new Volume(
params.get("id"),
obj.getString("DependantTitle")
));
}
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
return item;
}
protected String getCopyColumnKey(String text) {
switch (text) {
case "Zweigstelle":
case "Bibliothek":
return "branch";
case "Standorte":
case "Standort":
case "Standort 2":
case "Standort 3":
return "location";
case "Status":
return "status";
case "Vorbestellungen":
return "reservations";
case "Frist":
case "Rückgabedatum":
return "returndate";
case "Signatur":
return "signature";
case "Barcode":
return "barcode";
default:
return null;
}
}
@Override
public DetailedItem getResult(int position) throws IOException, OpacErrorException {
return null;
}
@Override
public ReservationResult reservation(DetailedItem item, Account account,
int useraction, String selection) throws IOException {
return null;
}
@Override
public ProlongResult prolong(String media, Account account, int useraction,
String selection) throws IOException {
return null;
}
@Override
public ProlongAllResult prolongAll(Account account, int useraction, String selection)
throws IOException {
return null;
}
@Override
public CancelResult cancel(String media, Account account, int useraction,
String selection) throws IOException, OpacErrorException {
return null;
}
@Override
public AccountData account(Account account)
throws IOException, JSONException, OpacErrorException {
return null;
}
@Override
public void checkAccountData(Account account)
throws IOException, JSONException, OpacErrorException {
}
@Override
public List<SearchField> parseSearchFields()
throws IOException, OpacErrorException, JSONException {
String url =
opac_url + "/" + data.getJSONObject("urls").getString("advanced_search") +
NO_MOBILE;
Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding()));
if (doc.select("[id$=LblErrorMsg]").size() > 0 &&
doc.select("[id$=ContentPane] input").size() == 0) {
throw new OpacErrorException(doc.select("[id$=LblErrorMsg]").text());
}
Element module = doc.select(".ModOPENExtendedSearchModuleC").first();
List<SearchField> fields = new ArrayList<>();
JSONObject selectable = new JSONObject();
selectable.put("selectable", true);
JSONObject notSelectable = new JSONObject();
notSelectable.put("selectable", false);
// Selectable search criteria
Elements options = module.select("select[id$=FirstSearchField] option");
for (Element option : options) {
TextSearchField field = new TextSearchField();
field.setId(option.val());
field.setDisplayName(option.text());
field.setData(selectable);
fields.add(field);
}
// More criteria
Element moreHeader = null;
if (module.select("table").size() == 1) {
moreHeader = module.select("span[id$=LblMoreCriterias]").parents().select("tr").first();
} else {
// Newer OPEN, e.g. Erlangen
moreHeader = module.select("span[id$=LblMoreCriterias]").first();
}
if (moreHeader != null) {
Elements siblings = moreHeader.siblingElements();
int startIndex = moreHeader.elementSiblingIndex();
for (int i = startIndex; i < siblings.size(); i++) {
Element tr = siblings.get(i);
if (tr.select("input, select").size() == 0) continue;
if (tr.select("input[type=text]").size() == 1) {
Element input = tr.select("input[type=text]").first();
TextSearchField field = new TextSearchField();
field.setId(input.attr("name"));
field.setDisplayName(tr.select("span[id*=Lbl]").first().text());
field.setData(notSelectable);
if (tr.text().contains("nur Ziffern")) field.setNumber(true);
fields.add(field);
} else if (tr.select("input[type=text]").size() == 2) {
Element input1 = tr.select("input[type=text]").get(0);
Element input2 = tr.select("input[type=text]").get(1);
TextSearchField field1 = new TextSearchField();
field1.setId(input1.attr("name"));
field1.setDisplayName(tr.select("span[id*=Lbl]").first().text());
field1.setData(notSelectable);
if (tr.text().contains("nur Ziffern")) field1.setNumber(true);
fields.add(field1);
TextSearchField field2 = new TextSearchField();
field2.setId(input2.attr("name"));
field2.setDisplayName(tr.select("span[id*=Lbl]").first().text());
field2.setData(notSelectable);
field2.setHalfWidth(true);
if (tr.text().contains("nur Ziffern")) field2.setNumber(true);
fields.add(field2);
} else if (tr.select("select").size() == 1) {
Element select = tr.select("select").first();
DropdownSearchField dropdown = new DropdownSearchField();
dropdown.setId(select.attr("name"));
dropdown.setDisplayName(tr.select("span[id*=Lbl]").first().text());
List<DropdownSearchField.Option> values = new ArrayList<>();
for (Element option : select.select("option")) {
DropdownSearchField.Option opt =
new DropdownSearchField.Option(option.val(), option.text());
values.add(opt);
}
dropdown.setDropdownValues(values);
fields.add(dropdown);
} else if (tr.select("input[type=checkbox]").size() == 1) {
Element checkbox = tr.select("input[type=checkbox]").first();
CheckboxSearchField field = new CheckboxSearchField();
field.setId(checkbox.attr("name"));
field.setDisplayName(tr.select("span[id*=Lbl]").first().text());
fields.add(field);
}
}
}
return fields;
}
@Override
public String getShareUrl(String id, String title) {
return opac_url + "/Permalink.aspx" + "?id" + "=" + id;
}
@Override
public int getSupportFlags() {
return SUPPORT_FLAG_ENDLESS_SCROLLING;
}
@Override
public Set<String> getSupportedLanguages() throws IOException {
return null;
}
@Override
public void setLanguage(String language) {
}
@Override
protected String getDefaultEncoding() {
try {
if (data.has("charset")) {
return data.getString("charset");
}
} catch (JSONException e) {
e.printStackTrace();
}
return "UTF-8";
}
static StringBuilder appendQuotedString(StringBuilder target, String key) {
target.append('"');
for (int i = 0, len = key.length(); i < len; i++) {
char ch = key.charAt(i);
switch (ch) {
case '\n':
target.append("%0A");
break;
case '\r':
target.append("%0D");
break;
case '"':
target.append("%22");
break;
default:
target.append(ch);
break;
}
}
target.append('"');
return target;
}
public static MultipartBody.Part createFormData(String name, String value) {
return createFormData(name, null, RequestBody.create(null, value.getBytes()));
}
public static MultipartBody.Part createFormData(String name, String filename, RequestBody body) {
if (name == null) {
throw new NullPointerException("name == null");
}
StringBuilder disposition = new StringBuilder("form-data; name=");
appendQuotedString(disposition, name);
if (filename != null) {
disposition.append("; filename=");
appendQuotedString(disposition, filename);
}
return create(Headers.of("Content-Disposition", disposition.toString()), body);
}
/**
* Better version of JSoup's implementation of this function ({@link
* org.jsoup.nodes.FormElement#formData()}).
*
* @param form The form to submit
* @param submitName The name attribute of the button which is clicked to submit the form, or
* null
* @return A MultipartEntityBuilder containing the data of the form
*/
protected static MultipartBody.Builder formData(FormElement form, String submitName) {
MultipartBody.Builder data = new MultipartBody.Builder();
data.setType(MediaType.parse("multipart/form-data"));
// data.setCharset somehow breaks everything in Bern.
// data.addTextBody breaks utf-8 characters in select boxes in Bern
// .getBytes is an implicit, undeclared UTF-8 conversion, this seems to work -- at least
// in Bern
// Remove nested forms
form.select("form form").remove();
form = ((FormElement) Jsoup.parse(form.outerHtml()).select("form").get(0));
// iterate the form control elements and accumulate their values
for (Element el : form.elements()) {
if (!el.tag().isFormSubmittable()) {
continue; // contents are form listable, superset of submitable
}
String name = el.attr("name");
if (name.length() == 0) continue;
String type = el.attr("type");
if ("select".equals(el.tagName())) {
Elements options = el.select("option[selected]");
boolean set = false;
for (Element option : options) {
data.addPart(createFormData(name, option.val()));
set = true;
}
if (!set) {
Element option = el.select("option").first();
if (option != null) {
data.addPart(createFormData(name, option.val()));
}
}
} else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) {
// only add checkbox or radio if they have the checked attribute
if (el.hasAttr("checked")) {
data.addFormDataPart(name, el.val().length() > 0 ? el.val() : "on");
}
} else if ("submit".equalsIgnoreCase(type) || "image".equalsIgnoreCase(type) ||
"button".equalsIgnoreCase(type)) {
if (submitName != null && el.attr("name").contains(submitName)) {
data.addPart(createFormData(name, el.val()));
}
} else {
data.addPart(createFormData(name, el.val()));
}
}
return data;
}
}
|
package sh.jay.xposed.whatsapp;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import java.util.HashMap;
import java.util.Map;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.RelativeLayout;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
/**
* Adds support for making the background color of group conversation rows
* grey in color.
*
* Note: this code has been written solely to be performant. This means some
* code is inlined (read: copy/pasted) that wouldn't normally be, and private
* classes are used in a cache without getters and setters - amongst other things.
* This is because we're hooking into android.view.View->setTag(java.lang.Object)
* which is quite a general method, so we want to be as fast as possible.
*/
public class HighlightGroups implements IXposedHookLoadPackage {
private static final Map<Object, Drawable> processedTags = new HashMap<Object, Drawable>();
private static final Map<View, View> conversationRows = new HashMap<View, View>();
/**
* This is initially called by the Xposed Framework when we register this
* android application as an Xposed Module.
*/
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
// This method is called once per package, so we only want to apply hooks to WhatsApp.
if (Utils.WHATSAPP_PACKAGE_NAME.equals(lpparam.packageName)) {
return;
}
if (!Preferences.hasHighlightGroups()) {
Utils.debug("Ignoring call to setTag() due to the highlight groups feature being disabled");
return;
}
findAndHookMethod("android.view.View", lpparam.classLoader, "setTag", Object.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
final View thisView = (View) param.thisObject;
View conversationRow = conversationRows.get(thisView);
if (!conversationRows.containsKey(thisView)) {
final View contactPickerViewContainer = (View) ((View) param.thisObject).getParent();
if (null == contactPickerViewContainer) {
// Doesn't even have a parent.
conversationRows.put(thisView, null);
return;
}
conversationRow = (View) contactPickerViewContainer.getParent();
if (null == conversationRow || !(conversationRow instanceof RelativeLayout)) {
// We require that our conversationRow is a RelativeLayout
// (see the overall parent of res/layout/conversations_row.xml).
conversationRows.put(thisView, null);
return;
}
conversationRows.put(thisView, conversationRow);
} else if (null == conversationRow) {
return;
}
final Object tag = param.args[0];
if (processedTags.containsKey(tag)) {
// For performance, there are no debugging or trace lines here. Let's hope it always works!
conversationRow.setBackgroundDrawable(processedTags.get(tag));
return;
}
// We have never considered what color this conversation should be. Let's figure it out.
Utils.debug("Cache miss for " + tag + " so computing the correct color");
Drawable background = null;
if (tag.toString().contains("@g.us")) {
background = new ColorDrawable(Preferences.getHighlightGroupColor());
}
conversationRow.setBackgroundDrawable(background);
processedTags.put(tag, background);
Utils.debug("Set background to " + background + " for " + tag);
}
});
}
}
|
package org.ovirt.engine.ui.uicommonweb.models.vms;
import java.util.ArrayList;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel;
import org.ovirt.engine.ui.uicommonweb.models.TabName;
import org.ovirt.engine.ui.uicommonweb.models.vms.instancetypes.InstanceTypeManager;
import org.ovirt.engine.ui.uicommonweb.models.vms.instancetypes.NewPoolInstanceTypeManager;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NewPoolNameLengthValidation;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
public class NewPoolModelBehavior extends PoolModelBehaviorBase {
private InstanceTypeManager instanceTypeManager;
@Override
public void initialize(SystemTreeItemModel systemTreeSelectedItem) {
super.initialize(systemTreeSelectedItem);
getModel().getVmType().setIsChangeable(true);
templateValidate();
instanceTypeManager = new NewPoolInstanceTypeManager(getModel());
getModel().getVmInitModel().init(null);
}
@Override
protected void postDataCentersLoaded(List<StoragePool> dataCenters) {
if (!dataCenters.isEmpty()) {
super.postDataCentersLoaded(dataCenters);
} else {
getModel().disableEditing(ConstantsManager.getInstance().getConstants().notAvailableWithNoUpDC());
}
}
@Override
public void postDataCenterWithClusterSelectedItemChanged() {
super.postDataCenterWithClusterSelectedItemChanged();
final DataCenterWithCluster dataCenterWithCluster = getModel().getDataCenterWithClustersList().getSelectedItem();
StoragePool dataCenter = getModel().getSelectedDataCenter();
if (dataCenter == null) {
return;
}
AsyncDataProvider.getInstance().getTemplateListByDataCenter(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target1, Object returnValue1) {
List<VmTemplate> templatesByDataCenter = (List<VmTemplate>) returnValue1;
List<VmTemplate> properArchitectureTemplates =
AsyncDataProvider.getInstance().filterTemplatesByArchitecture(templatesByDataCenter,
dataCenterWithCluster.getCluster().getArchitecture());
List<VmTemplate> templatesWithoutBlank = new ArrayList<>();
for (VmTemplate template : properArchitectureTemplates) {
final boolean isBlankOrVersionOfBlank = template.getId().equals(Guid.Empty)
|| template.getBaseTemplateId().equals(Guid.Empty);
if (!isBlankOrVersionOfBlank) {
templatesWithoutBlank.add(template);
}
}
initTemplateWithVersion(templatesWithoutBlank, null, false);
}
}), dataCenter.getId());
instanceTypeManager.updateAll();
}
@Override
public void templateWithVersion_SelectedItemChanged() {
super.templateWithVersion_SelectedItemChanged();
VmTemplate template = getModel().getTemplateWithVersion().getSelectedItem() != null
? getModel().getTemplateWithVersion().getSelectedItem().getTemplateVersion()
: null;
if (template == null) {
return;
}
setupWindowModelFrom(template);
doChangeDefaultHost(template.getDedicatedVmForVdsList());
updateRngDevice(template.getId());
getModel().getCustomPropertySheet().deserialize(template.getCustomProperties());
}
@Override
public boolean validate() {
boolean parentValidation = super.validate();
if (getModel().getName().getIsValid()) {
getModel().getName().validateEntity(new IValidation[] { new NewPoolNameLengthValidation(
getModel().getName().getEntity(),
getModel().getNumOfDesktops().getEntity(),
getModel().getOSType().getSelectedItem()
) });
final boolean isNameValid = getModel().getName().getIsValid();
getModel().setValidTab(TabName.GENERAL_TAB, getModel().isValidTab(TabName.GENERAL_TAB) && isNameValid);
return getModel().getName().getIsValid() && parentValidation;
}
return parentValidation;
}
private void templateValidate() {
AsyncDataProvider.getInstance().countAllTemplates(new AsyncQuery(getModel(), new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
int count = (Integer) returnValue;
if (count <= 1) {
getModel().disableEditing(ConstantsManager.getInstance().getConstants().notAvailableWithNoTemplates());
}
}
}));
}
@Override
protected List<VDSGroup> filterClusters(List<VDSGroup> clusters) {
return AsyncDataProvider.getInstance().filterClustersWithoutArchitecture(clusters);
}
@Override
public InstanceTypeManager getInstanceTypeManager() {
return instanceTypeManager;
}
@Override
public void enableSinglePCI(boolean enabled) {
super.enableSinglePCI(enabled);
getModel().getIsSingleQxlEnabled().setEntity(enabled);
}
}
|
package org.innovateuk.ifs.application.transactional;
import org.innovateuk.ifs.Application;
import org.innovateuk.ifs.BaseUnitTestMocksTest;
import org.innovateuk.ifs.application.domain.Question;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.resource.CompetitionSetupSection;
import org.innovateuk.ifs.competition.transactional.CompetitionSetupService;
import org.innovateuk.ifs.setup.resource.SetupStatusResource;
import org.innovateuk.ifs.setup.transactional.SetupStatusService;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import java.util.List;
import java.util.Map;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.setup.builder.SetupStatusResourceBuilder.newSetupStatusResource;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
public class QuestionSetupServiceTest extends BaseUnitTestMocksTest {
@InjectMocks
protected QuestionSetupService service = new QuestionSetupServiceImpl();
@Mock
private SetupStatusService setupStatusService;
@Mock
private CompetitionSetupService competitionSetupService;
@Test
public void testMarkQuestionInSetupAsCompleteFindOne() throws Exception {
final Long questionId = 23L;
final Long competitionId = 32L;
final CompetitionSetupSection parentSection = CompetitionSetupSection.APPLICATION_FORM;
final SetupStatusResource foundStatusResource = newSetupStatusResource()
.withId(13L)
.withClassName(Question.class.getName())
.withClassPk(questionId)
.withTargetClassName(Competition.class.getName())
.withClassPk(competitionId)
.withParentId(12L)
.withCompleted(Boolean.FALSE).build();
final SetupStatusResource savingStatus = newSetupStatusResource()
.withId(13L)
.withClassName(Question.class.getName())
.withClassPk(questionId)
.withTargetClassName(Competition.class.getName())
.withClassPk(competitionId)
.withParentId(12L)
.withCompleted(Boolean.TRUE).build();
final SetupStatusResource savedStatus = newSetupStatusResource()
.withId(13L)
.withClassName(Question.class.getName())
.withClassPk(questionId)
.withParentId(12L)
.withTargetClassName(Competition.class.getName())
.withClassPk(competitionId)
.withCompleted(Boolean.TRUE).build();
when(setupStatusService.findSetupStatusAndTarget(Question.class.getName(), questionId, Competition.class.getName(), competitionId))
.thenReturn(serviceSuccess(foundStatusResource));
when(setupStatusService.saveSetupStatus(savingStatus)).thenReturn(serviceSuccess(savedStatus));
service.markQuestionInSetupAsComplete(questionId, competitionId, parentSection);
verify(setupStatusService, times(1)).findSetupStatusAndTarget(Question.class.getName(), questionId, Competition.class.getName(), competitionId);
verify(setupStatusService, times(1)).saveSetupStatus(savingStatus);
}
@Test
public void testMarkQuestionInSetupAsIncompleteCreateOne() throws Exception {
final Long questionId = 23L;
final Long competitionId = 32L;
final CompetitionSetupSection parentSection = CompetitionSetupSection.APPLICATION_FORM;
final SetupStatusResource savingStatus = newSetupStatusResource()
.withClassName(Question.class.getName())
.withClassPk(questionId)
.withParentId(12L)
.withTargetClassName(Competition.class.getName())
.withTargetId(competitionId)
.withCompleted(Boolean.FALSE).build();
savingStatus.setId(null);
final SetupStatusResource savedStatus = newSetupStatusResource()
.withId(13L)
.withClassName(Question.class.getName())
.withClassPk(questionId)
.withParentId(12L)
.withTargetClassName(Competition.class.getName())
.withTargetId(competitionId)
.withCompleted(Boolean.FALSE).build();
final SetupStatusResource parentSectionStatus = newSetupStatusResource()
.withId(12L)
.withClassName(parentSection.getClass().getName())
.withClassPk(parentSection.getId())
.withParentId()
.withTargetClassName(Competition.class.getName())
.withTargetId(competitionId)
.withCompleted(Boolean.FALSE).build();
when(setupStatusService.findSetupStatusAndTarget(parentSection.getClass().getName(), parentSection.getId(), Competition.class.getName(), competitionId))
.thenReturn(serviceFailure(new Error("GENERAL_NOT_FOUND", HttpStatus.BAD_REQUEST)));
when(competitionSetupService.markSectionIncomplete(competitionId, parentSection)).thenReturn(serviceSuccess(parentSectionStatus));
when(setupStatusService.findSetupStatusAndTarget(Question.class.getName(), questionId, Competition.class.getName(), competitionId))
.thenReturn(serviceFailure(new Error("GENERAL_NOT_FOUND", HttpStatus.BAD_REQUEST)));
when(setupStatusService.saveSetupStatus(savingStatus)).thenReturn(serviceSuccess(savedStatus));
service.markQuestionInSetupAsIncomplete(questionId, competitionId, parentSection);
verify(setupStatusService, times(1)).findSetupStatusAndTarget(parentSection.getClass().getName(), parentSection.getId(), Competition.class.getName(), competitionId);
verify(competitionSetupService, times(1)).markSectionIncomplete(competitionId, parentSection);
verify(setupStatusService, times(1)).findSetupStatusAndTarget(Question.class.getName(), questionId, Competition.class.getName(), competitionId);
verify(setupStatusService, times(1)).saveSetupStatus(savingStatus);
}
@Test
public void testGetQuestionStatuses() throws Exception {
final Long questionId = 23L;
final Long competitionId = 32L;
final CompetitionSetupSection parentSection = CompetitionSetupSection.APPLICATION_FORM;
final List<SetupStatusResource> foundStatuses = newSetupStatusResource()
.withId(13L)
.withClassName(Question.class.getName(), Application.class.getName())
.withClassPk(questionId, 14L)
.withTargetClassName(Competition.class.getName(), Competition.class.getName())
.withTargetId(competitionId, competitionId)
.withParentId(12L, 12L)
.withCompleted(Boolean.FALSE, Boolean.TRUE).build(2);
final SetupStatusResource parentSectionStatus = newSetupStatusResource()
.withId(12L)
.withClassName(parentSection.getClass().getName())
.withClassPk(parentSection.getId())
.withParentId()
.withTargetClassName(Competition.class.getName())
.withTargetId(competitionId)
.withCompleted(Boolean.FALSE).build();
when(setupStatusService.findSetupStatusAndTarget(parentSection.getClass().getName(), parentSection.getId(), Competition.class.getName(), competitionId))
.thenReturn(serviceSuccess(parentSectionStatus));
when(setupStatusService.findByTargetClassNameAndTargetIdAndParentId(Competition.class.getName(), competitionId, parentSectionStatus.getId()))
.thenReturn(serviceSuccess(foundStatuses));
Map<Long, Boolean> result = service.getQuestionStatuses(competitionId, parentSection).getSuccessObjectOrThrowException();
verify(setupStatusService, times(1)).findByTargetClassNameAndTargetIdAndParentId(Competition.class.getName(), competitionId, parentSectionStatus.getId());
verify(setupStatusService, times(1)).findSetupStatusAndTarget(parentSection.getClass().getName(), parentSection.getId(), Competition.class.getName(), competitionId);
assertEquals(1, result.size());
assertEquals(false, result.get(questionId));
}
}
|
// This file is part of the OpenNMS(R) Application.
// reserved.
// OpenNMS(R) is a derivative work, containing both original code, included
// code and modified
// for modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
// Tab Size = 8
package org.opennms.netmgt.syslogd.jmx;
public class Syslogd implements SyslogdMBean {
public void init() {
org.opennms.netmgt.syslogd.Syslogd.getInstance().init();
}
public void start() {
org.opennms.netmgt.syslogd.Syslogd.getInstance().start();
}
public void stop() {
org.opennms.netmgt.syslogd.Syslogd.getInstance().stop();
}
public int getStatus() {
return org.opennms.netmgt.syslogd.Syslogd.getInstance().getStatus();
}
public String status() {
return org.opennms.core.fiber.Fiber.STATUS_NAMES[getStatus()];
}
public String getStatusText() {
return org.opennms.core.fiber.Fiber.STATUS_NAMES[getStatus()];
}
}
|
package org.innovateuk.ifs.competition.transactional;
import org.innovateuk.ifs.BaseServiceUnitTest;
import org.innovateuk.ifs.application.constant.ApplicationStatusConstants;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.domain.ApplicationStatistics;
import org.innovateuk.ifs.application.domain.FundingDecisionStatus;
import org.innovateuk.ifs.assessment.domain.Assessment;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.resource.*;
import org.innovateuk.ifs.invite.domain.CompetitionParticipant;
import org.innovateuk.ifs.invite.domain.ParticipantStatus;
import org.innovateuk.ifs.workflow.domain.ActivityState;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.EnumSet;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.EnumSet.of;
import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication;
import static org.innovateuk.ifs.application.builder.ApplicationStatisticsBuilder.newApplicationStatistics;
import static org.innovateuk.ifs.application.transactional.ApplicationSummaryServiceImpl.CREATED_AND_OPEN_STATUS_IDS;
import static org.innovateuk.ifs.application.transactional.ApplicationSummaryServiceImpl.SUBMITTED_STATUS_IDS;
import static org.innovateuk.ifs.assessment.builder.AssessmentBuilder.newAssessment;
import static org.innovateuk.ifs.assessment.builder.CompetitionParticipantBuilder.newCompetitionParticipant;
import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition;
import static org.innovateuk.ifs.competition.builder.CompetitionClosedKeyStatisticsResourceBuilder.newCompetitionClosedKeyStatisticsResource;
import static org.innovateuk.ifs.competition.builder.CompetitionInAssessmentKeyStatisticsResourceBuilder.newCompetitionInAssessmentKeyStatisticsResource;
import static org.innovateuk.ifs.competition.builder.CompetitionOpenKeyStatisticsResourceBuilder.newCompetitionOpenKeyStatisticsResource;
import static org.innovateuk.ifs.competition.builder.CompetitionReadyToOpenKeyStatisticsResourceBuilder.newCompetitionReadyToOpenKeyStatisticsResource;
import static org.innovateuk.ifs.invite.constant.InviteStatus.OPENED;
import static org.innovateuk.ifs.invite.constant.InviteStatus.SENT;
import static org.innovateuk.ifs.invite.domain.CompetitionParticipantRole.ASSESSOR;
import static org.innovateuk.ifs.workflow.domain.ActivityType.APPLICATION_ASSESSMENT;
import static org.innovateuk.ifs.workflow.resource.State.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
public class CompetitionKeyStatisticsServiceImplTest extends BaseServiceUnitTest<CompetitionKeyStatisticsServiceImpl> {
@Override
protected CompetitionKeyStatisticsServiceImpl supplyServiceUnderTest() {
return new CompetitionKeyStatisticsServiceImpl();
}
@Test
public void getReadyToOpenKeyStatisticsByCompetition() throws Exception {
Long competitionId = 1L;
CompetitionReadyToOpenKeyStatisticsResource keyStatisticsResource = newCompetitionReadyToOpenKeyStatisticsResource()
.withAssessorsAccepted(1)
.withAssessorsInvited(2)
.build();
when(competitionInviteRepositoryMock.countByCompetitionIdAndStatusIn(competitionId, EnumSet.of(OPENED, SENT))).thenReturn(keyStatisticsResource.getAssessorsInvited());
when(competitionParticipantRepositoryMock.countByCompetitionIdAndRoleAndStatus(competitionId, ASSESSOR, ParticipantStatus.ACCEPTED)).thenReturn(keyStatisticsResource.getAssessorsAccepted());
CompetitionReadyToOpenKeyStatisticsResource response = service.getReadyToOpenKeyStatisticsByCompetition(competitionId).getSuccessObjectOrThrowException();
assertEquals(keyStatisticsResource, response);
}
@Test
public void getOpenKeyStatisticsByCompetition() throws Exception {
Long competitionId = 1L;
CompetitionOpenKeyStatisticsResource keyStatisticsResource = newCompetitionOpenKeyStatisticsResource()
.withAssessorsAccepted(1)
.withAssessorsInvited(2)
.withApplicationsPastHalf(3)
.withApplicationsPerAssessor(4)
.withApplicationsStarted(5)
.withApplicationsSubmitted(6)
.build();
Competition competition = newCompetition()
.withAssessorCount(4)
.build();
BigDecimal limit = new BigDecimal(50L);
when(competitionInviteRepositoryMock.countByCompetitionIdAndStatusIn(competitionId, EnumSet.of(OPENED, SENT))).thenReturn(keyStatisticsResource.getAssessorsInvited());
when(competitionParticipantRepositoryMock.countByCompetitionIdAndRoleAndStatus(competitionId, ASSESSOR, ParticipantStatus.ACCEPTED)).thenReturn(keyStatisticsResource.getAssessorsAccepted());
when(competitionRepositoryMock.findById(competitionId)).thenReturn(competition);
when(applicationRepositoryMock.countByCompetitionIdAndApplicationStatusIdInAndCompletionLessThanEqual(competitionId, CREATED_AND_OPEN_STATUS_IDS, limit)).thenReturn(keyStatisticsResource.getApplicationsStarted());
when(applicationRepositoryMock.countByCompetitionIdAndApplicationStatusIdNotInAndCompletionGreaterThan(competitionId, SUBMITTED_STATUS_IDS, limit)).thenReturn(keyStatisticsResource.getApplicationsPastHalf());
when(applicationRepositoryMock.countByCompetitionIdAndApplicationStatusIdIn(competitionId, SUBMITTED_STATUS_IDS)).thenReturn(keyStatisticsResource.getApplicationsSubmitted());
CompetitionOpenKeyStatisticsResource response = service.getOpenKeyStatisticsByCompetition(competitionId).getSuccessObjectOrThrowException();
assertEquals(keyStatisticsResource, response);
}
@Test
public void getClosedKeyStatisticsByCompetition() throws Exception {
long competitionId = 1L;
CompetitionClosedKeyStatisticsResource keyStatisticsResource = newCompetitionClosedKeyStatisticsResource()
.withAssessorsInvited(5)
.withAssessorsAccepted(6)
.withApplicationsPerAssessor(2)
.withApplicationsRequiringAssessors(2)
.withAssessorsWithoutApplications(2)
.withAssignmentCount(3)
.build();
Competition competition = newCompetition()
.withAssessorCount(2)
.build();
List<Assessment> assessments = newAssessment()
.withActivityState(
new ActivityState(APPLICATION_ASSESSMENT, PENDING),
new ActivityState(APPLICATION_ASSESSMENT, REJECTED),
new ActivityState(APPLICATION_ASSESSMENT, OPEN))
.build(3);
List<Assessment> assessmentList = newAssessment()
.withActivityState(new ActivityState(APPLICATION_ASSESSMENT, SUBMITTED))
.build(1);
List<ApplicationStatistics> applicationStatistics = newApplicationStatistics()
.withAssessments(assessments, assessmentList, emptyList())
.build(3);
List<CompetitionParticipant> competitionParticipants = newCompetitionParticipant()
.withId(1L, 2L, 3L)
.build(3);
when(assessmentRepositoryMock.countByParticipantUserIdAndActivityStateStateNotIn(1L, of(REJECTED, WITHDRAWN))).thenReturn(0L);
when(assessmentRepositoryMock.countByParticipantUserIdAndActivityStateStateNotIn(2L, of(REJECTED, WITHDRAWN))).thenReturn(2L);
when(assessmentRepositoryMock.countByParticipantUserIdAndActivityStateStateNotIn(3L, of(REJECTED, WITHDRAWN))).thenReturn(0L);
when(competitionRepositoryMock.findById(competitionId)).thenReturn(competition);
when(applicationStatisticsRepositoryMock.findByCompetition(competitionId)).thenReturn(applicationStatistics);
when(competitionParticipantRepositoryMock.getByCompetitionIdAndRoleAndStatus(competitionId, ASSESSOR, ParticipantStatus.ACCEPTED)).thenReturn(competitionParticipants);
when(applicationStatisticsRepositoryMock.findByCompetition(competitionId)).thenReturn(applicationStatistics);
when(competitionInviteRepositoryMock.countByCompetitionIdAndStatusIn(competitionId, EnumSet.of(OPENED, SENT))).thenReturn(keyStatisticsResource.getAssessorsInvited());
when(competitionParticipantRepositoryMock.countByCompetitionIdAndRoleAndStatus(competitionId, ASSESSOR, ParticipantStatus.ACCEPTED)).thenReturn(keyStatisticsResource.getAssessorsAccepted());
CompetitionClosedKeyStatisticsResource response = service.getClosedKeyStatisticsByCompetition(competitionId).getSuccessObjectOrThrowException();
assertEquals(keyStatisticsResource, response);
}
@Test
public void getInAssessmentKeyStatisticsByCompetition() throws Exception {
long competitionId = 1L;
CompetitionInAssessmentKeyStatisticsResource keyStatisticsResource = newCompetitionInAssessmentKeyStatisticsResource()
.withAssessmentsStarted(1)
.withAssessmentsSubmitted(2)
.withAssignmentCount(3)
.withAssignmentsAccepted(4)
.withAssignmentsWaiting(5)
.build();
List<Assessment> assessments = newAssessment()
.withActivityState(
new ActivityState(APPLICATION_ASSESSMENT, PENDING),
new ActivityState(APPLICATION_ASSESSMENT, REJECTED),
new ActivityState(APPLICATION_ASSESSMENT, OPEN))
.build(3);
List<Assessment> assessmentList = newAssessment()
.withActivityState(new ActivityState(APPLICATION_ASSESSMENT, SUBMITTED))
.build(1);
List<ApplicationStatistics> applicationStatistics = newApplicationStatistics()
.withAssessments(assessments, assessmentList)
.build(2);
when(applicationStatisticsRepositoryMock.findByCompetition(competitionId)).thenReturn(applicationStatistics);
when(assessmentRepositoryMock.countByActivityStateStateAndTargetCompetitionId(PENDING, competitionId)).thenReturn(keyStatisticsResource.getAssignmentsWaiting());
when(assessmentRepositoryMock.countByActivityStateStateAndTargetCompetitionId(ACCEPTED, competitionId)).thenReturn(keyStatisticsResource.getAssignmentsAccepted());
when(assessmentRepositoryMock.countByActivityStateStateInAndTargetCompetitionId(of(OPEN, DECIDE_IF_READY_TO_SUBMIT, READY_TO_SUBMIT), competitionId)).thenReturn(keyStatisticsResource.getAssessmentsStarted());
when(assessmentRepositoryMock.countByActivityStateStateAndTargetCompetitionId(SUBMITTED, competitionId)).thenReturn(keyStatisticsResource.getAssessmentsSubmitted());
CompetitionInAssessmentKeyStatisticsResource response = service.getInAssessmentKeyStatisticsByCompetition(competitionId).getSuccessObjectOrThrowException();
assertEquals(keyStatisticsResource, response);
}
@Test
public void getFundedKeyStatisticsByCompetition() throws Exception {
long competitionId = 1L;
int applicationsNotifiedOfDecision = 1;
int applicationsAwaitingDecision = 2;
List<Application> applications = newApplication()
.withApplicationStatus(ApplicationStatusConstants.SUBMITTED)
.withFundingDecision(FundingDecisionStatus.FUNDED, FundingDecisionStatus.UNFUNDED, FundingDecisionStatus.ON_HOLD)
.build(3);
when(applicationRepositoryMock.findByCompetitionIdAndApplicationStatusIdIn(competitionId, SUBMITTED_STATUS_IDS)).thenReturn(applications);
when(applicationRepositoryMock.countByCompetitionIdAndFundingDecisionIsNotNullAndManageFundingEmailDateIsNotNull(competitionId)).thenReturn(applicationsNotifiedOfDecision);
when(applicationRepositoryMock.countByCompetitionIdAndFundingDecisionIsNotNullAndManageFundingEmailDateIsNull(competitionId)).thenReturn(applicationsAwaitingDecision);
CompetitionFundedKeyStatisticsResource response = service.getFundedKeyStatisticsByCompetition(competitionId).getSuccessObjectOrThrowException();
assertEquals(3, response.getApplicationsSubmitted());
assertEquals(1, response.getApplicationsFunded());
assertEquals(1, response.getApplicationsNotFunded());
assertEquals(1, response.getApplicationsOnHold());
assertEquals(applicationsNotifiedOfDecision, response.getApplicationsNotifiedOfDecision());
assertEquals(applicationsAwaitingDecision, response.getApplicationsAwaitingDecision());
}
}
|
package org.caleydo.view.stratomex;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.datadomain.DataSupportDefinitions;
import org.caleydo.core.data.datadomain.IDataDomain;
import org.caleydo.core.data.datadomain.IDataSupportDefinition;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.data.perspective.variable.Perspective;
import org.caleydo.core.data.perspective.variable.PerspectiveInitializationData;
import org.caleydo.core.data.selection.EventBasedSelectionManager;
import org.caleydo.core.data.selection.IEventBasedSelectionManagerUser;
import org.caleydo.core.data.selection.SelectionManager;
import org.caleydo.core.data.selection.SelectionType;
import org.caleydo.core.data.selection.delta.SelectionDelta;
import org.caleydo.core.data.selection.events.SelectionCommandListener;
import org.caleydo.core.data.virtualarray.VirtualArray;
import org.caleydo.core.data.virtualarray.events.RecordVAUpdateEvent;
import org.caleydo.core.data.virtualarray.similarity.RelationAnalyzer;
import org.caleydo.core.event.EventListenerManager;
import org.caleydo.core.event.EventListenerManager.DeepScan;
import org.caleydo.core.event.EventListenerManager.ListenTo;
import org.caleydo.core.event.EventListenerManagers;
import org.caleydo.core.event.data.RelationsUpdatedEvent;
import org.caleydo.core.event.data.RemoveDataDomainEvent;
import org.caleydo.core.event.data.ReplaceTablePerspectiveEvent;
import org.caleydo.core.event.data.SelectionUpdateEvent;
import org.caleydo.core.event.view.TablePerspectivesChangedEvent;
import org.caleydo.core.id.IDCategory;
import org.caleydo.core.id.IDMappingManager;
import org.caleydo.core.id.IDMappingManagerRegistry;
import org.caleydo.core.id.IDType;
import org.caleydo.core.manager.GeneralManager;
import org.caleydo.core.serialize.ASerializedView;
import org.caleydo.core.util.collection.Pair;
import org.caleydo.core.util.logging.Logger;
import org.caleydo.core.view.IMultiTablePerspectiveBasedView;
import org.caleydo.core.view.listener.AddTablePerspectivesEvent;
import org.caleydo.core.view.listener.RemoveTablePerspectiveEvent;
import org.caleydo.core.view.listener.RemoveTablePerspectiveListener;
import org.caleydo.core.view.opengl.camera.CameraProjectionMode;
import org.caleydo.core.view.opengl.camera.ViewFrustum;
import org.caleydo.core.view.opengl.canvas.AGLView;
import org.caleydo.core.view.opengl.canvas.IGLCanvas;
import org.caleydo.core.view.opengl.canvas.listener.IViewCommandHandler;
import org.caleydo.core.view.opengl.canvas.remote.IGLRemoteRenderingView;
import org.caleydo.core.view.opengl.layout.Column;
import org.caleydo.core.view.opengl.layout.ElementLayout;
import org.caleydo.core.view.opengl.layout.LayoutManager;
import org.caleydo.core.view.opengl.layout.Row;
import org.caleydo.core.view.opengl.layout.util.ColorRenderer;
import org.caleydo.core.view.opengl.mouse.GLMouseListener;
import org.caleydo.core.view.opengl.picking.APickingListener;
import org.caleydo.core.view.opengl.picking.Pick;
import org.caleydo.core.view.opengl.util.GLCoordinateUtils;
import org.caleydo.core.view.opengl.util.draganddrop.DragAndDropController;
import org.caleydo.core.view.opengl.util.spline.ConnectionBandRenderer;
import org.caleydo.core.view.opengl.util.text.CaleydoTextRenderer;
import org.caleydo.core.view.opengl.util.texture.TextureManager;
import org.caleydo.data.loader.ResourceLoader;
import org.caleydo.datadomain.pathway.data.PathwayTablePerspective;
import org.caleydo.view.stratomex.brick.GLBrick;
import org.caleydo.view.stratomex.brick.configurer.CategoricalDataConfigurer;
import org.caleydo.view.stratomex.brick.configurer.IBrickConfigurer;
import org.caleydo.view.stratomex.brick.configurer.NumericalDataConfigurer;
import org.caleydo.view.stratomex.brick.contextmenu.SplitBrickItem;
import org.caleydo.view.stratomex.column.BrickColumn;
import org.caleydo.view.stratomex.column.BrickColumnManager;
import org.caleydo.view.stratomex.column.BrickColumnSpacingRenderer;
import org.caleydo.view.stratomex.event.AddGroupsToStratomexEvent;
import org.caleydo.view.stratomex.event.ConnectionsModeEvent;
import org.caleydo.view.stratomex.event.MergeBricksEvent;
import org.caleydo.view.stratomex.event.SelectElementsEvent;
import org.caleydo.view.stratomex.event.SplitBrickEvent;
import org.caleydo.view.stratomex.listener.AddGroupsToStratomexListener;
import org.caleydo.view.stratomex.listener.GLStratomexKeyListener;
import org.caleydo.view.stratomex.listener.ReplaceTablePerspectiveListener;
import org.caleydo.view.stratomex.tourguide.TourguideAdapter;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Composite;
/**
* VisBricks main view
*
* @author Marc Streit
* @author Alexander Lex
*/
public class GLStratomex extends AGLView implements IMultiTablePerspectiveBasedView, IGLRemoteRenderingView,
IViewCommandHandler, IEventBasedSelectionManagerUser {
public static final String VIEW_TYPE = "org.caleydo.view.stratomex";
public static final String VIEW_NAME = "StratomeX";
private final static int ARCH_PIXEL_HEIGHT = 100;
private final static int ARCH_PIXEL_WIDTH = 80;
private final static float ARCH_BOTTOM_PERCENT = 1f;
private final static float ARCH_STAND_WIDTH_PERCENT = 0.05f;
private final static int BRICK_COLUMN_SPACING_MIN_PIXEL_WIDTH = 20;
public final static int BRICK_COLUMN_SIDE_SPACING = 50;
public final static float[] ARCH_COLOR = { 0f, 0f, 0f, 0.1f };
private AddGroupsToStratomexListener addGroupsToStratomexListener;
private SelectionCommandListener selectionCommandListener;
private RemoveTablePerspectiveListener<GLStratomex> removeTablePerspectiveListener;
private ReplaceTablePerspectiveListener replaceTablePerspectiveListener;
private final EventListenerManager listeners = EventListenerManagers.wrap(this);
private BrickColumnManager brickColumnManager;
private ConnectionBandRenderer connectionRenderer;
private LayoutManager layoutManager;
private Row mainRow;
private Row centerRowLayout;
private Column leftColumnLayout;
private Column rightColumnLayout;
/** thickness of the arch at the sides */
private float archSideWidth = 0;
private float archInnerWidth = 0;
private float archTopY = 0;
private float archBottomY = 0;
private float archHeight = 0;
/** Flag signaling if a group needs to be moved out of the center */
boolean resizeNecessary = false;
boolean lastResizeDirectionWasToLeft = true;
boolean isLayoutDirty = false;
/** Flag telling whether a detail is shown left of its dimension group */
private boolean isLeftDetailShown = false;
/** Same as {@link #isLeftDetailShown} for right */
private boolean isRightDetailShown = false;
private Queue<BrickColumn> uninitializedSubViews = new LinkedList<>();
private DragAndDropController dragAndDropController;
private RelationAnalyzer relationAnalyzer;
private ElementLayout leftBrickColumnSpacing;
private ElementLayout rightBrickColumnSpacing;
/**
* The id category used to map between the records of the dimension groups. Only data with the same recordIDCategory
* can be connected
*/
private IDCategory recordIDCategory;
/**
* The selection manager for the records, used for highlighting the visual links
*/
private EventBasedSelectionManager recordSelectionManager;
private boolean connectionsOn = true;
private boolean connectionsHighlightDynamic = false;
private int selectedConnectionBandID = -1;
/**
* Determines the connection focus highlight dynamically in a range between 0 and 1
*/
private float connectionsFocusFactor;
private boolean isHorizontalMoveDraggingActive = false;
private int movedBrickColumn = -1;
/**
* The position of the mouse in the previous render cycle when dragging columns
*/
private float previousXCoordinate = Float.NaN;
/**
* If the mouse is dragged further out to the left than possible, this is set to where it was
*/
private float leftLimitXCoordinate = Float.NaN;
/** Same as {@link #leftLimitXCoordinate} for the right side */
private float rightLimitXCoordinate = Float.NaN;
/** Needed for selecting the elements when a connection band is picked **/
private HashMap<Integer, BrickConnection> hashConnectionBandIDToRecordVA = new HashMap<Integer, BrickConnection>();
private HashMap<Perspective, HashMap<Perspective, BrickConnection>> hashRowPerspectivesToConnectionBandID = new HashMap<Perspective, HashMap<Perspective, BrickConnection>>();
private int connectionBandIDCounter = 0;
private boolean isConnectionLinesDirty = true;
private List<TablePerspective> tablePerspectives;
@DeepScan
private TourguideAdapter tourguide;
/**
* Constructor.
*
*/
public GLStratomex(IGLCanvas glCanvas, Composite parentComposite, ViewFrustum viewFrustum) {
super(glCanvas, parentComposite, viewFrustum, VIEW_TYPE, VIEW_NAME);
connectionRenderer = new ConnectionBandRenderer();
dragAndDropController = new DragAndDropController(this);
brickColumnManager = new BrickColumnManager();
glKeyListener = new GLStratomexKeyListener();
relationAnalyzer = new RelationAnalyzer();
tablePerspectives = new ArrayList<TablePerspective>();
textureManager = new TextureManager(new ResourceLoader(Activator.getResourceLocator()));
tourguide = new TourguideAdapter(this);
registerPickingListeners();
}
/**
* @return the tourguide, see {@link #tourguide}
*/
public TourguideAdapter getTourguide() {
return tourguide;
}
@Override
public void init(GL2 gl) {
displayListIndex = gl.glGenLists(1);
textRenderer = new CaleydoTextRenderer(24);
connectionRenderer.init(gl);
layoutManager = new LayoutManager(viewFrustum, pixelGLConverter);
mainRow = new Row();
layoutManager.setBaseElementLayout(mainRow);
leftColumnLayout = new Column("leftArchColumn");
leftColumnLayout.setPixelSizeX(ARCH_PIXEL_WIDTH);
rightColumnLayout = new Column("rightArchColumn");
rightColumnLayout.setPixelSizeX(ARCH_PIXEL_WIDTH);
}
public void initLayouts() {
brickColumnManager.getBrickColumnSpacers().clear();
mainRow.clear();
if (!isLeftDetailShown && !isRightDetailShown) {
initLeftLayout();
}
initCenterLayout();
if (!isLeftDetailShown && !isRightDetailShown) {
initRightLayout();
}
layoutManager.updateLayout();
updateConnectionLinesBetweenColumns();
}
private void initLeftLayout() {
initSideLayout(leftColumnLayout, 0, brickColumnManager.getCenterColumnStartIndex());
}
private void initRightLayout() {
initSideLayout(rightColumnLayout, brickColumnManager.getRightColumnStartIndex(), brickColumnManager
.getBrickColumns().size());
}
public int getSideArchWidthPixels() {
return pixelGLConverter.getPixelWidthForGLWidth(viewFrustum.getWidth() * ARCH_STAND_WIDTH_PERCENT);
}
/**
* Init the layout for the center region, showing the horizontal bar of the arch plus all sub-bricks above and below
*/
private void initCenterLayout() {
archSideWidth = viewFrustum.getWidth() * ARCH_STAND_WIDTH_PERCENT;
if (isRightDetailShown || isLeftDetailShown) {
archInnerWidth = 0;
} else {
archInnerWidth = viewFrustum.getWidth() * (ARCH_STAND_WIDTH_PERCENT + 0.024f);
}
archHeight = pixelGLConverter.getGLHeightForPixelHeight(ARCH_PIXEL_HEIGHT);
archBottomY = viewFrustum.getHeight() * ARCH_BOTTOM_PERCENT - archHeight;
archTopY = archBottomY + archHeight;
centerRowLayout = new Row("centerRowLayout");
centerRowLayout.setPriorityRendereing(true);
centerRowLayout.setFrameColor(0, 0, 1, 1);
List<Object> columns = new ArrayList<>();
for (int columnIndex = brickColumnManager.getCenterColumnStartIndex(); columnIndex < brickColumnManager
.getRightColumnStartIndex(); columnIndex++) {
BrickColumn column = brickColumnManager.getBrickColumns().get(columnIndex);
column.setCollapsed(false);
column.setArchHeight(ARCH_PIXEL_HEIGHT);
columns.add(column);
}
tourguide.addTemplateColumns(columns);
mainRow.append(centerRowLayout);
// Handle special case where center contains no groups
if (columns.isEmpty()) {
leftBrickColumnSpacing = new ElementLayout("firstCenterDimGrSpacing");
leftBrickColumnSpacing.setRenderer(new BrickColumnSpacingRenderer(null, connectionRenderer, null, null,
this));
leftBrickColumnSpacing.setGrabX(true);
centerRowLayout.append(leftBrickColumnSpacing);
return;
}
leftBrickColumnSpacing = new ElementLayout("firstCenterDimGrSpacing");
leftBrickColumnSpacing.setRenderer(new BrickColumnSpacingRenderer(null, connectionRenderer, null,
asBrickColumn(columns.get(0)), this));
if (columns.size() > 1)
leftBrickColumnSpacing.setPixelSizeX(BRICK_COLUMN_SIDE_SPACING);
else
leftBrickColumnSpacing.setGrabX(true);
centerRowLayout.append(leftBrickColumnSpacing);
BrickColumn last = null;
for (int i = 0; i < columns.size(); ++i) {
Object elem = columns.get(i);
BrickColumn column = asBrickColumn(elem);
if (i > 0) { // not the last one
ElementLayout dynamicColumnSpacing = new ElementLayout("dynamicDimGrSpacing");
dynamicColumnSpacing.setGrabX(true);
dynamicColumnSpacing.setRenderer(new BrickColumnSpacingRenderer(relationAnalyzer, connectionRenderer,
last, column, this));
centerRowLayout.append(dynamicColumnSpacing);
}
if (elem instanceof BrickColumn) {
centerRowLayout.add(((BrickColumn) elem).getLayout());
} else if (elem instanceof ElementLayout) {
centerRowLayout.add((ElementLayout) elem);
}
last = column;
}
rightBrickColumnSpacing = new ElementLayout("lastDimGrSpacing");
rightBrickColumnSpacing.setRenderer(new BrickColumnSpacingRenderer(null, connectionRenderer, last, null, this));
if (columns.size() > 1)
rightBrickColumnSpacing.setPixelSizeX(BRICK_COLUMN_SIDE_SPACING);
else
rightBrickColumnSpacing.setGrabX(true);
centerRowLayout.append(rightBrickColumnSpacing);
}
private static BrickColumn asBrickColumn(Object obj) {
return obj instanceof BrickColumn ? ((BrickColumn) obj) : null;
}
/**
* Initialize the layout for the sides of the arch
*
* @param columnLayout
* @param layoutTemplate
* @param layoutManager
* @param columnStartIndex
* @param columnEndIndex
*/
private void initSideLayout(Column columnLayout, int columnStartIndex, int columnEndIndex) {
columnLayout.setFrameColor(1, 1, 0, 1);
columnLayout.setBottomUp(true);
columnLayout.clear();
columnLayout.setRenderer(new ColorRenderer(new float[] { 0.7f, 0.7f, 0.7f, 1f }));
ElementLayout columnSpacing = new ElementLayout("firstSideDimGrSpacing");
columnSpacing.setGrabY(true);
columnLayout.append(columnSpacing);
BrickColumnSpacingRenderer brickColumnSpacingRenderer = null;
// Handle special case where arch stand contains no groups
if (columnStartIndex == 0 || columnStartIndex == columnEndIndex) {
brickColumnSpacingRenderer = new BrickColumnSpacingRenderer(null, connectionRenderer, null, null, this);
} else {
brickColumnSpacingRenderer = new BrickColumnSpacingRenderer(null, connectionRenderer, null,
brickColumnManager.getBrickColumns().get(brickColumnManager.getCenterColumnStartIndex()), this);
}
columnSpacing.setRenderer(brickColumnSpacingRenderer);
brickColumnSpacingRenderer.setVertical(false);
for (int columnIndex = columnStartIndex; columnIndex < columnEndIndex; columnIndex++) {
BrickColumn column = brickColumnManager.getBrickColumns().get(columnIndex);
column.getLayout().setAbsoluteSizeY(archSideWidth);
column.setArchHeight(-1);
columnLayout.append(column.getLayout());
column.setCollapsed(true);
columnSpacing = new ElementLayout("sideDimGrSpacing");
columnSpacing.setGrabY(true);
brickColumnSpacingRenderer = new BrickColumnSpacingRenderer(null, null, column, null, this);
columnLayout.append(columnSpacing);
columnSpacing.setRenderer(brickColumnSpacingRenderer);
brickColumnSpacingRenderer.setVertical(false);
}
mainRow.append(columnLayout);
}
@Override
public void initLocal(GL2 gl) {
// Register keyboard listener to GL2 canvas
parentComposite.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
parentComposite.addKeyListener(glKeyListener);
}
});
init(gl);
}
@Override
public void initRemote(final GL2 gl, final AGLView glParentView, final GLMouseListener glMouseListener) {
this.glMouseListener = glMouseListener;
init(gl);
initLayouts();
}
@Override
public void displayLocal(GL2 gl) {
pickingManager.handlePicking(this, gl);
display(gl);
if (!lazyMode) {
checkForHits(gl);
}
}
@Override
public void displayRemote(GL2 gl) {
display(gl);
}
@Override
public void display(GL2 gl) {
if ((tablePerspectives == null || tablePerspectives.isEmpty()) && tourguide.isEmpty()) {
if (isDisplayListDirty) {
gl.glNewList(displayListIndex, GL2.GL_COMPILE);
tourguide.renderStartButton(gl, 0, getArchTopY(), getViewFrustum().getWidth(), getArchBottomY()
- getArchTopY(), 0);
if (tourguide.hasTourGuide()) {
renderEmptyViewText(gl, new String[] { "To add a column showing a dataset",
" click the \"+\" button at the top", "or use the TourGuide or the DVI", "",
"Refer to http://help.caleydo.org for more information." });
} else {
renderEmptyViewText(gl, new String[] { "Please use the Data-View Integrator to assign ",
"one or multiple dataset(s) to StratomeX.",
"Refer to http://help.caleydo.org for more information." });
}
gl.glEndList();
isDisplayListDirty = false;
}
gl.glCallList(displayListIndex);
} else {
if (!uninitializedSubViews.isEmpty()) {
while (uninitializedSubViews.peek() != null) {
uninitializedSubViews.poll().initRemote(gl, this, glMouseListener);
}
initLayouts();
}
// if (isDisplayListDirty) {
// buildDisplayList(gl, displayListIndex);
// isDisplayListDirty = false;
for (BrickColumn group : brickColumnManager.getBrickColumns()) {
group.processEvents();
}
handleHorizontalColumnMove(gl);
if (isLayoutDirty) {
isLayoutDirty = false;
layoutManager.updateLayout();
float minWidth = pixelGLConverter.getGLWidthForPixelWidth(BRICK_COLUMN_SPACING_MIN_PIXEL_WIDTH);
for (ElementLayout layout : centerRowLayout) {
if (!(layout.getRenderer() instanceof BrickColumnSpacingRenderer))
continue;
if (resizeNecessary)
break;
if (layout.getSizeScaledX() < minWidth - 0.01f) {
resizeNecessary = true;
break;
}
}
}
if (resizeNecessary) {
// int size = centerRowLayout.size();
// if (size >= 3) {
// if (lastResizeDirectionWasToLeft) {
// dimensionGroupManager.setCenterGroupStartIndex(dimensionGroupManager
// .getCenterGroupStartIndex() + 1);
// float width =
// centerRowLayout.getElements().get(0).getSizeScaledX()
// + centerRowLayout.getElements().get(1).getSizeScaledX()
// + centerRowLayout.getElements().get(2).getSizeScaledX();
// centerRowLayout.remove(0);
// centerRowLayout.remove(0);
// leftDimensionGroupSpacing =
// centerRowLayout.getElements().get(0);
// leftDimensionGroupSpacing.setAbsoluteSizeX(width);
// ((DimensionGroupSpacingRenderer) leftDimensionGroupSpacing
// .getRenderer()).setLeftDimGroup(null);
// initLeftLayout();
// // if (size == 3)
// // leftDimensionGroupSpacing.setGrabX(true);
// } else {
// dimensionGroupManager.setRightGroupStartIndex(dimensionGroupManager
// .getRightGroupStartIndex() - 1);
// // float width = centerRowLayout.getElements().get(size - 1)
// // .getSizeScaledX()
// // + centerRowLayout.getElements().get(size - 2)
// // .getSizeScaledX()
// // + centerRowLayout.getElements().get(size - 3)
// // .getSizeScaledX();
// centerRowLayout.remove(centerRowLayout.size() - 1);
// centerRowLayout.remove(centerRowLayout.size() - 1);
// rightDimensionGroupSpacing =
// centerRowLayout.getElements().get(
// centerRowLayout.size() - 1);
// // rightDimensionGroupSpacing.setAbsoluteSizeX(width);
// rightDimensionGroupSpacing.setGrabX(true);
// ((DimensionGroupSpacingRenderer) rightDimensionGroupSpacing
// .getRenderer()).setRightDimGroup(null);
// initRightLayout();
// // if (size == 3)
// // rightDimensionGroupSpacing.setGrabX(true);
// centerLayoutManager.updateLayout();
resizeNecessary = false;
}
for (BrickColumn column : brickColumnManager.getBrickColumns()) {
column.display(gl);
}
if (isConnectionLinesDirty) {
performConnectionLinesUpdate();
}
layoutManager.render(gl);
// if (!isRightDetailShown && !isLeftDetailShown) {
// gl.glCallList(displayListIndex);
// call after all other rendering because it calls the onDrag
// methods
// which need alpha blending...
dragAndDropController.handleDragging(gl, glMouseListener);
}
}
/**
* Switches to detail mode where the detail brick is on the right side of the specified column
*
* @param focusColumn
* the column that contains the focus brick
*/
public void switchToDetailModeRight(BrickColumn focusColumn) {
int columnIndex = brickColumnManager.indexOfBrickColumn(focusColumn);
// false only if this is the rightmost column. If true we
// move anything beyond the next column out
if (columnIndex != brickColumnManager.getRightColumnStartIndex() - 1) {
brickColumnManager.setRightColumnStartIndex(columnIndex + 2);
}
// false only if this is the leftmost colum. If true we
// move anything further left out
if (columnIndex != brickColumnManager.getCenterColumnStartIndex()) {
brickColumnManager.setCenterColumnStartIndex(columnIndex);
}
isRightDetailShown = true;
mainRow.remove(rightColumnLayout);
mainRow.remove(leftColumnLayout);
initLayouts();
setDisplayListDirty();
}
/**
* Switches to detail mode where the detail brick is on the left side of the specified column.
*
* @param focusColumn
* the column that contains the detail brick
*/
public void switchToDetailModeLeft(BrickColumn focusColumn) {
int columnIndex = brickColumnManager.indexOfBrickColumn(focusColumn);
// false only if this is the left-most column. If true we move
// out everything right of this column
if (columnIndex != brickColumnManager.getCenterColumnStartIndex()) {
brickColumnManager.setCenterColumnStartIndex(columnIndex - 1);
}
// false only if this is the right-most column
if (columnIndex != brickColumnManager.getRightColumnStartIndex() - 1) {
brickColumnManager.setRightColumnStartIndex(columnIndex + 1);
}
isLeftDetailShown = true;
mainRow.remove(rightColumnLayout);
mainRow.remove(leftColumnLayout);
initLayouts();
// layoutManager.updateLayout();
}
/**
* Hide the detail brick which is shown right of its parent dimension group
*/
public void switchToOverviewModeRight() {
isRightDetailShown = false;
initLayouts();
}
/**
* Hide the detail brick which is shown left of its parent dimension group
*/
public void switchToOverviewModeLeft() {
isLeftDetailShown = false;
initLayouts();
}
/**
* Handles the left-right dragging of the whole dimension group. Does collision handling and moves dimension groups
* to the sides if necessary.
*
* @param gl
*/
private void handleHorizontalColumnMove(GL2 gl) {
if (!isHorizontalMoveDraggingActive)
return;
if (glMouseListener.wasMouseReleased()) {
isHorizontalMoveDraggingActive = false;
previousXCoordinate = Float.NaN;
leftLimitXCoordinate = Float.NaN;
rightLimitXCoordinate = Float.NaN;
return;
}
Point currentPoint = glMouseListener.getPickedPoint();
float[] pointCordinates = GLCoordinateUtils.convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x,
currentPoint.y);
if (Float.isNaN(previousXCoordinate)) {
previousXCoordinate = pointCordinates[0];
return;
}
float change = pointCordinates[0] - previousXCoordinate;
// float change = -0.1f;
// isHorizontalMoveDraggingActive = false;
if (change > 0) {
if (change < 0.01f)
return;
lastResizeDirectionWasToLeft = false;
} else {
// ignore tiny changes
if (change > -0.01f)
return;
lastResizeDirectionWasToLeft = true;
}
if (!Float.isNaN(leftLimitXCoordinate)) {
if (leftLimitXCoordinate >= currentPoint.x)
return;
else
leftLimitXCoordinate = Float.NaN;
}
if (!Float.isNaN(rightLimitXCoordinate)) {
if (rightLimitXCoordinate <= currentPoint.x)
return;
else
rightLimitXCoordinate = Float.NaN;
}
previousXCoordinate = pointCordinates[0];
// the spacing left of the moved element
ElementLayout leftSpacing = null;
// the spacing right of the moved element
ElementLayout rightSpacing = null;
int leftIndex = 0;
int rightIndex = 0;
BrickColumnSpacingRenderer spacingRenderer;
int count = 0;
for (ElementLayout layout : centerRowLayout) {
if (layout.getRenderer() instanceof BrickColumnSpacingRenderer) {
spacingRenderer = (BrickColumnSpacingRenderer) layout.getRenderer();
if (spacingRenderer.getRightDimGroup() != null) {
if (spacingRenderer.getRightDimGroup().getID() == movedBrickColumn) {
leftSpacing = layout;
leftIndex = count;
}
}
if (spacingRenderer.getLeftDimGroup() != null) {
if (spacingRenderer.getLeftDimGroup().getID() == movedBrickColumn) {
rightSpacing = layout;
rightIndex = count;
}
}
if (count < centerRowLayout.size() - 1) {
layout.setGrabX(false);
layout.setAbsoluteSizeX(layout.getSizeScaledX());
} else
layout.setGrabX(true);
}
count++;
}
if (leftSpacing == null || rightSpacing == null)
return;
float leftSizeX = leftSpacing.getSizeScaledX();
float rightSizeX = rightSpacing.getSizeScaledX();
float minWidth = pixelGLConverter.getGLWidthForPixelWidth(BRICK_COLUMN_SPACING_MIN_PIXEL_WIDTH);
if (change > 0) {
// moved to the right, change is positive
if (rightSizeX - change > minWidth) {
// there is space, we adapt the spacings left and right
rightSpacing.setAbsoluteSizeX(rightSizeX - change);
leftSpacing.setAbsoluteSizeX(leftSizeX + change);
} else {
// the immediate neighbor doesn't have space, check for the
// following
rightSpacing.setAbsoluteSizeX(minWidth);
float savedSize = rightSizeX - minWidth;
float remainingChange = change - savedSize;
while (remainingChange > 0) {
if (centerRowLayout.size() < rightIndex + 2) {
rightLimitXCoordinate = currentPoint.x;
break;
}
rightIndex += 2;
ElementLayout spacing = centerRowLayout.get(rightIndex);
if (spacing.getSizeScaledX() - remainingChange > minWidth + 0.001f) {
spacing.setAbsoluteSizeX(spacing.getSizeScaledX() - remainingChange);
remainingChange = 0;
break;
} else {
savedSize = spacing.getSizeScaledX() - minWidth;
remainingChange -= savedSize;
if (rightIndex == centerRowLayout.size() - 1) {
rightLimitXCoordinate = currentPoint.x;
}
spacing.setAbsoluteSizeX(minWidth);
}
}
leftSpacing.setAbsoluteSizeX(leftSizeX + change - remainingChange);
}
} else {
// moved to the left, change is negative
if (leftSizeX + change > minWidth) {
// there is space, we adapt the spacings left and right
leftSpacing.setAbsoluteSizeX(leftSizeX + change);
rightSpacing.setAbsoluteSizeX(rightSizeX - change);
} else {
// the immediate neighbor doesn't have space, check for the
// following
leftSpacing.setAbsoluteSizeX(minWidth);
float savedSize = leftSizeX - minWidth;
float remainingChange = change + savedSize;
while (remainingChange < 0) {
if (leftIndex < 2) {
// if (leftIndex == 0) {
leftLimitXCoordinate = currentPoint.x;
break;
}
leftIndex -= 2;
ElementLayout spacing = centerRowLayout.get(leftIndex);
if (spacing.getSizeScaledX() + remainingChange > minWidth + 0.001f) {
// the whole change fits in the first spacing left of
// the source
spacing.setAbsoluteSizeX(spacing.getSizeScaledX() + remainingChange);
remainingChange = 0;
break;
} else {
savedSize = spacing.getSizeScaledX() - minWidth;
remainingChange += savedSize;
if (leftIndex == 0) {
leftLimitXCoordinate = currentPoint.x;
}
spacing.setAbsoluteSizeX(minWidth);
}
}
rightSpacing.setAbsoluteSizeX(rightSizeX - change + remainingChange);
}
}
setLayoutDirty();
}
protected void registerPickingListeners() {
addTypePickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
selectedConnectionBandID = pick.getObjectID();
selectElementsByConnectionBandID(selectedConnectionBandID);
}
@Override
public void rightClicked(Pick pick) {
contextMenuCreator.addContextMenuItem(new SplitBrickItem(pick.getObjectID(), true));
contextMenuCreator.addContextMenuItem(new SplitBrickItem(pick.getObjectID(), false));
}
}, EPickingType.BRICK_CONNECTION_BAND.name());
addTypePickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
dragAndDropController.clearDraggables();
dragAndDropController.setDraggingStartPosition(pick.getPickedPoint());
dragAndDropController.addDraggable((BrickColumn) generalManager.getViewManager().getGLView(
pick.getObjectID()));
dragAndDropController.setDraggingMode("DimensionGroupDrag");
}
// @Override
// public void dragged(Pick pick) {
// if (dragAndDropController.hasDraggables()) {
// String draggingMode = dragAndDropController.getDraggingMode();
// if (glMouseListener.wasRightMouseButtonPressed())
// dragAndDropController.clearDraggables();
// else if (!dragAndDropController.isDragging() && draggingMode !=
// null
// && draggingMode.equals("DimensionGroupDrag"))
// dragAndDropController.startDragging();
}, EPickingType.DIMENSION_GROUP.name());
addTypePickingListener(new APickingListener() {
@Override
public void dragged(Pick pick) {
if (dragAndDropController.isDragging() && dragAndDropController.getDraggingMode() != null
&& dragAndDropController.getDraggingMode().equals("DimensionGroupDrag")) {
dragAndDropController.setDropArea(brickColumnManager.getBrickColumnSpacers()
.get(pick.getObjectID()));
} else {
if (dragAndDropController.isDragging()) {
}
}
}
}, EPickingType.DIMENSION_GROUP_SPACER.name());
addTypePickingListener(new APickingListener() {
@Override
public void dragged(Pick pick) {
if (dragAndDropController.isDragging() && dragAndDropController.getDraggingMode() != null
&& dragAndDropController.getDraggingMode().equals("DimensionGroupDrag")) {
dragAndDropController.setDropArea(brickColumnManager.getBrickColumnSpacers()
.get(pick.getObjectID()));
} else {
if (dragAndDropController.isDragging()) {
}
}
}
@Override
protected void mouseOver(Pick pick) {
for (BrickColumnSpacingRenderer manager : brickColumnManager.getBrickColumnSpacers().values())
manager.setHeaderHovered(true);
super.mouseOver(pick);
}
@Override
protected void mouseOut(Pick pick) {
for (BrickColumnSpacingRenderer manager : brickColumnManager.getBrickColumnSpacers().values())
manager.setHeaderHovered(false);
super.mouseOut(pick);
}
}, EPickingType.DIMENSION_GROUP_SPACER_HEADER.name());
addTypePickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
isHorizontalMoveDraggingActive = true;
movedBrickColumn = pick.getObjectID();
}
}, EPickingType.MOVE_HORIZONTALLY_HANDLE.name());
tourguide.registerPickingListeners();
}
@Override
public ASerializedView getSerializableRepresentation() {
SerializedStratomexView serializedForm = new SerializedStratomexView(this);
serializedForm.setViewID(this.getID());
return serializedForm;
}
@Override
public String toString() {
return "StratomeX";
}
@Override
public void registerEventListeners() {
super.registerEventListeners();
addGroupsToStratomexListener = new AddGroupsToStratomexListener();
addGroupsToStratomexListener.setHandler(this);
eventPublisher.addListener(AddGroupsToStratomexEvent.class, addGroupsToStratomexListener);
eventPublisher.addListener(AddTablePerspectivesEvent.class, addGroupsToStratomexListener);
removeTablePerspectiveListener = new RemoveTablePerspectiveListener<>();
removeTablePerspectiveListener.setHandler(this);
eventPublisher.addListener(RemoveTablePerspectiveEvent.class, removeTablePerspectiveListener);
replaceTablePerspectiveListener = new ReplaceTablePerspectiveListener();
replaceTablePerspectiveListener.setHandler(this);
eventPublisher.addListener(ReplaceTablePerspectiveEvent.class, replaceTablePerspectiveListener);
listeners.register(this);
}
@Override
public void unregisterEventListeners() {
super.unregisterEventListeners();
if (addGroupsToStratomexListener != null) {
eventPublisher.removeListener(addGroupsToStratomexListener);
addGroupsToStratomexListener = null;
}
if (selectionCommandListener != null) {
eventPublisher.removeListener(selectionCommandListener);
selectionCommandListener = null;
}
if (removeTablePerspectiveListener != null) {
eventPublisher.removeListener(removeTablePerspectiveListener);
removeTablePerspectiveListener = null;
}
if (replaceTablePerspectiveListener != null) {
eventPublisher.removeListener(replaceTablePerspectiveListener);
replaceTablePerspectiveListener = null;
}
listeners.unregisterAll();
}
@Override
public void handleRedrawView() {
// TODO Auto-generated method stub
}
public void clearAllSelections() {
if (recordSelectionManager != null)
recordSelectionManager.clearSelections();
updateConnectionLinesBetweenColumns();
}
@Override
public List<AGLView> getRemoteRenderedViews() {
return new ArrayList<AGLView>(brickColumnManager.getBrickColumns());
}
@Override
public void addTablePerspective(TablePerspective tablePerspective) {
List<TablePerspective> tablePerspectiveWrapper = new ArrayList<TablePerspective>();
tablePerspectiveWrapper.add(tablePerspective);
addTablePerspectives(tablePerspectiveWrapper, null, null);
}
@Override
public void addTablePerspectives(List<TablePerspective> newTablePerspectives) {
addTablePerspectives(newTablePerspectives, null, null);
}
/**
* <p>
* Creates a column for each TablePerspective supplied
* </p>
* <p>
* As StratomeX can only map between data sets that share a mapping between records, the imprinting of the IDType
* and IDCategory for the records is done here if there is no data set yet.
* </p>
*
* @param newTablePerspectives
* @param brickConfigurer
* The brick configurer can be specified externally (e.g., pathways, kaplan meier). If null, the
* {@link NumericalDataConfigurer} will be used.
*/
public void addTablePerspectives(List<TablePerspective> newTablePerspectives, IBrickConfigurer brickConfigurer,
BrickColumn sourceColumn) {
addTablePerspectives(newTablePerspectives, brickConfigurer, sourceColumn, true);
}
public List<Pair<Integer, BrickColumn>> addTablePerspectives(List<TablePerspective> newTablePerspectives,
IBrickConfigurer brickConfigurer,
BrickColumn sourceColumn, boolean addRight) {
List<Pair<Integer, BrickColumn>> added = new ArrayList<>();
if (newTablePerspectives == null || newTablePerspectives.size() == 0) {
Logger.log(new Status(IStatus.WARNING, this.toString(),
"newTablePerspectives in addTablePerspectives was null or empty"));
return added;
}
// if this is the first data container set, we imprint StratomeX
if (recordIDCategory == null) {
ATableBasedDataDomain dataDomain = newTablePerspectives.get(0).getDataDomain();
imprintVisBricks(dataDomain);
}
ArrayList<BrickColumn> brickColumns = brickColumnManager.getBrickColumns();
for (TablePerspective tablePerspective : newTablePerspectives) {
if (tablePerspective == null) {
Logger.log(new Status(IStatus.ERROR, this.toString(), "Data container was null."));
continue;
}
if (!tablePerspective.getDataDomain().getTable().isDataHomogeneous() && brickConfigurer == null) {
Logger.log(new Status(IStatus.WARNING, this.toString(),
"Tried to add inhomogeneous table perspective without brick configurerer. Currently not supported."));
continue;
}
if (!tablePerspective.getDataDomain().getRecordIDCategory().equals(recordIDCategory)) {
Logger.log(new Status(IStatus.ERROR, this.toString(), "Data container " + tablePerspective
+ "does not match the recordIDCategory of Visbricks - no mapping possible."));
continue;
}
boolean columnExists = false;
for (BrickColumn brickColumn : brickColumns) {
if (brickColumn.getTablePerspective().getID() == tablePerspective.getID()) {
columnExists = true;
break;
}
}
if (!columnExists) {
BrickColumn brickColumn = createBrickColumn(brickConfigurer, tablePerspective);
int columnIndex;
if (sourceColumn == null)
columnIndex = addRight ? brickColumnManager.getRightColumnStartIndex() : brickColumnManager
.getCenterColumnStartIndex();
else
columnIndex = brickColumns.indexOf(sourceColumn) + 1;
added.add(Pair.make(columnIndex, brickColumn));
brickColumns.add(columnIndex, brickColumn);
tablePerspectives.add(tablePerspective);
// if (tablePerspective instanceof PathwayTablePerspective) {
// dataDomains.add(((PathwayTablePerspective) tablePerspective)
// .getPathwayDataDomain());
// } else {
// dataDomains.add(tablePerspective.getDataDomain());
brickColumnManager.setRightColumnStartIndex(brickColumnManager.getRightColumnStartIndex() + 1);
}
}
TablePerspectivesChangedEvent event = new TablePerspectivesChangedEvent(this);
event.setSender(this);
GeneralManager.get().getEventPublisher().triggerEvent(event);
return added;
}
/**
* @param tablePerspective
* @param brickConfigurer
* @return
*/
private BrickColumn createBrickColumn(IBrickConfigurer brickConfigurer, TablePerspective tablePerspective) {
BrickColumn brickColumn = (BrickColumn) GeneralManager
.get()
.getViewManager()
.createGLView(BrickColumn.class, getParentGLCanvas(), parentComposite,
new ViewFrustum(CameraProjectionMode.ORTHOGRAPHIC, 0, 1, 0, 1, -1, 1));
if (brickConfigurer == null) {
brickConfigurer = createDefaultBrickConfigurer(tablePerspective);
}
brickColumn.setDetailLevel(this.getDetailLevel());
brickColumn.setBrickConfigurer(brickConfigurer);
brickColumn.setDataDomain(tablePerspective != null ? tablePerspective.getDataDomain() : null);
brickColumn.setTablePerspective(tablePerspective);
brickColumn.setRemoteRenderingGLView(this);
brickColumn.setStratomex(this);
brickColumn.initialize();
uninitializedSubViews.add(brickColumn);
tourguide.addedBrickColumn(brickColumn);
return brickColumn;
}
public IBrickConfigurer createDefaultBrickConfigurer(TablePerspective tablePerspective) {
IBrickConfigurer brickConfigurer;
// FIXME this is a hack to make tablePerspectives that have
// only one dimension categorical data
if (tablePerspective.getNrDimensions() == 1) {
brickConfigurer = new CategoricalDataConfigurer(tablePerspective);
} else {
brickConfigurer = new NumericalDataConfigurer(tablePerspective);
}
return brickConfigurer;
}
@Override
public void removeTablePerspective(TablePerspective tablePerspective) {
Iterator<TablePerspective> tablePerspectiveIterator = tablePerspectives.iterator();
while (tablePerspectiveIterator.hasNext()) {
TablePerspective container = tablePerspectiveIterator.next();
if (container == tablePerspective) {
tablePerspectiveIterator.remove();
}
}
brickColumnManager.removeBrickColumn(tablePerspective.getID());
// remove uninitalized referenced
for (Iterator<BrickColumn> it = uninitializedSubViews.iterator(); it.hasNext();) {
if (it.next().getTablePerspective() == tablePerspective)
it.remove();
}
initLayouts();
TablePerspectivesChangedEvent event = new TablePerspectivesChangedEvent(this);
event.setSender(this);
GeneralManager.get().getEventPublisher().triggerEvent(event);
}
@ListenTo
private void removeDataDomain(RemoveDataDomainEvent event) {
String dataDomainID = event.getEventSpace();
List<TablePerspective> tmp = new ArrayList<>(getTablePerspectives());
for (TablePerspective p : tmp) {
if (dataDomainID.equals(p.getDataDomain().getDataDomainID()))
removeTablePerspective(p);
}
System.out.println();
}
@Override
public List<TablePerspective> getTablePerspectives() {
return tablePerspectives;
}
/**
* Replaces an old tablePerspective with a new one whil keeping the column at the same place.
*
* @param newTablePerspective
* @param oldTablePerspective
*/
public void replaceTablePerspective(TablePerspective newTablePerspective, TablePerspective oldTablePerspective) {
Iterator<TablePerspective> tablePerspectiveIterator = tablePerspectives.iterator();
while (tablePerspectiveIterator.hasNext()) {
TablePerspective tempPerspective = tablePerspectiveIterator.next();
if (tempPerspective.equals(oldTablePerspective)) {
tablePerspectiveIterator.remove();
}
}
tablePerspectives.add(newTablePerspective);
for (BrickColumn column : brickColumnManager.getBrickColumns()) {
if (column.getTablePerspective().equals(oldTablePerspective)) {
column.replaceTablePerspective(newTablePerspective);
}
}
TablePerspectivesChangedEvent event = new TablePerspectivesChangedEvent(this);
eventPublisher.triggerEvent(event);
}
/**
* Imprints VisBricks to a particular record ID Category by setting the {@link #recordIDCategory}, and initializes
* the {@link #recordSelectionManager}.
*
* @param dataDomain
*/
private void imprintVisBricks(ATableBasedDataDomain dataDomain) {
recordIDCategory = dataDomain.getRecordIDCategory();
IDType mappingRecordIDType = recordIDCategory.getPrimaryMappingType();
recordSelectionManager = new EventBasedSelectionManager(this, mappingRecordIDType);
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
super.reshape(drawable, x, y, width, height);
initLayouts();
updateLayout();
setLayoutDirty();
}
@Override
public void setDisplayListDirty() {
super.setDisplayListDirty();
}
public void moveColumn(BrickColumnSpacingRenderer spacer, BrickColumn movedColumn, BrickColumn referenceColumn) {
movedColumn.getLayout().reset();
clearColumnSpacerHighlight();
if (movedColumn == referenceColumn)
return;
boolean insertComplete = false;
ArrayList<BrickColumn> columns = brickColumnManager.getBrickColumns();
for (ElementLayout leftLayout : leftColumnLayout) {
if (spacer == leftLayout.getRenderer()) {
brickColumnManager.setCenterColumnStartIndex(brickColumnManager.getCenterColumnStartIndex() + 1);
columns.remove(movedColumn);
if (referenceColumn == null) {
columns.add(0, movedColumn);
} else {
columns.add(columns.indexOf(referenceColumn), movedColumn);
}
insertComplete = true;
break;
}
}
if (!insertComplete) {
for (ElementLayout rightLayout : rightColumnLayout) {
if (spacer == rightLayout.getRenderer()) {
brickColumnManager.setRightColumnStartIndex(brickColumnManager.getRightColumnStartIndex() - 1);
columns.remove(movedColumn);
if (referenceColumn == null) {
columns.add(columns.size(), movedColumn);
} else {
columns.add(columns.indexOf(referenceColumn) + 1, movedColumn);
}
insertComplete = true;
break;
}
}
}
if (!insertComplete) {
for (ElementLayout centerLayout : centerRowLayout) {
if (spacer == centerLayout.getRenderer()) {
if (columns.indexOf(movedColumn) < brickColumnManager.getCenterColumnStartIndex())
brickColumnManager
.setCenterColumnStartIndex(brickColumnManager.getCenterColumnStartIndex() - 1);
else if (columns.indexOf(movedColumn) >= brickColumnManager.getRightColumnStartIndex())
brickColumnManager.setRightColumnStartIndex(brickColumnManager.getRightColumnStartIndex() + 1);
columns.remove(movedColumn);
if (referenceColumn == null) {
columns.add(brickColumnManager.getCenterColumnStartIndex(), movedColumn);
} else {
columns.add(columns.indexOf(referenceColumn) + 1, movedColumn);
}
insertComplete = true;
break;
}
}
}
initLayouts();
RelationsUpdatedEvent event = new RelationsUpdatedEvent();
event.setSender(this);
eventPublisher.triggerEvent(event);
}
/** FIXME: documentation */
public void clearColumnSpacerHighlight() {
// Clear previous spacer highlights
for (ElementLayout element : centerRowLayout) {
if (element.getRenderer() instanceof BrickColumnSpacingRenderer)
((BrickColumnSpacingRenderer) element.getRenderer()).setRenderSpacer(false);
}
for (ElementLayout element : leftColumnLayout) {
if (element.getRenderer() instanceof BrickColumnSpacingRenderer)
((BrickColumnSpacingRenderer) element.getRenderer()).setRenderSpacer(false);
}
for (ElementLayout element : rightColumnLayout) {
if (element.getRenderer() instanceof BrickColumnSpacingRenderer)
((BrickColumnSpacingRenderer) element.getRenderer()).setRenderSpacer(false);
}
}
public BrickColumnManager getBrickColumnManager() {
return brickColumnManager;
}
public void updateConnectionLinesBetweenColumns() {
isConnectionLinesDirty = true;
}
private void performConnectionLinesUpdate() {
connectionBandIDCounter = 0;
if (centerRowLayout != null) {
for (ElementLayout elementLayout : centerRowLayout) {
if (elementLayout.getRenderer() instanceof BrickColumnSpacingRenderer) {
((BrickColumnSpacingRenderer) elementLayout.getRenderer()).init();
}
}
}
isConnectionLinesDirty = false;
}
public void setLayoutDirty() {
isLayoutDirty = true;
}
public void updateLayout() {
for (BrickColumn dimGroup : brickColumnManager.getBrickColumns()) {
dimGroup.updateLayout();
}
}
public void relayout() {
initLayouts();
setDisplayListDirty();
}
/**
* Set whether the last resize of any sub-brick was to the left(true) or to the right. Important for determining,
* which brick to kick next.
*
* @param lastResizeDirectionWasToLeft
*/
public void setLastResizeDirectionWasToLeft(boolean lastResizeDirectionWasToLeft) {
this.lastResizeDirectionWasToLeft = lastResizeDirectionWasToLeft;
}
public float getArchTopY() {
return archTopY;
}
public float getArchBottomY() {
return archBottomY;
}
public SelectionManager getRecordSelectionManager() {
return recordSelectionManager;
}
public GLStratomexKeyListener getKeyListener() {
return (GLStratomexKeyListener) glKeyListener;
}
@ListenTo
private void onHandleTrendHighlightMode(ConnectionsModeEvent event) {
this.connectionsOn = event.isConnectionsOn();
this.connectionsHighlightDynamic = event.isConnectionsHighlightDynamic();
this.connectionsFocusFactor = event.getFocusFactor();
updateConnectionLinesBetweenColumns();
}
public boolean isConnectionsOn() {
return connectionsOn;
}
public boolean isConnectionsHighlightDynamic() {
return connectionsHighlightDynamic;
}
public float getConnectionsFocusFactor() {
return connectionsFocusFactor;
}
public int getSelectedConnectionBandID() {
return selectedConnectionBandID;
}
/**
* @return the hashConnectionBandIDToRecordVA, see {@link #hashConnectionBandIDToRecordVA}
*/
public HashMap<Integer, BrickConnection> getHashConnectionBandIDToRecordVA() {
return hashConnectionBandIDToRecordVA;
}
/**
* @return the hashTablePerspectivesToConnectionBandID, see {@link #hashRowPerspectivesToConnectionBandID}
*/
public HashMap<Perspective, HashMap<Perspective, BrickConnection>> getHashTablePerspectivesToConnectionBandID() {
return hashRowPerspectivesToConnectionBandID;
}
public void selectElementsByConnectionBandID(Perspective recordPerspective1, Perspective recordPerspective2) {
BrickConnection connectionBand = null;
HashMap<Perspective, BrickConnection> tmp = hashRowPerspectivesToConnectionBandID.get(recordPerspective1);
if (tmp != null) {
connectionBand = tmp.get(recordPerspective2);
} else {
tmp = hashRowPerspectivesToConnectionBandID.get(recordPerspective2);
if (tmp != null)
connectionBand = tmp.get(recordPerspective1);
}
if (connectionBand != null)
selectElementsByConnectionBandID(connectionBand.getConnectionBandID());
}
public void selectElementsByConnectionBandID(int connectionBandID) {
BrickConnection connectionBand = hashConnectionBandIDToRecordVA.get(connectionBandID);
VirtualArray recordVA = connectionBand.getSharedRecordVirtualArray();
selectElements(recordVA, recordVA.getIdType(), connectionBand.getLeftBrick().getDataDomain().getDataDomainID(),
recordSelectionManager.getSelectionType());
}
@ListenTo(sendToMe = true)
private void onSelectElements(SelectElementsEvent event) {
selectElements(event.getIds(), event.getIdType(), event.getEventSpace(), event.getSelectionType());
}
public void selectElements(Iterable<Integer> ids, IDType idType, String dataDomainID, SelectionType selectionType) {
if (recordSelectionManager == null)
return;
if (!getKeyListener().isCtrlDown())
recordSelectionManager.clearSelection(selectionType);
for (Integer recordID : ids) {
recordSelectionManager.addToType(selectionType, idType, recordID);
}
SelectionUpdateEvent event = new SelectionUpdateEvent();
event.setSender(this);
SelectionDelta delta = recordSelectionManager.getDelta();
event.setSelectionDelta(delta);
// FIXME: actually we should not send a data domain in this case -
// however, if we don't send it, we don't see the selection in the
// selection info view. to fix this, we need to redesign the selection
// info view.
event.setEventSpace(dataDomainID);
eventPublisher.triggerEvent(event);
updateConnectionLinesBetweenColumns();
}
@ListenTo
private void onSplitBrick(SplitBrickEvent event) {
splitBrick(event.getConnectionBandID(), event.isSplitLeftBrick());
}
/**
* Splits a brick into two portions: those values that are in the band identified through the connection band id and
* the others.
*/
public void splitBrick(Integer connectionBandID, boolean isSplitLeftBrick) {
BrickConnection brickConnection = hashConnectionBandIDToRecordVA.get(connectionBandID);
VirtualArray sharedRecordVA = brickConnection.getSharedRecordVirtualArray();
Perspective sourcePerspective;
VirtualArray sourceVA;
Integer sourceGroupIndex;
GLBrick sourceBrick;
if (isSplitLeftBrick) {
sourceBrick = brickConnection.getLeftBrick();
} else {
sourceBrick = brickConnection.getRightBrick();
}
sourcePerspective = sourceBrick.getBrickColumn().getTablePerspective().getRecordPerspective();
sourceVA = sourcePerspective.getVirtualArray();
sourceGroupIndex = sourceBrick.getTablePerspective().getRecordGroup().getGroupIndex();
boolean idNeedsConverting = false;
if (!sourceVA.getIdType().equals(sharedRecordVA.getIdType())) {
idNeedsConverting = true;
// sharedRecordVA =
// sourceBrick.getDataDomain().convertForeignRecordPerspective(foreignPerspective)
}
List<Integer> remainingGroupIDs = new ArrayList<Integer>();
// this is necessary because the originalGroupIDs is backed by the
// original VA and changes in it also change the VA
for (Integer id : sourceVA.getIDsOfGroup(sourceGroupIndex)) {
remainingGroupIDs.add(id);
}
IDMappingManager idMappingManager = IDMappingManagerRegistry.get().getIDMappingManager(
sourceVA.getIdType().getIDCategory());
if (idNeedsConverting) {
VirtualArray mappedSharedRecordVA = new VirtualArray(sourceVA.getIdType());
for (Integer recordID : sharedRecordVA) {
recordID = idMappingManager.getID(sharedRecordVA.getIdType(), sourceVA.getIdType(), recordID);
if (recordID == null || recordID == -1)
continue;
mappedSharedRecordVA.append(recordID);
}
sharedRecordVA = mappedSharedRecordVA;
}
// remove the ids of the shared record va from the group which is beeing
// split
for (Integer recordID : sharedRecordVA) {
Iterator<Integer> remainingGroupIDIterator = remainingGroupIDs.iterator();
while (remainingGroupIDIterator.hasNext()) {
Integer id = remainingGroupIDIterator.next();
if (id.equals(recordID)) {
remainingGroupIDIterator.remove();
}
}
}
sourceVA.getGroupList().updateGroupInfo();
List<Integer> newIDs = new ArrayList<Integer>(sourceVA.size());
List<Integer> groupSizes = new ArrayList<Integer>(sourceVA.getGroupList().size() + 1);
List<String> groupNames = new ArrayList<String>(sourceVA.getGroupList().size() + 1);
List<Integer> sampleElements = new ArrayList<Integer>(sourceVA.getGroupList().size() + 1);
// build up the data for the perspective
int sizeCounter = 0;
for (Integer groupIndex = 0; groupIndex < sourceVA.getGroupList().size(); groupIndex++) {
if (groupIndex == sourceGroupIndex) {
newIDs.addAll(sharedRecordVA.getIDs());
groupSizes.add(sharedRecordVA.size());
sampleElements.add(sizeCounter);
sizeCounter += sharedRecordVA.size();
groupNames.add(sourceVA.getGroupList().get(groupIndex).getLabel() + " Split 1");
newIDs.addAll(remainingGroupIDs);
groupSizes.add(remainingGroupIDs.size());
sampleElements.add(sizeCounter);
sizeCounter += remainingGroupIDs.size();
groupNames.add(sourceVA.getGroupList().get(groupIndex).getLabel() + " Split 2");
} else {
newIDs.addAll(sourceVA.getIDsOfGroup(groupIndex));
groupSizes.add(sourceVA.getGroupList().get(groupIndex).getSize());
sampleElements.add(sizeCounter);
sizeCounter += sourceVA.getGroupList().get(groupIndex).getSize();
groupNames.add(sourceVA.getGroupList().get(groupIndex).getLabel());
}
}
PerspectiveInitializationData data = new PerspectiveInitializationData();
data.setData(newIDs, groupSizes, sampleElements, groupNames);
// FIXME the rest should probably not be done here but in the data
// domain.
sourcePerspective.init(data);
RecordVAUpdateEvent event = new RecordVAUpdateEvent();
event.setPerspectiveID(sourcePerspective.getPerspectiveID());
eventPublisher.triggerEvent(event);
}
@ListenTo
private void onMergeBricks(MergeBricksEvent event) {
List<GLBrick> bricksToMerge = event.getBricks();
if (bricksToMerge.size() <= 1)
return;
Collections.reverse(bricksToMerge);
BrickColumn brickColumn = bricksToMerge.get(0).getBrickColumn();
Perspective sourcePerspective = brickColumn.getTablePerspective().getRecordPerspective();
VirtualArray sourceVA = sourcePerspective.getVirtualArray();
List<GLBrick> bricks = brickColumn.getSegmentBricks();
Collections.reverse(bricks);
List<Integer> mergedBrickIDs = new ArrayList<>();
// add ids of all bricks
for (GLBrick brick : bricksToMerge) {
mergedBrickIDs.addAll(brick.getTablePerspective().getRecordPerspective().getVirtualArray().getIDs());
}
List<Integer> newIDs = new ArrayList<Integer>(sourceVA.size());
List<Integer> groupSizes = new ArrayList<Integer>(bricks.size() - bricksToMerge.size() + 1);
List<String> groupNames = new ArrayList<String>(bricks.size() - bricksToMerge.size() + 1);
List<Integer> sampleElements = new ArrayList<Integer>(bricks.size() - bricksToMerge.size() + 1);
boolean mergedBrickAdded = false;
int sizeCounter = 0;
for (GLBrick brick : bricks) {
if (bricksToMerge.contains(brick)) {
if (mergedBrickAdded)
continue;
newIDs.addAll(mergedBrickIDs);
groupSizes.add(mergedBrickIDs.size());
sampleElements.add(sizeCounter);
sizeCounter += mergedBrickIDs.size();
StringBuilder label = new StringBuilder("Merge of ");
for (int i = 0; i < bricksToMerge.size(); i++) {
GLBrick b = bricksToMerge.get(i);
label.append(sourceVA.getGroupList().get(b.getTablePerspective().getRecordGroup().getGroupIndex())
.getLabel());
if (i < bricksToMerge.size() - 1)
label.append(", ");
}
groupNames.add(label.toString());
mergedBrickAdded = true;
} else {
List<Integer> brickIDs = brick.getTablePerspective().getRecordPerspective().getVirtualArray().getIDs();
newIDs.addAll(brickIDs);
groupSizes.add(brickIDs.size());
sampleElements.add(sizeCounter);
sizeCounter += brickIDs.size();
groupNames.add(sourceVA.getGroupList()
.get(brick.getTablePerspective().getRecordGroup().getGroupIndex()).getLabel());
}
}
PerspectiveInitializationData data = new PerspectiveInitializationData();
data.setData(newIDs, groupSizes, sampleElements, groupNames);
// FIXME the rest should probably not be done here but in the data
// domain.
sourcePerspective.init(data);
RecordVAUpdateEvent e = new RecordVAUpdateEvent();
e.setPerspectiveID(sourcePerspective.getPerspectiveID());
eventPublisher.triggerEvent(e);
}
public int getNextConnectionBandID() {
return connectionBandIDCounter++;
}
public RelationAnalyzer getRelationAnalyzer() {
return relationAnalyzer;
}
public float getArchInnerWidth() {
return archInnerWidth;
}
@Override
public Set<IDataDomain> getDataDomains() {
Set<IDataDomain> dataDomains = new HashSet<IDataDomain>();
if (tablePerspectives == null) {
System.out.println("Problem");
return dataDomains;
}
for (TablePerspective tablePerspective : tablePerspectives) {
if (tablePerspective instanceof PathwayTablePerspective) {
dataDomains.add(((PathwayTablePerspective) tablePerspective).getPathwayDataDomain());
} else {
dataDomains.add(tablePerspective.getDataDomain());
}
}
return dataDomains;
}
@Override
public boolean isDataView() {
return true;
}
public int getArchHeight() {
return ARCH_PIXEL_HEIGHT;
}
public DragAndDropController getDragAndDropController() {
return dragAndDropController;
}
@Override
protected void destroyViewSpecificContent(GL2 gl) {
gl.glDeleteLists(displayListIndex, 1);
// if (centerLayoutManager != null)
// centerLayoutManager.destroy(gl);
// if (leftLayoutManager != null)
// leftLayoutManager.destroy(gl);
// if (rightLayoutManager != null)
// rightLayoutManager.destroy(gl);
if (layoutManager != null)
layoutManager.destroy(gl);
}
public Row getLayout() {
return mainRow;
}
@Override
public IDataSupportDefinition getDataSupportDefinition() {
return DataSupportDefinitions.all;
}
@Override
public void notifyOfSelectionChange(EventBasedSelectionManager selectionManager) {
// TODO Auto-generated method stub
updateConnectionLinesBetweenColumns();
}
/**
* @param wizard
*/
public void registerEventListener(Object elem) {
listeners.register(elem);
}
public void unregisterEventListener(Object elem) {
listeners.unregister(elem);
}
}
|
package org.safehaus.subutai.core.env.ui.forms;
import org.safehaus.subutai.core.env.api.Environment;
import org.safehaus.subutai.core.env.api.exception.EnvironmentModificationException;
import com.google.common.base.Strings;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.Window;
public class SshKeyWindow extends Window
{
private final TextArea sshKeyTxt;
public SshKeyWindow( final Environment environment )
{
setCaption( "Ssh key" );
setWidth( "600px" );
setHeight( "300px" );
setModal( true );
setClosable( true );
GridLayout content = new GridLayout( 2, 2 );
content.setSizeFull();
content.setMargin( true );
content.setSpacing( true );
boolean keyExists = !Strings.isNullOrEmpty( environment.getSshKey() );
CheckBox keyExistsChk = new CheckBox( "Key exists" );
keyExistsChk.setValue( keyExists );
keyExistsChk.setReadOnly( true );
content.addComponent( keyExistsChk );
Button removeKeyBtn = new Button( "Remove key" );
removeKeyBtn.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent event )
{
try
{
environment.setSshKey( null, true );
Notification.show( "Please, wait..." );
close();
}
catch ( EnvironmentModificationException e )
{
Notification.show( "Error setting ssh key", e.getMessage(), Notification.Type.ERROR_MESSAGE );
}
}
} );
removeKeyBtn.setEnabled( keyExists );
content.addComponent( removeKeyBtn );
sshKeyTxt = createSshKeyTxt();
content.addComponent( sshKeyTxt );
Button setSshKeyBtn = new Button( "Set key" );
setSshKeyBtn.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent event )
{
String sshKey = sshKeyTxt.getValue();
if ( Strings.isNullOrEmpty( sshKey ) )
{
Notification.show( "Please, enter key" );
return;
}
try
{
environment.setSshKey( sshKey, true );
Notification.show( "Please, wait..." );
close();
}
catch ( EnvironmentModificationException e )
{
Notification.show( "Error setting ssh key", e.getMessage(), Notification.Type.ERROR_MESSAGE );
}
}
} );
content.addComponent( setSshKeyBtn, 1, 1 );
setContent( content );
}
private TextArea createSshKeyTxt()
{
TextArea sshKeyTxt = new TextArea( "Ssh key" );
sshKeyTxt.setId( "sshKeyTxt" );
sshKeyTxt.setRows( 7 );
sshKeyTxt.setColumns( 30 );
sshKeyTxt.setImmediate( true );
sshKeyTxt.setWordwrap( true );
return sshKeyTxt;
}
}
|
package org.caleydo.view.visbricks;
import gleem.linalg.Vec3f;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import org.caleydo.core.data.collection.ISet;
import org.caleydo.core.data.graph.tree.ClusterTree;
import org.caleydo.core.data.selection.ContentSelectionManager;
import org.caleydo.core.data.selection.SelectionType;
import org.caleydo.core.data.selection.delta.ISelectionDelta;
import org.caleydo.core.data.virtualarray.EVAOperation;
import org.caleydo.core.data.virtualarray.similarity.RelationAnalyzer;
import org.caleydo.core.manager.GeneralManager;
import org.caleydo.core.manager.datadomain.ASetBasedDataDomain;
import org.caleydo.core.manager.event.data.NewMetaSetsEvent;
import org.caleydo.core.manager.event.data.RelationsUpdatedEvent;
import org.caleydo.core.manager.event.view.ClearSelectionsEvent;
import org.caleydo.core.manager.picking.EPickingMode;
import org.caleydo.core.manager.picking.EPickingType;
import org.caleydo.core.manager.picking.Pick;
import org.caleydo.core.serialize.ASerializedView;
import org.caleydo.core.util.mapping.color.ColorMappingManager;
import org.caleydo.core.util.mapping.color.EColorMappingType;
import org.caleydo.core.view.IDataDomainSetBasedView;
import org.caleydo.core.view.opengl.camera.ECameraProjectionMode;
import org.caleydo.core.view.opengl.camera.ViewFrustum;
import org.caleydo.core.view.opengl.canvas.AGLView;
import org.caleydo.core.view.opengl.canvas.DetailLevel;
import org.caleydo.core.view.opengl.canvas.GLCaleydoCanvas;
import org.caleydo.core.view.opengl.canvas.listener.ClearSelectionsListener;
import org.caleydo.core.view.opengl.canvas.listener.ISelectionUpdateHandler;
import org.caleydo.core.view.opengl.canvas.listener.IViewCommandHandler;
import org.caleydo.core.view.opengl.canvas.remote.IGLRemoteRenderingView;
import org.caleydo.core.view.opengl.layout.Column;
import org.caleydo.core.view.opengl.layout.ElementLayout;
import org.caleydo.core.view.opengl.layout.LayoutManager;
import org.caleydo.core.view.opengl.layout.LayoutTemplate;
import org.caleydo.core.view.opengl.layout.Row;
import org.caleydo.core.view.opengl.mouse.GLMouseListener;
import org.caleydo.core.view.opengl.util.draganddrop.DragAndDropController;
import org.caleydo.core.view.opengl.util.spline.ConnectionBandRenderer;
import org.caleydo.core.view.opengl.util.text.CaleydoTextRenderer;
import org.caleydo.core.view.opengl.util.vislink.NURBSCurve;
import org.caleydo.view.visbricks.dimensiongroup.DimensionGroup;
import org.caleydo.view.visbricks.dimensiongroup.DimensionGroupManager;
import org.caleydo.view.visbricks.dimensiongroup.DimensionGroupSpacingRenderer;
import org.caleydo.view.visbricks.listener.GLVisBricksKeyListener;
import org.caleydo.view.visbricks.listener.NewMetaSetsListener;
import org.caleydo.view.visbricks.renderstyle.VisBricksRenderStyle;
/**
* VisBricks main view
*
* @author Marc Streit
* @author Alexander Lex
*/
public class GLVisBricks extends AGLView implements IGLRemoteRenderingView,
IViewCommandHandler, ISelectionUpdateHandler, IDataDomainSetBasedView {
public final static String VIEW_ID = "org.caleydo.view.visbricks";
private final static int ARCH_PIXEL_HEIGHT = 150;
private final static float ARCH_BOTTOM_PERCENT = 0.5f;
private final static float ARCH_STAND_WIDTH_PERCENT = 0.05f;
private final static int DIMENSION_GROUP_SPACING = 30;
private NewMetaSetsListener metaSetsListener;
private ClearSelectionsListener clearSelectionsListener;
private ASetBasedDataDomain dataDomain;
private VisBricksRenderStyle renderStyle;
private DimensionGroupManager dimensionGroupManager;
private ConnectionBandRenderer connectionRenderer;
private LayoutManager centerLayoutManager;
private LayoutManager leftLayoutManager;
private LayoutManager rightLayoutManager;
private LayoutTemplate centerLayout;
private LayoutTemplate leftLayoutTemplate;
private LayoutTemplate rightLayout;
private Row centerRowLayout;
private Column leftColumnLayout;
private Column rightColumnLayout;
/** thickness of the arch at the sided */
private float archSideThickness = 0;
private float archInnerWidth = 0;
private float archTopY = 0;
private float archBottomY = 0;
private float archHeight = 0;
/** Flag signalling if a group needs to be moved out of the center */
boolean resizeNecessary = false;
boolean lastResizeDirectionWasToLeft = true;
boolean isLayoutDirty = false;
private Queue<DimensionGroup> uninitializedDimensionGroups = new LinkedList<DimensionGroup>();
private DragAndDropController dragAndDropController;
private boolean dropDimensionGroupAfter = true;
private RelationAnalyzer relationAnalyzer;
private ElementLayout leftDimensionGroupSpacing;
private ElementLayout rightDimensionGroupSpacing;
private ContentSelectionManager contentSelectionManager;
/**
* Constructor.
*
* @param glCanvas
* @param sLabel
* @param viewFrustum
*/
public GLVisBricks(GLCaleydoCanvas glCanvas, final ViewFrustum viewFrustum) {
super(glCanvas, viewFrustum, true);
viewType = GLVisBricks.VIEW_ID;
connectionRenderer = new ConnectionBandRenderer();
dragAndDropController = new DragAndDropController(this);
dimensionGroupManager = new DimensionGroupManager();
glKeyListener = new GLVisBricksKeyListener();
}
@Override
public void init(GL2 gl) {
textRenderer = new CaleydoTextRenderer(24);
dataDomain.createContentRelationAnalyzer();
relationAnalyzer = dataDomain.getContentRelationAnalyzer();
contentSelectionManager = dataDomain.getContentSelectionManager();
// renderStyle = new GeneralRenderStyle(viewFrustum);
renderStyle = new VisBricksRenderStyle(viewFrustum);
super.renderStyle = renderStyle;
detailLevel = DetailLevel.HIGH;
metaSetsUpdated();
connectionRenderer.init(gl);
}
private void initLayouts() {
dimensionGroupManager.getDimensionGroupSpacers().clear();
initCenterLayout();
ViewFrustum leftArchFrustum = new ViewFrustum(viewFrustum.getProjectionMode(), 0,
archSideThickness, 0, archBottomY, 0, 1);
leftLayoutManager = new LayoutManager(leftArchFrustum);
leftColumnLayout = new Column("leftArchColumn");
leftLayoutTemplate = new LayoutTemplate();
initSideLayout(leftColumnLayout, leftLayoutTemplate, leftLayoutManager, 0,
dimensionGroupManager.getCenterGroupStartIndex());
ViewFrustum rightArchFrustum = new ViewFrustum(viewFrustum.getProjectionMode(),
0, archSideThickness, 0, archBottomY, 0, 1);
rightColumnLayout = new Column("rightArchColumn");
rightLayout = new LayoutTemplate();
rightLayoutManager = new LayoutManager(rightArchFrustum);
initSideLayout(rightColumnLayout, rightLayout, rightLayoutManager,
dimensionGroupManager.getRightGroupStartIndex(), dimensionGroupManager
.getDimensionGroups().size());
updateConnectionLinesBetweenDimensionGroups();
}
/**
* Init the layout for the center region, showing the horizontal bar of the
* arch plus all sub-bricks above and below
*/
private void initCenterLayout() {
archSideThickness = viewFrustum.getWidth() * ARCH_STAND_WIDTH_PERCENT;
archInnerWidth = viewFrustum.getWidth() * (ARCH_STAND_WIDTH_PERCENT + 0.024f);
archHeight = parentGLCanvas.getPixelGLConverter().getGLHeightForPixelHeight(
ARCH_PIXEL_HEIGHT);
archBottomY = viewFrustum.getHeight() * ARCH_BOTTOM_PERCENT - archHeight / 2f;
archTopY = archBottomY + archHeight;
int dimensionGroupCountInCenter = dimensionGroupManager.getRightGroupStartIndex()
- dimensionGroupManager.getCenterGroupStartIndex();
float centerLayoutWidth = viewFrustum.getWidth() - 2 * (archInnerWidth);
centerRowLayout = new Row("centerArchRow");
centerRowLayout.setFrameColor(1, 1, 0, 1);
// centerRowLayout.setDebug(false);
leftDimensionGroupSpacing = new ElementLayout("firstCenterDimGrSpacing");
// leftDimensionGroupSpacing.setDebug(true);
DimensionGroupSpacingRenderer dimensionGroupSpacingRenderer = null;
// Handle special case where center contains no groups
if (dimensionGroupCountInCenter < 1) {
dimensionGroupSpacingRenderer = new DimensionGroupSpacingRenderer(null,
connectionRenderer, null, null, this);
} else {
dimensionGroupSpacingRenderer = new DimensionGroupSpacingRenderer(null,
connectionRenderer, null, dimensionGroupManager.getDimensionGroups()
.get(dimensionGroupManager.getCenterGroupStartIndex()), this);
}
leftDimensionGroupSpacing.setRenderer(dimensionGroupSpacingRenderer);
dimensionGroupSpacingRenderer.setLineLength(archHeight);
leftDimensionGroupSpacing.setPixelGLConverter(parentGLCanvas
.getPixelGLConverter());
if (dimensionGroupCountInCenter > 1)
leftDimensionGroupSpacing.setPixelSizeX(50);
else
leftDimensionGroupSpacing.setGrabX(true);
centerRowLayout.append(leftDimensionGroupSpacing);
for (int dimensionGroupIndex = dimensionGroupManager.getCenterGroupStartIndex(); dimensionGroupIndex < dimensionGroupManager
.getRightGroupStartIndex(); dimensionGroupIndex++) {
ElementLayout dynamicDimensionGroupSpacing;
DimensionGroup group = dimensionGroupManager.getDimensionGroups().get(
dimensionGroupIndex);
group.setCollapsed(false);
group.setArchHeight(ARCH_PIXEL_HEIGHT);
centerRowLayout.append(group.getLayout());
// centerRowLayout.setDebug(true);
if (dimensionGroupIndex != dimensionGroupManager.getRightGroupStartIndex() - 1) {
dynamicDimensionGroupSpacing = new ElementLayout("dynamicDimGrSpacing");
dimensionGroupSpacingRenderer = new DimensionGroupSpacingRenderer(
relationAnalyzer, connectionRenderer, group,
dimensionGroupManager.getDimensionGroups().get(
dimensionGroupIndex + 1), this);
dynamicDimensionGroupSpacing.setGrabX(true);
dynamicDimensionGroupSpacing.setRenderer(dimensionGroupSpacingRenderer);
centerRowLayout.append(dynamicDimensionGroupSpacing);
} else {
rightDimensionGroupSpacing = new ElementLayout("lastDimGrSpacing");
dimensionGroupSpacingRenderer = new DimensionGroupSpacingRenderer(null,
connectionRenderer, group, null, this);
rightDimensionGroupSpacing.setPixelGLConverter(parentGLCanvas
.getPixelGLConverter());
if (dimensionGroupCountInCenter > 1)
rightDimensionGroupSpacing.setPixelSizeX(50);
else
rightDimensionGroupSpacing.setGrabX(true);
rightDimensionGroupSpacing.setRenderer(dimensionGroupSpacingRenderer);
centerRowLayout.append(rightDimensionGroupSpacing);
}
// dimensionGroupSpacing.setDebug(true);
dimensionGroupSpacingRenderer.setLineLength(archHeight);
}
centerLayout = new LayoutTemplate();
centerLayout.setPixelGLConverter(parentGLCanvas.getPixelGLConverter());
centerLayout.setBaseElementLayout(centerRowLayout);
ViewFrustum centerArchFrustum = new ViewFrustum(viewFrustum.getProjectionMode(),
0, centerLayoutWidth, 0, viewFrustum.getHeight(), 0, 1);
centerLayoutManager = new LayoutManager(centerArchFrustum);
centerLayoutManager.setTemplate(centerLayout);
centerLayoutManager.updateLayout();
}
/**
* Initialize the layout for the sides of the arch
*
* @param columnLayout
* @param layoutTemplate
* @param layoutManager
* @param dimensinoGroupStartIndex
* @param dimensinoGroupEndIndex
*/
private void initSideLayout(Column columnLayout, LayoutTemplate layoutTemplate,
LayoutManager layoutManager, int dimensinoGroupStartIndex,
int dimensinoGroupEndIndex) {
layoutTemplate.setPixelGLConverter(parentGLCanvas.getPixelGLConverter());
layoutTemplate.setBaseElementLayout(columnLayout);
layoutManager.setTemplate(layoutTemplate);
columnLayout.setFrameColor(1, 1, 0, 1);
// columnLayout.setDebug(true);
columnLayout.setBottomUp(true);
ElementLayout dimensionGroupSpacing = new ElementLayout("firstSideDimGrSpacing");
// dimensionGroupSpacing.setDebug(true);
dimensionGroupSpacing.setGrabY(true);
columnLayout.append(dimensionGroupSpacing);
DimensionGroupSpacingRenderer dimensionGroupSpacingRenderer = null;
// Handle special case where arch stand contains no groups
if (dimensinoGroupStartIndex == 0) {
dimensionGroupSpacingRenderer = new DimensionGroupSpacingRenderer(null,
connectionRenderer, null, null, this);
} else {
dimensionGroupSpacingRenderer = new DimensionGroupSpacingRenderer(null,
connectionRenderer, null, dimensionGroupManager.getDimensionGroups()
.get(dimensionGroupManager.getCenterGroupStartIndex()), this);
}
dimensionGroupSpacing.setRenderer(dimensionGroupSpacingRenderer);
dimensionGroupSpacingRenderer.setVertical(false);
dimensionGroupSpacingRenderer.setLineLength(archSideThickness);
for (int dimensionGroupIndex = dimensinoGroupStartIndex; dimensionGroupIndex < dimensinoGroupEndIndex; dimensionGroupIndex++) {
DimensionGroup group = dimensionGroupManager.getDimensionGroups().get(
dimensionGroupIndex);
group.getLayout().setAbsoluteSizeY(archSideThickness);
// group.getLayout().setDebug(true);
group.setArchHeight(-1);
columnLayout.append(group.getLayout());
group.setCollapsed(true);
dimensionGroupSpacing = new ElementLayout("sideDimGrSpacing");
// dimensionGroupSpacing.setDebug(true);
dimensionGroupSpacing.setGrabY(true);
dimensionGroupSpacingRenderer = new DimensionGroupSpacingRenderer(null, null,
group, null, this);
columnLayout.append(dimensionGroupSpacing);
dimensionGroupSpacing.setRenderer(dimensionGroupSpacingRenderer);
dimensionGroupSpacingRenderer.setVertical(false);
dimensionGroupSpacingRenderer.setLineLength(archSideThickness);
}
layoutManager.updateLayout();
}
@Override
public void initLocal(GL2 gl) {
// Register keyboard listener to GL2 canvas
parentGLCanvas.getParentComposite().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
parentGLCanvas.getParentComposite().addKeyListener(glKeyListener);
}
});
iGLDisplayListIndexLocal = gl.glGenLists(1);
iGLDisplayListToCall = iGLDisplayListIndexLocal;
init(gl);
}
@Override
public void initRemote(final GL2 gl, final AGLView glParentView,
final GLMouseListener glMouseListener) {
}
@Override
public void displayLocal(GL2 gl) {
iGLDisplayListToCall = iGLDisplayListIndexLocal;
if (!uninitializedDimensionGroups.isEmpty()) {
while (uninitializedDimensionGroups.peek() != null) {
uninitializedDimensionGroups.poll().initRemote(gl, this, glMouseListener);
}
initLayouts();
}
if (bIsDisplayListDirtyLocal) {
buildDisplayList(gl, iGLDisplayListIndexLocal);
bIsDisplayListDirtyLocal = false;
}
for (DimensionGroup group : dimensionGroupManager.getDimensionGroups()) {
group.processEvents();
}
// brick.display(gl);
pickingManager.handlePicking(this, gl);
display(gl);
checkForHits(gl);
}
@Override
public void displayRemote(GL2 gl) {
}
@Override
public void display(GL2 gl) {
gl.glCallList(iGLDisplayListToCall);
if (isLayoutDirty) {
isLayoutDirty = false;
centerLayoutManager.updateLayout();
for (ElementLayout layout : centerRowLayout) {
if (resizeNecessary)
break;
if (layout.getSizeScaledX() < parentGLCanvas.getPixelGLConverter()
.getGLWidthForPixelWidth(DIMENSION_GROUP_SPACING) + 0.001f) {
resizeNecessary = true;
break;
}
}
}
for (DimensionGroup dimensionGroup : dimensionGroupManager.getDimensionGroups()) {
dimensionGroup.display(gl);
}
if (resizeNecessary) {
if (lastResizeDirectionWasToLeft) {
dimensionGroupManager.setCenterGroupStartIndex(dimensionGroupManager
.getCenterGroupStartIndex() + 1);
if (centerRowLayout.size() == 3)
leftDimensionGroupSpacing.setGrabX(true);
} else {
dimensionGroupManager.setRightGroupStartIndex(dimensionGroupManager
.getRightGroupStartIndex() - 1);
if (centerRowLayout.size() == 3)
rightDimensionGroupSpacing.setGrabX(true);
}
initLayouts();
updateLayout();
resizeNecessary = false;
}
leftLayoutManager.render(gl);
gl.glTranslatef(archInnerWidth, 0, 0);
centerLayoutManager.render(gl);
gl.glTranslatef(-archInnerWidth, 0, 0);
float rightArchStand = (1 - ARCH_STAND_WIDTH_PERCENT) * viewFrustum.getWidth();
gl.glTranslatef(rightArchStand, 0, 0);
rightLayoutManager.render(gl);
gl.glTranslatef(-rightArchStand, 0, 0);
// call after all other rendering because it calls the onDrag methods
// which need alpha blending...
dragAndDropController.handleDragging(gl, glMouseListener);
}
private void buildDisplayList(final GL2 gl, int iGLDisplayListIndex) {
gl.glNewList(iGLDisplayListIndex, GL2.GL_COMPILE);
renderArch(gl);
gl.glEndList();
}
private void renderArch(GL2 gl) {
// Left arch
gl.glLineWidth(1);
gl.glColor4f(0.5f, 0.5f, 0.5f, 1f);
gl.glBegin(GL2.GL_POLYGON);
gl.glVertex3f(0, 0, 0f);
gl.glVertex3f(0, archBottomY, 0f);
gl.glVertex3f(archSideThickness, archBottomY, 0f);
gl.glVertex3f(archSideThickness, 0, 0f);
gl.glEnd();
ArrayList<Vec3f> inputPoints = new ArrayList<Vec3f>();
inputPoints.add(new Vec3f(0, archBottomY, 0));
inputPoints.add(new Vec3f(0, archTopY, 0));
inputPoints.add(new Vec3f(archInnerWidth * 0.9f, archTopY, 0));
NURBSCurve curve = new NURBSCurve(inputPoints, 10);
ArrayList<Vec3f> outputPointsTop = curve.getCurvePoints();
outputPointsTop.add(new Vec3f(archInnerWidth, archTopY, 0));
inputPoints.clear();
inputPoints.add(new Vec3f(archInnerWidth, archBottomY, 0));
inputPoints.add(new Vec3f(archSideThickness, archBottomY, 0));
inputPoints.add(new Vec3f(archSideThickness, archBottomY * 0.8f, 0));
curve = new NURBSCurve(inputPoints, 10);
ArrayList<Vec3f> outputPointsBottom = new ArrayList<Vec3f>();
outputPointsBottom.addAll(curve.getCurvePoints());
ArrayList<Vec3f> outputPoints = new ArrayList<Vec3f>();
outputPoints.addAll(outputPointsTop);
outputPoints.add(new Vec3f(archInnerWidth, archBottomY, 0));
outputPoints.addAll(outputPointsBottom);
connectionRenderer.render(gl, outputPoints);
gl.glColor4f(0, 0, 0, 0.8f);
gl.glBegin(GL2.GL_LINE_STRIP);
for (Vec3f point : outputPointsTop)
gl.glVertex3f(point.x(), point.y(), point.z());
gl.glEnd();
gl.glBegin(GL2.GL_LINE_STRIP);
for (Vec3f point : outputPointsBottom)
gl.glVertex3f(point.x(), point.y(), point.z());
gl.glEnd();
gl.glColor4f(0, 0, 0, 0.8f);
gl.glBegin(GL2.GL_LINES);
gl.glVertex3f(0, archBottomY, 0f);
gl.glVertex3f(0, 0, 0f);
gl.glEnd();
gl.glBegin(GL2.GL_LINES);
gl.glVertex3f(archSideThickness, archBottomY * 0.8f, 0f);
gl.glVertex3f(archSideThickness, 0, 0f);
gl.glEnd();
// Right arch
gl.glColor4f(0.5f, 0.5f, 0.5f, 1f);
gl.glBegin(GL2.GL_POLYGON);
gl.glVertex3f(viewFrustum.getWidth(), 0, 0f);
gl.glVertex3f(viewFrustum.getWidth(), archBottomY, 0f);
gl.glVertex3f(viewFrustum.getWidth() - archSideThickness, archBottomY, 0f);
gl.glVertex3f(viewFrustum.getWidth() - archSideThickness, 0, 0f);
gl.glEnd();
inputPoints.clear();
inputPoints.add(new Vec3f(viewFrustum.getWidth(), archBottomY, 0));
inputPoints.add(new Vec3f(viewFrustum.getWidth(), archTopY, 0));
inputPoints.add(new Vec3f(viewFrustum.getWidth() - archInnerWidth * 0.9f,
archTopY, 0));
curve = new NURBSCurve(inputPoints, 10);
outputPointsTop.clear();
outputPointsTop = curve.getCurvePoints();
outputPointsTop.add(new Vec3f(viewFrustum.getWidth() - archInnerWidth, archTopY,
0));
inputPoints.clear();
inputPoints
.add(new Vec3f(viewFrustum.getWidth() - archInnerWidth, archBottomY, 0));
inputPoints.add(new Vec3f(viewFrustum.getWidth() - archSideThickness,
archBottomY, 0));
inputPoints.add(new Vec3f(viewFrustum.getWidth() - archSideThickness,
archBottomY * 0.8f, 0));
curve = new NURBSCurve(inputPoints, 10);
outputPointsBottom.clear();
outputPointsBottom = new ArrayList<Vec3f>();
outputPointsBottom.addAll(curve.getCurvePoints());
outputPoints.clear();
outputPoints.addAll(outputPointsTop);
outputPoints.add(new Vec3f(viewFrustum.getWidth() - archInnerWidth, archBottomY,
0));
outputPoints.addAll(outputPointsBottom);
connectionRenderer.render(gl, outputPoints);
gl.glColor4f(0, 0, 0, 0.8f);
gl.glBegin(GL2.GL_LINE_STRIP);
for (Vec3f point : outputPointsTop)
gl.glVertex3f(point.x(), point.y(), point.z());
gl.glEnd();
gl.glBegin(GL2.GL_LINE_STRIP);
for (Vec3f point : outputPointsBottom)
gl.glVertex3f(point.x(), point.y(), point.z());
gl.glEnd();
gl.glBegin(GL2.GL_LINES);
gl.glVertex3f(viewFrustum.getWidth(), 0, 0f);
gl.glVertex3f(viewFrustum.getWidth(), archBottomY, 0f);
gl.glEnd();
gl.glBegin(GL2.GL_LINES);
gl.glVertex3f(viewFrustum.getWidth() - archSideThickness, archBottomY * 0.8f,
0.01f);
gl.glVertex3f(viewFrustum.getWidth() - archSideThickness, 0, 0.1f);
gl.glEnd();
}
@Override
protected void handlePickingEvents(EPickingType pickingType,
EPickingMode pickingMode, int externalID, Pick pick) {
if (detailLevel == DetailLevel.VERY_LOW) {
return;
}
switch (pickingType) {
case DIMENSION_GROUP:
switch (pickingMode) {
case MOUSE_OVER:
System.out.println("Mouse over");
break;
case CLICKED:
dragAndDropController.setDraggingStartPosition(pick.getPickedPoint());
dragAndDropController.addDraggable((DimensionGroup) generalManager
.getViewGLCanvasManager().getGLView(externalID));
break;
case RIGHT_CLICKED:
break;
case DRAGGED:
if (dragAndDropController.hasDraggables()) {
if (glMouseListener.wasRightMouseButtonPressed())
dragAndDropController.clearDraggables();
else if (!dragAndDropController.isDragging())
dragAndDropController.startDragging();
}
break;
}
case DIMENSION_GROUP_SPACER:
switch (pickingMode) {
case DRAGGED:
dragAndDropController.setDropArea(dimensionGroupManager
.getDimensionGroupSpacers().get(externalID));
break;
}
}
}
@Override
public ASerializedView getSerializableRepresentation() {
SerializedVisBricksView serializedForm = new SerializedVisBricksView(
dataDomain.getDataDomainType());
serializedForm.setViewID(this.getID());
return serializedForm;
}
@Override
public String toString() {
return "TODO: ADD INFO THAT APPEARS IN THE LOG";
}
@Override
public void registerEventListeners() {
super.registerEventListeners();
metaSetsListener = new NewMetaSetsListener();
metaSetsListener.setHandler(this);
eventPublisher.addListener(NewMetaSetsEvent.class, metaSetsListener);
clearSelectionsListener = new ClearSelectionsListener();
clearSelectionsListener.setHandler(this);
eventPublisher.addListener(ClearSelectionsEvent.class, clearSelectionsListener);
}
@Override
public void unregisterEventListeners() {
super.unregisterEventListeners();
if (metaSetsListener != null) {
eventPublisher.removeListener(metaSetsListener);
metaSetsListener = null;
}
if (clearSelectionsListener != null) {
eventPublisher.removeListener(clearSelectionsListener);
clearSelectionsListener = null;
}
}
@Override
public void handleSelectionUpdate(ISelectionDelta selectionDelta,
boolean scrollToSelection, String info) {
// TODO Auto-generated method stub
}
@Override
public void handleRedrawView() {
// TODO Auto-generated method stub
}
@Override
public void handleUpdateView() {
// TODO Auto-generated method stub
}
@Override
public void handleClearSelections() {
clearAllSelections();
}
@Override
public void clearAllSelections() {
contentSelectionManager.clearSelections();
updateConnectionLinesBetweenDimensionGroups();
}
@Override
public void broadcastElements(EVAOperation type) {
// TODO Auto-generated method stub
}
@Override
public int getNumberOfSelections(SelectionType SelectionType) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<AGLView> getRemoteRenderedViews() {
return null;
}
public void metaSetsUpdated() {
ClusterTree storageTree = dataDomain.getSet().getStorageData(storageVAType)
.getStorageTree();
if (storageTree == null)
return;
ArrayList<ISet> allMetaSets = storageTree.getRoot().getAllMetaSetsFromSubTree();
ArrayList<ISet> filteredMetaSets = new ArrayList<ISet>(allMetaSets.size() / 2);
for (ISet metaSet : allMetaSets) {
if (metaSet.size() > 1 && metaSet.size() != dataDomain.getSet().size())
filteredMetaSets.add(metaSet);
}
initializeBricks(filteredMetaSets);
}
private void initializeBricks(ArrayList<ISet> metaSets) {
ArrayList<DimensionGroup> dimensionGroups = dimensionGroupManager
.getDimensionGroups();
Iterator<DimensionGroup> dimensionGroupIterator = dimensionGroups.iterator();
while (dimensionGroupIterator.hasNext()) {
DimensionGroup dimensionGroup = dimensionGroupIterator.next();
ISet metaSet = dimensionGroup.getSet();
if (!metaSets.contains(metaSet)) {
dimensionGroupIterator.remove();
} else {
metaSets.remove(metaSet);
}
}
for (ISet set : metaSets) {
// TODO here we need to check which metaSets have already been
// assigned to a dimensiongroup and not re-create them
DimensionGroup dimensionGroup = (DimensionGroup) GeneralManager
.get()
.getViewGLCanvasManager()
.createGLView(
DimensionGroup.class,
getParentGLCanvas(),
new ViewFrustum(ECameraProjectionMode.ORTHOGRAPHIC, 0, 1, 0,
1, -1, 1));
dimensionGroup.setDataDomain(dataDomain);
dimensionGroup.setSet(set);
dimensionGroup.setRemoteRenderingGLView(this);
dimensionGroup.setVisBricks(this);
dimensionGroup.setVisBricksView(this);
dimensionGroup.initialize();
dimensionGroups.add(dimensionGroup);
uninitializedDimensionGroups.add(dimensionGroup);
}
dimensionGroupManager.calculateGroupDivision();
}
@Override
public void setDataDomain(ASetBasedDataDomain dataDomain) {
this.dataDomain = dataDomain;
}
@Override
public ASetBasedDataDomain getDataDomain() {
return dataDomain;
}
@Override
public String getShortInfo() {
return "LayoutTemplate Caleydo View";
}
@Override
public String getDetailedInfo() {
return "LayoutTemplate Caleydo View";
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
super.reshape(drawable, x, y, width, height);
initLayouts();
}
@Override
public void setDisplayListDirty() {
super.setDisplayListDirty();
}
public void moveDimensionGroup(DimensionGroupSpacingRenderer spacer,
DimensionGroup movedDimGroup, DimensionGroup referenceDimGroup) {
movedDimGroup.getLayout().reset();
clearDimensionGroupSpacerHighlight();
boolean insertComplete = false;
ArrayList<DimensionGroup> dimensionGroups = dimensionGroupManager
.getDimensionGroups();
for (ElementLayout leftLayout : leftColumnLayout.getElements()) {
if (spacer == leftLayout.getRenderer()) {
dimensionGroupManager.setCenterGroupStartIndex(dimensionGroupManager
.getCenterGroupStartIndex() + 1);
dimensionGroups.remove(movedDimGroup);
if (referenceDimGroup == null) {
dimensionGroups.add(0, movedDimGroup);
} else {
dimensionGroups.add(dimensionGroups.indexOf(referenceDimGroup),
movedDimGroup);
}
insertComplete = true;
break;
}
}
if (!insertComplete) {
for (ElementLayout rightLayout : rightColumnLayout.getElements()) {
if (spacer == rightLayout.getRenderer()) {
dimensionGroupManager.setRightGroupStartIndex(dimensionGroupManager
.getRightGroupStartIndex() - 1);
dimensionGroups.remove(movedDimGroup);
if (referenceDimGroup == null) {
dimensionGroups.add(dimensionGroups.size(), movedDimGroup);
} else {
dimensionGroups.add(
dimensionGroups.indexOf(referenceDimGroup) + 1,
movedDimGroup);
}
insertComplete = true;
break;
}
}
}
if (!insertComplete) {
for (ElementLayout centerLayout : centerRowLayout.getElements()) {
if (spacer == centerLayout.getRenderer()) {
if (dimensionGroups.indexOf(movedDimGroup) < dimensionGroupManager
.getCenterGroupStartIndex())
dimensionGroupManager
.setCenterGroupStartIndex(dimensionGroupManager
.getCenterGroupStartIndex() - 1);
else if (dimensionGroups.indexOf(movedDimGroup) >= dimensionGroupManager
.getRightGroupStartIndex())
dimensionGroupManager
.setRightGroupStartIndex(dimensionGroupManager
.getRightGroupStartIndex() + 1);
dimensionGroups.remove(movedDimGroup);
if (referenceDimGroup == null) {
dimensionGroups.add(
dimensionGroupManager.getCenterGroupStartIndex(),
movedDimGroup);
} else {
dimensionGroups.add(
dimensionGroups.indexOf(referenceDimGroup) + 1,
movedDimGroup);
}
insertComplete = true;
break;
}
}
}
initLayouts();
// FIXME: check why the second layout is needed here. otherwise the
// moved views appear upside down
initLayouts();
RelationsUpdatedEvent event = new RelationsUpdatedEvent();
event.setDataDomainType(dataDomain.getDataDomainType());
event.setSender(this);
eventPublisher.triggerEvent(event);
}
public void clearDimensionGroupSpacerHighlight() {
// Clear previous spacer highlights
for (ElementLayout element : centerRowLayout.getElements()) {
if (element.getRenderer() instanceof DimensionGroupSpacingRenderer)
((DimensionGroupSpacingRenderer) element.getRenderer())
.setRenderSpacer(false);
}
for (ElementLayout element : leftColumnLayout.getElements()) {
if (element.getRenderer() instanceof DimensionGroupSpacingRenderer)
((DimensionGroupSpacingRenderer) element.getRenderer())
.setRenderSpacer(false);
}
for (ElementLayout element : rightColumnLayout.getElements()) {
if (element.getRenderer() instanceof DimensionGroupSpacingRenderer)
((DimensionGroupSpacingRenderer) element.getRenderer())
.setRenderSpacer(false);
}
}
public DimensionGroupManager getDimensionGroupManager() {
return dimensionGroupManager;
}
public void updateConnectionLinesBetweenDimensionGroups() {
if (centerRowLayout != null) {
for (ElementLayout elementLayout : centerRowLayout.getElements()) {
if (elementLayout.getRenderer() instanceof DimensionGroupSpacingRenderer) {
((DimensionGroupSpacingRenderer) elementLayout.getRenderer()).init();
}
}
}
}
public void updateLayout() {
isLayoutDirty = true;
}
/**
* Set whether the last resize of any sub-brick was to the left(true) or to
* the right. Important for determining, which dimensionGroup to kick next.
*
* @param lastResizeDirectionWasToLeft
*/
public void setLastResizeDirectionWasToLeft(boolean lastResizeDirectionWasToLeft) {
this.lastResizeDirectionWasToLeft = lastResizeDirectionWasToLeft;
}
public float getArchTopY() {
return archTopY;
}
public float getArchBottomY() {
return archBottomY;
}
public ContentSelectionManager getContentSelectionManager() {
return contentSelectionManager;
}
public GLVisBricksKeyListener getKeyListener() {
return (GLVisBricksKeyListener) glKeyListener;
}
}
|
package org.mifosplatform.portfolio.loanaccount.guarantor.service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.mifosplatform.infrastructure.core.data.ApiParameterError;
import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException;
import org.mifosplatform.portfolio.account.PortfolioAccountType;
import org.mifosplatform.portfolio.account.data.AccountTransferDTO;
import org.mifosplatform.portfolio.account.domain.AccountTransferDetails;
import org.mifosplatform.portfolio.account.domain.AccountTransferType;
import org.mifosplatform.portfolio.account.service.AccountTransfersWritePlatformService;
import org.mifosplatform.portfolio.common.BusinessEventNotificationConstants.BUSINESS_ENTITY;
import org.mifosplatform.portfolio.common.BusinessEventNotificationConstants.BUSINESS_EVENTS;
import org.mifosplatform.portfolio.common.service.BusinessEventListner;
import org.mifosplatform.portfolio.common.service.BusinessEventNotifierService;
import org.mifosplatform.portfolio.loanaccount.domain.Loan;
import org.mifosplatform.portfolio.loanaccount.domain.LoanTransaction;
import org.mifosplatform.portfolio.loanaccount.guarantor.GuarantorConstants;
import org.mifosplatform.portfolio.loanaccount.guarantor.domain.Guarantor;
import org.mifosplatform.portfolio.loanaccount.guarantor.domain.GuarantorFundingDetails;
import org.mifosplatform.portfolio.loanaccount.guarantor.domain.GuarantorFundingRepository;
import org.mifosplatform.portfolio.loanaccount.guarantor.domain.GuarantorFundingTransaction;
import org.mifosplatform.portfolio.loanaccount.guarantor.domain.GuarantorFundingTransactionRepository;
import org.mifosplatform.portfolio.loanaccount.guarantor.domain.GuarantorRepository;
import org.mifosplatform.portfolio.loanproduct.domain.LoanProduct;
import org.mifosplatform.portfolio.loanproduct.domain.LoanProductGuaranteeDetails;
import org.mifosplatform.portfolio.paymentdetail.domain.PaymentDetail;
import org.mifosplatform.portfolio.savings.domain.DepositAccountOnHoldTransaction;
import org.mifosplatform.portfolio.savings.domain.DepositAccountOnHoldTransactionRepository;
import org.mifosplatform.portfolio.savings.domain.SavingsAccount;
import org.mifosplatform.portfolio.savings.exception.InsufficientAccountBalanceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class GuarantorDomainServiceImpl implements GuarantorDomainService {
private final GuarantorRepository guarantorRepository;
private final GuarantorFundingRepository guarantorFundingRepository;
private final GuarantorFundingTransactionRepository guarantorFundingTransactionRepository;
private final AccountTransfersWritePlatformService accountTransfersWritePlatformService;
private final BusinessEventNotifierService businessEventNotifierService;
private final DepositAccountOnHoldTransactionRepository depositAccountOnHoldTransactionRepository;
private final Map<Long, Long> releaseLoanIds = new HashMap<>(2);
private final RoundingMode roundingMode = RoundingMode.HALF_EVEN;
@Autowired
public GuarantorDomainServiceImpl(final GuarantorRepository guarantorRepository,
final GuarantorFundingRepository guarantorFundingRepository,
final GuarantorFundingTransactionRepository guarantorFundingTransactionRepository,
final AccountTransfersWritePlatformService accountTransfersWritePlatformService,
final BusinessEventNotifierService businessEventNotifierService,
final DepositAccountOnHoldTransactionRepository depositAccountOnHoldTransactionRepository) {
this.guarantorRepository = guarantorRepository;
this.guarantorFundingRepository = guarantorFundingRepository;
this.guarantorFundingTransactionRepository = guarantorFundingTransactionRepository;
this.accountTransfersWritePlatformService = accountTransfersWritePlatformService;
this.businessEventNotifierService = businessEventNotifierService;
this.depositAccountOnHoldTransactionRepository = depositAccountOnHoldTransactionRepository;
}
@PostConstruct
public void addListners() {
this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_APPROVED, new ValidateOnBusinessEvent());
this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_APPROVED, new HoldFundsOnBusinessEvent());
this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_UNDO_APPROVAL, new UndoAllFundTransactions());
this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_UNDO_DISBURSAL,
new ReverseAllFundsOnBusinessEvent());
this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_ADJUST_TRANSACTION,
new AdjustFundsOnBusinessEvent());
this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_MAKE_REPAYMENT,
new ReleaseFundsOnBusinessEvent());
this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_WRITTEN_OFF, new ReleaseAllFunds());
this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.LOAN_UNDO_WRITTEN_OFF,
new ReverseFundsOnBusinessEvent());
}
@Override
public void validateGuarantorBusinessRules(Loan loan) {
LoanProduct loanProduct = loan.loanProduct();
BigDecimal principal = loan.getPrincpal().getAmount();
if (loanProduct.isHoldGuaranteeFundsEnabled()) {
LoanProductGuaranteeDetails guaranteeData = loanProduct.getLoanProductGuaranteeDetails();
final List<Guarantor> existGuarantorList = this.guarantorRepository.findByLoan(loan);
BigDecimal mandatoryAmount = principal.multiply(guaranteeData.getMandatoryGuarantee()).divide(BigDecimal.valueOf(100));
BigDecimal minSelfAmount = principal.multiply(guaranteeData.getMinimumGuaranteeFromOwnFunds()).divide(BigDecimal.valueOf(100));
BigDecimal minExtGuarantee = principal.multiply(guaranteeData.getMinimumGuaranteeFromGuarantor()).divide(
BigDecimal.valueOf(100));
BigDecimal actualAmount = BigDecimal.ZERO;
BigDecimal actualSelfAmount = BigDecimal.ZERO;
BigDecimal actualExtGuarantee = BigDecimal.ZERO;
for (Guarantor guarantor : existGuarantorList) {
List<GuarantorFundingDetails> fundingDetails = guarantor.getGuarantorFundDetails();
for (GuarantorFundingDetails guarantorFundingDetails : fundingDetails) {
if (guarantorFundingDetails.getStatus().isActive() || guarantorFundingDetails.getStatus().isWithdrawn()
|| guarantorFundingDetails.getStatus().isCompleted()) {
if (guarantor.isSelfGuarantee()) {
actualSelfAmount = actualSelfAmount.add(guarantorFundingDetails.getAmount()).subtract(
guarantorFundingDetails.getAmountTransfered());
} else {
actualExtGuarantee = actualExtGuarantee.add(guarantorFundingDetails.getAmount()).subtract(
guarantorFundingDetails.getAmountTransfered());
}
}
}
}
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.guarantor");
if (actualSelfAmount.compareTo(minSelfAmount) == -1) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(GuarantorConstants.GUARANTOR_SELF_GUARANTEE_ERROR,
minSelfAmount);
}
if (actualExtGuarantee.compareTo(minExtGuarantee) == -1) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(GuarantorConstants.GUARANTOR_EXTERNAL_GUARANTEE_ERROR,
minExtGuarantee);
}
actualAmount = actualAmount.add(actualExtGuarantee).add(actualSelfAmount);
if (actualAmount.compareTo(mandatoryAmount) == -1) {
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(GuarantorConstants.GUARANTOR_MANDATORY_GUARANTEE_ERROR,
mandatoryAmount);
}
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors); }
}
}
/**
* Method assigns a guarantor to loan and blocks the funds on guarantor's
* account
*/
@Override
public void assignGuarantor(final GuarantorFundingDetails guarantorFundingDetails, final LocalDate transactionDate) {
if (guarantorFundingDetails.getStatus().isActive()) {
SavingsAccount savingsAccount = guarantorFundingDetails.getLinkedSavingsAccount();
savingsAccount.holdFunds(guarantorFundingDetails.getAmount());
if (savingsAccount.getWithdrawableBalance().compareTo(BigDecimal.ZERO) == -1) {
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.guarantor");
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(GuarantorConstants.GUARANTOR_INSUFFICIENT_BALANCE_ERROR,
savingsAccount.getId());
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.",
dataValidationErrors);
}
DepositAccountOnHoldTransaction onHoldTransaction = DepositAccountOnHoldTransaction.hold(savingsAccount,
guarantorFundingDetails.getAmount(), transactionDate);
GuarantorFundingTransaction guarantorFundingTransaction = new GuarantorFundingTransaction(guarantorFundingDetails, null,
onHoldTransaction);
guarantorFundingDetails.addGuarantorFundingTransactions(guarantorFundingTransaction);
this.depositAccountOnHoldTransactionRepository.save(onHoldTransaction);
}
}
/**
* Method releases(withdraw) a guarantor from loan and unblocks the funds on
* guarantor's account
*/
@Override
public void releaseGuarantor(final GuarantorFundingDetails guarantorFundingDetails, final LocalDate transactionDate) {
BigDecimal amoutForWithdraw = guarantorFundingDetails.getAmountRemaining();
if (amoutForWithdraw.compareTo(BigDecimal.ZERO) == 1 && (guarantorFundingDetails.getStatus().isActive())) {
SavingsAccount savingsAccount = guarantorFundingDetails.getLinkedSavingsAccount();
savingsAccount.releaseFunds(amoutForWithdraw);
DepositAccountOnHoldTransaction onHoldTransaction = DepositAccountOnHoldTransaction.release(savingsAccount, amoutForWithdraw,
transactionDate);
GuarantorFundingTransaction guarantorFundingTransaction = new GuarantorFundingTransaction(guarantorFundingDetails, null,
onHoldTransaction);
guarantorFundingDetails.addGuarantorFundingTransactions(guarantorFundingTransaction);
guarantorFundingDetails.releaseFunds(amoutForWithdraw);
guarantorFundingDetails.withdrawFunds(amoutForWithdraw);
guarantorFundingDetails.getLoanAccount().updateGuaranteeAmount(amoutForWithdraw.negate());
this.depositAccountOnHoldTransactionRepository.save(onHoldTransaction);
this.guarantorFundingRepository.save(guarantorFundingDetails);
}
}
/**
* Method is to recover funds from guarantor's in case loan is unpaid.
* (Transfers guarantee amount from guarantor's account to loan account and
* releases guarantor)
*/
@Override
public void transaferFundsFromGuarantor(final Loan loan) {
if (loan.getGuaranteeAmount().compareTo(BigDecimal.ZERO) != 1) { return; }
final List<Guarantor> existGuarantorList = this.guarantorRepository.findByLoan(loan);
final boolean isRegularTransaction = true;
final boolean isExceptionForBalanceCheck = true;
LocalDate transactionDate = LocalDate.now();
PortfolioAccountType fromAccountType = PortfolioAccountType.SAVINGS;
PortfolioAccountType toAccountType = PortfolioAccountType.LOAN;
final Long toAccountId = loan.getId();
final String description = "Payment from guarantor savings";
final Locale locale = null;
final DateTimeFormatter fmt = null;
final PaymentDetail paymentDetail = null;
final Integer fromTransferType = null;
final Integer toTransferType = null;
final Long chargeId = null;
final Integer loanInstallmentNumber = null;
final Integer transferType = AccountTransferType.LOAN_REPAYMENT.getValue();
final AccountTransferDetails accountTransferDetails = null;
final String noteText = null;
final String txnExternalId = null;
final SavingsAccount toSavingsAccount = null;
Long loanId = loan.getId();
for (Guarantor guarantor : existGuarantorList) {
final List<GuarantorFundingDetails> fundingDetails = guarantor.getGuarantorFundDetails();
for (GuarantorFundingDetails guarantorFundingDetails : fundingDetails) {
if (guarantorFundingDetails.getStatus().isActive()) {
final SavingsAccount fromSavingsAccount = guarantorFundingDetails.getLinkedSavingsAccount();
final Long fromAccountId = fromSavingsAccount.getId();
releaseLoanIds.put(loanId, guarantorFundingDetails.getId());
try {
BigDecimal remainingAmount = guarantorFundingDetails.getAmountRemaining();
if (loan.getGuaranteeAmount().compareTo(loan.getPrincpal().getAmount()) == 1) {
remainingAmount = remainingAmount.multiply(loan.getPrincpal().getAmount()).divide(loan.getGuaranteeAmount(),
roundingMode);
}
AccountTransferDTO accountTransferDTO = new AccountTransferDTO(transactionDate, remainingAmount, fromAccountType,
toAccountType, fromAccountId, toAccountId, description, locale, fmt, paymentDetail, fromTransferType,
toTransferType, chargeId, loanInstallmentNumber, transferType, accountTransferDetails, noteText,
txnExternalId, loan, toSavingsAccount, fromSavingsAccount, isRegularTransaction, isExceptionForBalanceCheck);
transferAmount(accountTransferDTO);
} finally {
releaseLoanIds.remove(loanId);
}
}
}
}
}
/**
* @param accountTransferDTO
*/
private void transferAmount(final AccountTransferDTO accountTransferDTO) {
try {
this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO);
} catch (final InsufficientAccountBalanceException e) {
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.guarantor");
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(GuarantorConstants.GUARANTOR_INSUFFICIENT_BALANCE_ERROR,
accountTransferDTO.getFromAccountId(), accountTransferDTO.getToAccountId());
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.",
dataValidationErrors);
}
}
/**
* Method reverses all blocked fund(both hold and release) transactions.
* example: reverses all transactions on undo approval of loan account.
*
*/
private void reverseAllFundTransaction(final Loan loan) {
if (loan.getGuaranteeAmount().compareTo(BigDecimal.ZERO) == 1) {
final List<Guarantor> existGuarantorList = this.guarantorRepository.findByLoan(loan);
List<GuarantorFundingDetails> guarantorFundingDetailList = new ArrayList<>();
for (Guarantor guarantor : existGuarantorList) {
final List<GuarantorFundingDetails> fundingDetails = guarantor.getGuarantorFundDetails();
for (GuarantorFundingDetails guarantorFundingDetails : fundingDetails) {
guarantorFundingDetails.undoAllTransactions();
guarantorFundingDetailList.add(guarantorFundingDetails);
}
}
if (!guarantorFundingDetailList.isEmpty()) {
loan.setGuaranteeAmount(null);
this.guarantorFundingRepository.save(guarantorFundingDetailList);
}
}
}
/**
* Method holds all guarantor's guarantee amount for a loan account.
* example: hold funds on approval of loan account.
*
*/
private void holdGuarantorFunds(final Loan loan) {
if (loan.loanProduct().isHoldGuaranteeFundsEnabled()) {
final List<Guarantor> existGuarantorList = this.guarantorRepository.findByLoan(loan);
List<GuarantorFundingDetails> guarantorFundingDetailList = new ArrayList<>();
List<DepositAccountOnHoldTransaction> onHoldTransactions = new ArrayList<>();
BigDecimal totalGuarantee = BigDecimal.ZERO;
List<Long> insufficientBalanceIds = new ArrayList<>();
for (Guarantor guarantor : existGuarantorList) {
final List<GuarantorFundingDetails> fundingDetails = guarantor.getGuarantorFundDetails();
for (GuarantorFundingDetails guarantorFundingDetails : fundingDetails) {
if (guarantorFundingDetails.getStatus().isActive()) {
SavingsAccount savingsAccount = guarantorFundingDetails.getLinkedSavingsAccount();
savingsAccount.holdFunds(guarantorFundingDetails.getAmount());
totalGuarantee = totalGuarantee.add(guarantorFundingDetails.getAmount());
DepositAccountOnHoldTransaction onHoldTransaction = DepositAccountOnHoldTransaction.hold(savingsAccount,
guarantorFundingDetails.getAmount(), loan.getApprovedOnDate());
onHoldTransactions.add(onHoldTransaction);
GuarantorFundingTransaction guarantorFundingTransaction = new GuarantorFundingTransaction(guarantorFundingDetails,
null, onHoldTransaction);
guarantorFundingDetails.addGuarantorFundingTransactions(guarantorFundingTransaction);
guarantorFundingDetailList.add(guarantorFundingDetails);
if (savingsAccount.getWithdrawableBalance().compareTo(BigDecimal.ZERO) == -1) {
insufficientBalanceIds.add(savingsAccount.getId());
}
}
}
}
if (!insufficientBalanceIds.isEmpty()) {
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.guarantor");
baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(GuarantorConstants.GUARANTOR_INSUFFICIENT_BALANCE_ERROR,
insufficientBalanceIds);
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.",
dataValidationErrors);
}
loan.setGuaranteeAmount(totalGuarantee);
if (!guarantorFundingDetailList.isEmpty()) {
this.depositAccountOnHoldTransactionRepository.save(onHoldTransactions);
this.guarantorFundingRepository.save(guarantorFundingDetailList);
}
}
}
/**
* Method releases all guarantor's guarantee amount(first external guarantee
* and then self guarantee) for a loan account in the portion of guarantee
* percentage on a paid principal. example: releases funds on repayments of
* loan account.
*
*/
private void releaseGuarantorFunds(final LoanTransaction loanTransaction) {
final Loan loan = loanTransaction.getLoan();
if (loan.getGuaranteeAmount().compareTo(BigDecimal.ZERO) == 1) {
final List<Guarantor> existGuarantorList = this.guarantorRepository.findByLoan(loan);
List<GuarantorFundingDetails> externalGuarantorList = new ArrayList<>();
List<GuarantorFundingDetails> selfGuarantorList = new ArrayList<>();
BigDecimal selfGuarantee = BigDecimal.ZERO;
BigDecimal guarantorGuarantee = BigDecimal.ZERO;
for (Guarantor guarantor : existGuarantorList) {
final List<GuarantorFundingDetails> fundingDetails = guarantor.getGuarantorFundDetails();
for (GuarantorFundingDetails guarantorFundingDetails : fundingDetails) {
if (guarantorFundingDetails.getStatus().isActive()) {
if (guarantor.isSelfGuarantee()) {
selfGuarantorList.add(guarantorFundingDetails);
selfGuarantee = selfGuarantee.add(guarantorFundingDetails.getAmountRemaining());
} else if (guarantor.isExistingCustomer()) {
externalGuarantorList.add(guarantorFundingDetails);
guarantorGuarantee = guarantorGuarantee.add(guarantorFundingDetails.getAmountRemaining());
}
}
}
}
BigDecimal amountForRelease = loanTransaction.getPrincipalPortion();
BigDecimal totalGuaranteeAmount = loan.getGuaranteeAmount();
BigDecimal principal = loan.getPrincpal().getAmount();
if((amountForRelease!=null)&&(totalGuaranteeAmount!=null))
{
amountForRelease = amountForRelease.multiply(totalGuaranteeAmount).divide(principal,this.roundingMode);
List<DepositAccountOnHoldTransaction> accountOnHoldTransactions = new ArrayList<>();
BigDecimal amountLeft = calculateAndRelaseGuarantorFunds(externalGuarantorList, guarantorGuarantee, amountForRelease,
loanTransaction, accountOnHoldTransactions);
if (amountLeft.compareTo(BigDecimal.ZERO) == 1) {
calculateAndRelaseGuarantorFunds(selfGuarantorList, selfGuarantee, amountLeft, loanTransaction, accountOnHoldTransactions);
externalGuarantorList.addAll(selfGuarantorList);
}
if (!externalGuarantorList.isEmpty()) {
this.depositAccountOnHoldTransactionRepository.save(accountOnHoldTransactions);
this.guarantorFundingRepository.save(externalGuarantorList);
}
}
}
}
/**
* Method releases all guarantor's guarantee amount. example: releases funds
* on write-off of a loan account.
*
*/
private void releaseAllGuarantors(final LoanTransaction loanTransaction) {
Loan loan = loanTransaction.getLoan();
if (loan.getGuaranteeAmount().compareTo(BigDecimal.ZERO) == 1) {
final List<Guarantor> existGuarantorList = this.guarantorRepository.findByLoan(loan);
List<GuarantorFundingDetails> saveGuarantorFundingDetails = new ArrayList<>();
List<DepositAccountOnHoldTransaction> onHoldTransactions = new ArrayList<>();
for (Guarantor guarantor : existGuarantorList) {
final List<GuarantorFundingDetails> fundingDetails = guarantor.getGuarantorFundDetails();
for (GuarantorFundingDetails guarantorFundingDetails : fundingDetails) {
BigDecimal amoutForRelease = guarantorFundingDetails.getAmountRemaining();
if (amoutForRelease.compareTo(BigDecimal.ZERO) == 1 && (guarantorFundingDetails.getStatus().isActive())) {
SavingsAccount savingsAccount = guarantorFundingDetails.getLinkedSavingsAccount();
savingsAccount.releaseFunds(amoutForRelease);
DepositAccountOnHoldTransaction onHoldTransaction = DepositAccountOnHoldTransaction.release(savingsAccount,
amoutForRelease, loanTransaction.getTransactionDate());
onHoldTransactions.add(onHoldTransaction);
GuarantorFundingTransaction guarantorFundingTransaction = new GuarantorFundingTransaction(guarantorFundingDetails,
loanTransaction, onHoldTransaction);
guarantorFundingDetails.addGuarantorFundingTransactions(guarantorFundingTransaction);
guarantorFundingDetails.releaseFunds(amoutForRelease);
saveGuarantorFundingDetails.add(guarantorFundingDetails);
}
}
}
if (!saveGuarantorFundingDetails.isEmpty()) {
this.depositAccountOnHoldTransactionRepository.save(onHoldTransactions);
this.guarantorFundingRepository.save(saveGuarantorFundingDetails);
}
}
}
/**
* Method releases guarantor's guarantee amount on transferring guarantee
* amount to loan account. example: on recovery of guarantee funds from
* guarantor's.
*/
private void completeGuarantorFund(final LoanTransaction loanTransaction) {
Loan loan = loanTransaction.getLoan();
GuarantorFundingDetails guarantorFundingDetails = this.guarantorFundingRepository.findOne(releaseLoanIds.get(loan.getId()));
if (guarantorFundingDetails != null) {
BigDecimal amountForRelease = loanTransaction.getAmount(loan.getCurrency()).getAmount();
BigDecimal guarantorGuarantee = amountForRelease;
List<GuarantorFundingDetails> guarantorList = Arrays.asList(guarantorFundingDetails);
final List<DepositAccountOnHoldTransaction> accountOnHoldTransactions = new ArrayList<>();
calculateAndRelaseGuarantorFunds(guarantorList, guarantorGuarantee, amountForRelease, loanTransaction,
accountOnHoldTransactions);
this.depositAccountOnHoldTransactionRepository.save(accountOnHoldTransactions);
this.guarantorFundingRepository.save(guarantorFundingDetails);
}
}
private BigDecimal calculateAndRelaseGuarantorFunds(List<GuarantorFundingDetails> guarantorList, BigDecimal totalGuaranteeAmount,
BigDecimal amountForRelease, LoanTransaction loanTransaction,
final List<DepositAccountOnHoldTransaction> accountOnHoldTransactions) {
BigDecimal amountLeft = amountForRelease;
for (GuarantorFundingDetails fundingDetails : guarantorList) {
BigDecimal guarantorAmount = amountForRelease.multiply(fundingDetails.getAmountRemaining()).divide(totalGuaranteeAmount,
roundingMode);
if (fundingDetails.getAmountRemaining().compareTo(guarantorAmount) < 1) {
guarantorAmount = fundingDetails.getAmountRemaining();
}
fundingDetails.releaseFunds(guarantorAmount);
SavingsAccount savingsAccount = fundingDetails.getLinkedSavingsAccount();
savingsAccount.releaseFunds(guarantorAmount);
DepositAccountOnHoldTransaction onHoldTransaction = DepositAccountOnHoldTransaction.release(savingsAccount, guarantorAmount,
loanTransaction.getTransactionDate());
accountOnHoldTransactions.add(onHoldTransaction);
GuarantorFundingTransaction guarantorFundingTransaction = new GuarantorFundingTransaction(fundingDetails, loanTransaction,
onHoldTransaction);
fundingDetails.addGuarantorFundingTransactions(guarantorFundingTransaction);
amountLeft = amountLeft.subtract(guarantorAmount);
}
return amountLeft;
}
/**
* Method reverses the fund release transactions in case of loan transaction
* reversed
*/
private void reverseTransaction(final List<Long> loanTransactionIds) {
List<GuarantorFundingTransaction> fundingTransactions = this.guarantorFundingTransactionRepository
.fetchGuarantorFundingTransactions(loanTransactionIds);
for (GuarantorFundingTransaction fundingTransaction : fundingTransactions) {
fundingTransaction.reverseTransaction();
}
if (!fundingTransactions.isEmpty()) {
this.guarantorFundingTransactionRepository.save(fundingTransactions);
}
}
private class ValidateOnBusinessEvent implements BusinessEventListner {
@Override
public void businessEventToBeExecuted(@SuppressWarnings("unused") Map<BUSINESS_ENTITY, Object> businessEventEntity) {}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN);
if (entity instanceof Loan) {
Loan loan = (Loan) entity;
validateGuarantorBusinessRules(loan);
}
}
}
private class HoldFundsOnBusinessEvent implements BusinessEventListner {
@Override
public void businessEventToBeExecuted(@SuppressWarnings("unused") Map<BUSINESS_ENTITY, Object> businessEventEntity) {}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN);
if (entity instanceof Loan) {
Loan loan = (Loan) entity;
holdGuarantorFunds(loan);
}
}
}
private class ReleaseFundsOnBusinessEvent implements BusinessEventListner {
@Override
public void businessEventToBeExecuted(@SuppressWarnings("unused") Map<BUSINESS_ENTITY, Object> businessEventEntity) {}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN_TRANSACTION);
if (entity instanceof LoanTransaction) {
LoanTransaction loanTransaction = (LoanTransaction) entity;
if (releaseLoanIds.containsKey(loanTransaction.getLoan().getId())) {
completeGuarantorFund(loanTransaction);
} else {
releaseGuarantorFunds(loanTransaction);
}
}
}
}
private class ReverseFundsOnBusinessEvent implements BusinessEventListner {
@Override
public void businessEventToBeExecuted(@SuppressWarnings("unused") Map<BUSINESS_ENTITY, Object> businessEventEntity) {}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN_TRANSACTION);
if (entity instanceof LoanTransaction) {
LoanTransaction loanTransaction = (LoanTransaction) entity;
List<Long> reersedTransactions = new ArrayList<>(1);
reersedTransactions.add(loanTransaction.getId());
reverseTransaction(reersedTransactions);
}
}
}
private class AdjustFundsOnBusinessEvent implements BusinessEventListner {
@Override
public void businessEventToBeExecuted(@SuppressWarnings("unused") Map<BUSINESS_ENTITY, Object> businessEventEntity) {}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN_ADJUSTED_TRANSACTION);
if (entity instanceof LoanTransaction) {
LoanTransaction loanTransaction = (LoanTransaction) entity;
List<Long> reersedTransactions = new ArrayList<>(1);
reersedTransactions.add(loanTransaction.getId());
reverseTransaction(reersedTransactions);
}
Object transactionentity = businessEventEntity.get(BUSINESS_ENTITY.LOAN_TRANSACTION);
if (transactionentity != null && transactionentity instanceof LoanTransaction) {
LoanTransaction loanTransaction = (LoanTransaction) transactionentity;
releaseGuarantorFunds(loanTransaction);
}
}
}
private class ReverseAllFundsOnBusinessEvent implements BusinessEventListner {
@Override
public void businessEventToBeExecuted(@SuppressWarnings("unused") Map<BUSINESS_ENTITY, Object> businessEventEntity) {}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN);
if (entity instanceof Loan) {
Loan loan = (Loan) entity;
List<Long> reersedTransactions = new ArrayList<>(1);
reersedTransactions.addAll(loan.findExistingTransactionIds());
reverseTransaction(reersedTransactions);
}
}
}
private class UndoAllFundTransactions implements BusinessEventListner {
@Override
public void businessEventToBeExecuted(@SuppressWarnings("unused") Map<BUSINESS_ENTITY, Object> businessEventEntity) {}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN);
if (entity instanceof Loan) {
Loan loan = (Loan) entity;
reverseAllFundTransaction(loan);
}
}
}
private class ReleaseAllFunds implements BusinessEventListner {
@Override
public void businessEventToBeExecuted(@SuppressWarnings("unused") Map<BUSINESS_ENTITY, Object> businessEventEntity) {}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BUSINESS_ENTITY.LOAN_TRANSACTION);
if (entity instanceof LoanTransaction) {
LoanTransaction loanTransaction = (LoanTransaction) entity;
releaseAllGuarantors(loanTransaction);
}
}
}
}
|
package org.eclipse.mylyn.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.mylyn.jira.tests.AllJiraTests;
import org.eclipse.mylyn.trac.tests.AllTracTests;
import org.eclipse.mylyn.xplanner.tests.AllXPlannerTests;
/**
* @author Shawn Minto
*/
public class AllConnectorTests {
public static Test suite() {
// the order of these tests might still matter, but shouldn't
TestSuite suite = new TestSuite("All Connector Tests for org.eclipse.mylyn.tests");
// FIXME re-enable suite.addTest(AllBugzillaTests.suite());
suite.addTest(AllJiraTests.suite());
suite.addTest(AllTracTests.suite());
suite.addTest(AllXPlannerTests.suite());
return suite;
}
}
|
package eu.liveandgov.wp1.sensor_miner.sensors;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.location.Location;
import android.net.wifi.ScanResult;
import android.os.Build;
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.json.JSONStringer;
import java.util.List;
import eu.liveandgov.wp1.human_activity_recognition.containers.MotionSensorValue;
import eu.liveandgov.wp1.sensor_miner.GlobalContext;
import eu.liveandgov.wp1.sensor_miner.sensors.sensor_value_objects.GpsSensorValue;
import static eu.liveandgov.wp1.sensor_miner.configuration.SsfFileFormat.SSF_ACCELEROMETER;
import static eu.liveandgov.wp1.sensor_miner.configuration.SsfFileFormat.SSF_GOOGLE_ACTIVITY;
import static eu.liveandgov.wp1.sensor_miner.configuration.SsfFileFormat.SSF_GPS;
import static eu.liveandgov.wp1.sensor_miner.configuration.SsfFileFormat.SSF_GRAVITY;
import static eu.liveandgov.wp1.sensor_miner.configuration.SsfFileFormat.SSF_GYROSCOPE;
import static eu.liveandgov.wp1.sensor_miner.configuration.SsfFileFormat.SSF_LINEAR_ACCELERATION;
import static eu.liveandgov.wp1.sensor_miner.configuration.SsfFileFormat.SSF_MAGNETOMETER;
import static eu.liveandgov.wp1.sensor_miner.configuration.SsfFileFormat.SSF_ROTATION;
import static eu.liveandgov.wp1.sensor_miner.configuration.SsfFileFormat.SSF_TAG;
public class SensorSerializer {
public static MotionSensorValue parseMotionEvent(String event) {
MotionSensorValue newEvent = new MotionSensorValue();
// Meta data
String[] temp = event.split(",");
newEvent.type = temp[0];
newEvent.time = Long.parseLong(temp[1]);
newEvent.id = temp[2];
// Values
String[] values = temp[3].split(" ");
newEvent.x = Float.parseFloat(values[0]);
newEvent.y = Float.parseFloat(values[1]);
newEvent.z = Float.parseFloat(values[2]);
return newEvent;
}
public static GpsSensorValue parseGpsEvent(String event) {
GpsSensorValue newEvent = new GpsSensorValue();
// Meta data
String[] temp = event.split(",");
newEvent.type = temp[0];
newEvent.time = Long.parseLong(temp[1]);
newEvent.id = temp[2];
// Values
String[] values = temp[3].split(" ");
newEvent.lat = Float.parseFloat(values[0]);
newEvent.lon = Float.parseFloat(values[1]);
newEvent.alt = Float.parseFloat(values[2]);
return newEvent;
}
public static String fromSensorEvent(SensorEvent event) {
int sensorType= event.sensor.getType();
// If build-version is above jelly-bean mr1 (17), timestamps of the sensors are already in
// utc, otherwise convert by rebasing them on the uptime
long timestamp_ms;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
timestamp_ms = (long) (event.timestamp / 1E6);
}
else
{
timestamp_ms = (long) (System.currentTimeMillis() + (event.timestamp - System.nanoTime()) / 1E6);
}
if ( sensorType == Sensor.TYPE_ACCELEROMETER){
return fillStringFloats(SSF_ACCELEROMETER, timestamp_ms, GlobalContext.getUserId(), event.values);
} else if (sensorType == Sensor.TYPE_LINEAR_ACCELERATION){
return fillStringFloats(SSF_LINEAR_ACCELERATION, timestamp_ms, GlobalContext.getUserId(), event.values);
} else if (sensorType == Sensor.TYPE_GRAVITY) {
return fillStringFloats(SSF_GRAVITY, timestamp_ms, GlobalContext.getUserId(), event.values);
} else if (sensorType == Sensor.TYPE_GYROSCOPE) {
return fillStringFloats(SSF_GYROSCOPE, timestamp_ms, GlobalContext.getUserId(), event.values);
} else if (sensorType == Sensor.TYPE_MAGNETIC_FIELD) {
return fillStringFloats(SSF_MAGNETOMETER, timestamp_ms, GlobalContext.getUserId(), event.values);
} else if (sensorType == Sensor.TYPE_ROTATION_VECTOR) {
return fillStringFloats(SSF_ROTATION, timestamp_ms, GlobalContext.getUserId(), event.values);
}
return "ERR," + timestamp_ms + ",,Unknown sensor " + sensorType;
}
public static String fromScanResults(long timestamp_ms, List<ScanResult> scanResults) {
StringBuilder builder = new StringBuilder();
boolean separate = false;
for(ScanResult scanResult : scanResults)
{
if(separate)
{
// Separate entries of the scan result list by semicolon
builder.append(';');
}
// Write each scan result as a tuple of Escaped SSID/Escaped BSSID/Frequency in MHz/Level in dBm
builder.append( "\"" + StringEscapeUtils.escapeJava(scanResult.SSID) + "\"");
builder.append('/');
builder.append( "\"" + StringEscapeUtils.escapeJava(scanResult.BSSID) + "\"");
builder.append('/');
builder.append(scanResult.frequency);
builder.append('/');
builder.append(scanResult.level);
separate = true;
}
return fillString(SSF_WIFI, timestamp_ms, GlobalContext.getUserId(), builder.toString());
}
public static String fromLocation(Location location) {
return fillStringDoubles(SSF_GPS, location.getTime(), GlobalContext.getUserId(), new double[]{location.getLatitude(), location.getLongitude(), location.getAltitude()});
}
public static String fromTag(String tag) {
return fillDefaults(SSF_TAG, "\""+ StringEscapeUtils.escapeJava(tag) +"\"");
}
// GOOGLE ACTIVITY RECOGNITION HELPER
public static String fromGoogleActivity(ActivityRecognitionResult result) {
DetectedActivity detectedActivity = result.getMostProbableActivity();
return fillStringObjects(SSF_GOOGLE_ACTIVITY, result.getTime(), GlobalContext.getUserId(),
new Object[]{getActivityNameFromType(detectedActivity.getType()),
detectedActivity.getConfidence()});
}
private static String getActivityNameFromType(int activityType) {
switch(activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.TILTING:
return "tilting";
}
return "unknown";
}
/**
* Writes sensor values in SSF format. (cf. project Wiki)
* @param type of Sensor
* @param timestamp of recording in ms
* @param deviceId unique device identified
* @param value String
* @return ssfRow
*/
private static String fillString(String type, long timestamp, String deviceId, String value) {
return String.format("%s,%d,%s,%s", type, timestamp, deviceId, value);
}
private static String fillStringFloats(String type, long timestamp, String deviceId, float[] values) {
String valueString = "";
for (float value : values) {
valueString += value + " ";
}
return fillString(type, timestamp, deviceId, valueString);
}
private static String fillStringDoubles(String type, long timestamp, String deviceId, double[] values) {
String valueString = "";
for (double value : values) {
valueString += value + " ";
}
return fillString(type, timestamp, deviceId, valueString);
}
private static String fillStringObjects(String type, long timestamp, String deviceId, Object[] values) {
String valueString = "";
for (Object value : values) {
valueString += value + " ";
}
return fillString(type, timestamp, deviceId, valueString);
}
public static String fillDefaults(String prefix, String value) {
return fillString(prefix, System.currentTimeMillis(), GlobalContext.getUserId(), value);
}
}
|
package org.motechproject.scheduletracking.api.service.impl;
import org.joda.time.LocalDate;
import org.junit.Test;
import org.motechproject.model.Time;
import org.motechproject.scheduletracking.api.service.EnrollmentRequest;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.motechproject.util.DateUtil.*;
public class EnrollmentRequestTest {
@Test
public void shouldReturnFalseIfStartingMilestoneNotProvided() {
EnrollmentRequest enrollmentRequest = new EnrollmentRequest("externalId", "scheduleName", new Time(10, 10), LocalDate.now(), null, null, null, null, null);
assertFalse("Starting milestone not expected, but was provided!", enrollmentRequest.enrollIntoMilestone());
}
@Test
public void shouldReturnTrueIfStartingMilestoneProvided() {
EnrollmentRequest enrollmentRequest = new EnrollmentRequest("externalId", "scheduleName", new Time(10, 10), LocalDate.now(), null, null, null, "Milestone", null);
assertTrue("Starting milestone expected, but was not provided!", enrollmentRequest.enrollIntoMilestone());
}
@Test
public void shouldReturnFalseIfEmptyStartingMilestoneProvided() {
EnrollmentRequest enrollmentRequest = new EnrollmentRequest("externalId", "scheduleName", new Time(10, 10), LocalDate.now(), null, null, null, "", null);
assertFalse("Starting milestone not expected, but was provided!", enrollmentRequest.enrollIntoMilestone());
}
@Test
public void shouldReturnFalseIfNullStartingMilestoneProvided() {
EnrollmentRequest enrollmentRequest = new EnrollmentRequest("externalId", "scheduleName", new Time(10, 10), LocalDate.now(), null, null, null, null, null);
assertFalse("Starting milestone not expected, but was provided!", enrollmentRequest.enrollIntoMilestone());
}
@Test
public void enrollmentDateShouldBeTodayAndEnrollmentTimeShouldBeMidnightWhenNotDefined() {
EnrollmentRequest enrollmentRequest = new EnrollmentRequest("externalId", "scheduleName", new Time(10, 10), null, null, null, null, null, null);
assertEquals(newDateTime(today()), enrollmentRequest.getEnrollmentDateTime());
}
@Test
public void shouldReturnEnrollmentDateTimeWithGivenDateAndTime() {
EnrollmentRequest enrollmentRequest = new EnrollmentRequest("externalId", "scheduleName", new Time(10, 10), null, null, newDate(2012, 3, 22), new Time(8, 30), null, null);
assertEquals(newDateTime(2012, 3, 22, 8, 30, 0), enrollmentRequest.getEnrollmentDateTime());
}
@Test
public void referenceDateShouldBeTodayAndReferenceTimeShouldBeMidnightWhenNotDefined() {
EnrollmentRequest referenceRequest = new EnrollmentRequest("externalId", "scheduleName", new Time(10, 10), null, null, null, null, null, null);
assertEquals(newDateTime(today()), referenceRequest.getReferenceDateTime());
}
@Test
public void shouldReturnReferenceDateTimeWithGivenDateAndTime() {
EnrollmentRequest referenceRequest = new EnrollmentRequest("externalId", "scheduleName", new Time(10, 10), newDate(2012, 3, 22), new Time(8, 30), null, null, null, null);
assertEquals(newDateTime(2012, 3, 22, 8, 30, 0), referenceRequest.getReferenceDateTime());
}
}
|
package net.mcft.copy.aho.config;
public enum EnumPreset {
// [ REGENERATION ] [ HURT PENALTY ] [ RESPAWN ]
PEACEFUL ( 1.5, 0, 10, 2.5, 1.5, 3.0, 10.0, 16.0, 20, 20, 0, 0.0 ),
EASY ( 4.0, 10, 15, 2.0, 3.0, 8.0, 16.0, 20.0, 20, 16, 0, 0.0 ),
NORMAL ( 10.0, 13, 17, 3.0, 6.0, 16.0, 40.0, 35.0, 16, 16, 0, 0.0 ),
HARD ( 30.0, 14, 18, 3.5, 12.0, 35.0, 120.0, 50.0, 12, 14, 0, 0.0 ),
HARDCORE ( 60.0, 14, 18, 4.0, 20.0, 80.0, 240.0, 60.0, 8, 12, 0, 0.0 ),
ULTRAHARDCORE ( 0.0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 6, 10, 0, 0.0 ),
CUSTOM ( 0.0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0, 0.0 );
public final double regenHealTime;
public final int regenHungerMinimum;
public final int regenHungerMaximum;
public final double regenExhaustion;
public final double hurtTime;
public final double hurtTimeMaximum;
public final double hurtMaximum;
public final double hurtBuffer;
public final int respawnHealth;
public final int respawnFood;
public final int respawnShield;
public final double respawnPenalty;
EnumPreset(double regenHealTime, int regenHungerMinimum, int regenHungerMaximum, double regenExhaustion,
double hurtTime, double hurtTimeMaximum, double hurtMaximum, double hurtBuffer,
int respawnHealth, int respawnFood, int respawnShield, double respawnPenalty) {
this.regenHealTime = regenHealTime;
this.regenHungerMinimum = regenHungerMinimum;
this.regenHungerMaximum = regenHungerMaximum;
this.regenExhaustion = regenExhaustion;
this.hurtTime = hurtTime;
this.hurtTimeMaximum = hurtTimeMaximum;
this.hurtMaximum = hurtMaximum;
this.hurtBuffer = hurtBuffer;
this.respawnHealth = respawnHealth;
this.respawnFood = respawnFood;
this.respawnShield = respawnShield;
this.respawnPenalty = respawnPenalty;
}
}
|
package org.wolfgang.contrail.ecosystem.factory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.wolfgang.common.lang.TypeUtils;
import org.wolfgang.contrail.component.CannotCreateComponentException;
import org.wolfgang.contrail.component.Component;
import org.wolfgang.contrail.component.ComponentConnectionRejectedException;
import org.wolfgang.contrail.component.DestinationComponent;
import org.wolfgang.contrail.component.PipelineComponent;
import org.wolfgang.contrail.component.RouterSourceComponent;
import org.wolfgang.contrail.component.SourceComponent;
import org.wolfgang.contrail.component.bound.CannotCreateDataSenderException;
import org.wolfgang.contrail.component.bound.DataReceiver;
import org.wolfgang.contrail.component.bound.DataSender;
import org.wolfgang.contrail.component.bound.DataSenderFactory;
import org.wolfgang.contrail.component.bound.InitialComponent;
import org.wolfgang.contrail.component.bound.TerminalComponent;
import org.wolfgang.contrail.component.bound.TerminalFactory;
import org.wolfgang.contrail.component.multiple.RouterSourceFactory;
import org.wolfgang.contrail.component.pipeline.PipelineFactory;
import org.wolfgang.contrail.ecosystem.EcosystemImpl;
import org.wolfgang.contrail.ecosystem.key.RegisteredUnitEcosystemKey;
import org.wolfgang.contrail.ecosystem.model.Binder;
import org.wolfgang.contrail.ecosystem.model.Ecosystem;
import org.wolfgang.contrail.ecosystem.model.Flow;
import org.wolfgang.contrail.ecosystem.model.Flow.Item;
import org.wolfgang.contrail.ecosystem.model.Pipeline;
import org.wolfgang.contrail.ecosystem.model.Router;
import org.wolfgang.contrail.ecosystem.model.Terminal;
import org.wolfgang.contrail.link.ComponentLinkManager;
import org.wolfgang.contrail.link.ComponentLinkManagerImpl;
/**
* <code>EcosystemFactory</code>
*
* @author Didier Plaindoux
* @version 1.0
*/
@SuppressWarnings("rawtypes")
public final class EcosystemFactory {
private class DataSenderFactoryImpl<U, D> implements DataSenderFactory<U, D> {
private final Item[] items;
/**
* Constructor
*
* @param items
*/
private DataSenderFactoryImpl(Item[] items) {
super();
this.items = items;
}
@Override
public DataSender<U> create(DataReceiver<D> receiver) throws CannotCreateDataSenderException {
try {
final InitialComponent<U, D> initialComponent = new InitialComponent<U, D>(receiver);
EcosystemFactory.this.create(initialComponent, items);
return initialComponent.getDataSender();
} catch (CannotCreateComponentException e) {
throw new CannotCreateDataSenderException(e);
} catch (ComponentConnectionRejectedException e) {
throw new CannotCreateDataSenderException(e);
}
}
}
private final ComponentLinkManager componentLinkManager;
/**
* The class loader to use when components must be created
*/
private final ClassLoader classLoader;
/**
* Aliasing
*/
private final Map<String, Component> aliasedComponents;
/**
* Declared pipelines
*/
private final Map<String, Pipeline> pipelines;
/**
* Declared pipelines
*/
private final Map<String, Router> routers;
/**
* Declared terminal
*/
private final Map<String, Terminal> terminals;
/**
* Declared terminal
*/
private final Map<String, Flow> flows;
{
this.componentLinkManager = new ComponentLinkManagerImpl();
this.aliasedComponents = new HashMap<String, Component>();
this.pipelines = new HashMap<String, Pipeline>();
this.terminals = new HashMap<String, Terminal>();
this.routers = new HashMap<String, Router>();
this.flows = new HashMap<String, Flow>();
this.classLoader = EcosystemFactory.class.getClassLoader();
}
/**
* Internal method dedicated to the component creation
*
* @param name
* @return
* @throws CannotCreateComponentException
* @throws CannotCreateDataSenderException
* @throws ComponentConnectionRejectedException
*/
private Component create(final Component source, final Item[] items) throws CannotCreateComponentException, CannotCreateDataSenderException, ComponentConnectionRejectedException {
Component current = source;
for (Item item : items) {
final Component component;
final String name = item.getName();
if (item.asAlias()) {
if (aliasedComponents.containsKey(item.getAlias())) {
component = aliasedComponents.get(item.getAlias());
} else {
if (pipelines.containsKey(name)) {
component = create(pipelines.get(name));
} else if (terminals.containsKey(name)) {
component = create(terminals.get(name));
} else if (routers.containsKey(name)) {
component = create(routers.get(name));
} else if (flows.containsKey(name)) {
component = create(current, Flow.decompose(flows.get(name).getValue()));
} else {
return null;
}
if (component == null) {
throw new CannotCreateDataSenderException();
} else {
aliasedComponents.put(item.getAlias(), component);
}
}
} else {
if (pipelines.containsKey(name)) {
component = create(pipelines.get(name));
} else if (terminals.containsKey(name)) {
component = create(terminals.get(name));
} else if (routers.containsKey(name)) {
component = create(routers.get(name));
} else if (flows.containsKey(name)) {
component = create(current, Flow.decompose(flows.get(name).getValue()));
} else {
return null;
}
if (component == null) {
throw new CannotCreateDataSenderException();
}
}
componentLinkManager.connect((SourceComponent) current, (DestinationComponent) component);
current = component;
}
return current;
}
/**
* @param pipeline
* @return
* @throws CannotCreateComponentException
*/
private PipelineComponent create(Pipeline pipeline) throws CannotCreateComponentException {
final String factory = pipeline.getFactory();
final List<String> parameters = pipeline.getParameters();
return PipelineFactory.create(classLoader, factory, parameters.toArray(new String[parameters.size()]));
}
/**
* @param pipeline
* @return
* @throws CannotCreateComponentException
*/
private TerminalComponent create(Terminal terminal) throws CannotCreateComponentException {
final String factory = terminal.getFactory();
final List<String> parameters = terminal.getParameters();
return TerminalFactory.create(classLoader, factory, parameters.toArray(new String[parameters.size()]));
}
/**
* @param pipeline
* @return
* @throws CannotCreateComponentException
*/
private RouterSourceComponent create(Router router) throws CannotCreateComponentException {
final String factory = router.getFactory();
final List<String> parameters = router.getParameters();
return RouterSourceFactory.create(classLoader, factory, parameters.toArray(new String[parameters.size()]), new RouterSourceFactory.Client[0]);
}
/**
* @param terminal
*/
private void register(Terminal terminal) {
this.terminals.put(terminal.getName(), terminal);
}
/**
* @param pipeline
*/
private void register(Pipeline pipeline) {
this.pipelines.put(pipeline.getName(), pipeline);
}
/**
* @param router
*/
private void register(Router router) {
this.routers.put(router.getName(), router);
}
/**
* @param router
*/
private void register(Flow flow) {
this.flows.put(flow.getName(), flow);
}
/**
* Main method called whether an ecosystem must be created
*
* @param ecosystem
* @throws ClassNotFoundException
*/
public org.wolfgang.contrail.ecosystem.Ecosystem build(Ecosystem ecosystem) throws ClassNotFoundException {
final EcosystemImpl ecosystemImpl = new EcosystemImpl();
for (Terminal terminal : ecosystem.getTerminals()) {
register(terminal);
}
for (Pipeline pipeline : ecosystem.getPipelines()) {
register(pipeline);
}
for (Router router : ecosystem.getRouters()) {
register(router);
}
for (Flow flow : ecosystem.getFlows()) {
register(flow);
}
for (Binder binder : ecosystem.getBinders()) {
final String name = binder.getName();
final Class<?> typeIn = TypeUtils.getType(binder.getTypeIn());
final Class<?> typeOut = TypeUtils.getType(binder.getTypeOut());
final RegisteredUnitEcosystemKey key = new RegisteredUnitEcosystemKey(name, typeIn, typeOut);
ecosystemImpl.addFactory(key, new DataSenderFactoryImpl(Flow.decompose(binder.getFlow())));
}
return ecosystemImpl;
}
}
|
package net.sf.jalita.server;
import java.util.Hashtable;
import java.util.Iterator;
import java.net.*;
import java.util.Vector;
import java.io.*;
import net.sf.jalita.io.TerminalIOInterface;
import net.sf.jalita.util.Configuration;
import java.util.Enumeration;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
/**
* Administrates the connected terminals
*
* @author Daniel "tentacle" Galn y Martins
* @version $Revision: 1.3 $
*/
public class SessionManager implements Runnable {
// constants
/** Lock-object for the cleanup */
private static final Object cleanupLockObject = new Object();
// class variables
/** log4j reference */
public final static Logger log = Logger.getLogger(Configuration.class);
/** Jalita configuration-properties */
private static Configuration config = Configuration.getConfiguration();
/** Singleton-object for the SessionManagers */
private static SessionManager sessionManager = null;
/**
* Locates the Session via IP.
* Key = InetAdress-Object(IP-Adresse); Value = Session-Object
* Consider that the Key may change on conversion to IPv6.
*/
private static Hashtable sessions = new Hashtable();
/** Contains TerminalIOInterface-Objects which are interrupted, but are not closed */
private static Vector brokenSessions = new Vector();
/** Contains Session-Objects wich are cloed, for e.g. by time-out */
private static Vector closedSessions = new Vector();
/** Globale SessionObject which all Sessions can access */
private static GlobalObject globalObject;
// class methods
/** Returns the Singleton */
public static SessionManager getSessionManager() {
if (sessionManager == null ) {
sessionManager = new SessionManager();
}
return sessionManager;
}
// instance variables
/** Tells us if the cleanup Thread is running in background */
private boolean cleanupActive = true;
// constructors
/** Creates a new SessionManager Object */
private SessionManager() {
log.debug("Creating instance of SessionManager");
// Starts the cleanup thread in background, which manages broken and closed connections, ass well as time outs
Thread cleanupThread = new Thread(this);
cleanupThread.start();
}
// private & protected methods
/** Validates connections from the Sessions and frees resources */
private void cleanup() {
synchronized (cleanupLockObject) {
checkSessions();
cleanupBrokenSession();
cleanupClosedSession();
}
}
/** Clearing Sessions which connections are broken */
private void cleanupBrokenSession() {
// to call ".size()" in the loop (processing FIFO)
boolean brokenObjectsLeft = true;
// cleanup loop
while (brokenObjectsLeft) {
synchronized(brokenSessions) {
if (brokenSessions.size() > 0) {
// retrieve next connection
Object next = brokenSessions.firstElement();
if (next instanceof TerminalIOInterface) {
TerminalIOInterface nextIO = (TerminalIOInterface)next;
log.debug("Closing Socket from broken Session: " + nextIO);
closeTerminalIO(nextIO);
}
// remove from the brokenSession-List, if available
brokenSessions.removeElement(next);
}
else {
brokenObjectsLeft = false;
}
}
}
}
/** Clearing Sessions which are closed normally */
private void cleanupClosedSession() {
// cleanup loop
while (closedSessions.size() != 0) {
// get a died one
Session nextOne = (Session)closedSessions.firstElement();
log.debug("Closing Socket from closed Session: " + nextOne);
closeTerminalIO(nextOne.getIO());
nextOne.finish();
// remove it from the closedSession-List and list of the running Sessions
closedSessions.removeElementAt(0);
}
}
/** Validates the Sessions if they are broken (interrupted), closed or have a timeout. */
private void checkSessions() {
Enumeration enumSessions = sessions.elements();
Enumeration enumKeys = sessions.keys();
while (enumSessions.hasMoreElements()) {
Session nextSession = (Session)enumSessions.nextElement();
String nextKey = (String)enumKeys.nextElement();
if (nextSession.isTimeout()) {
log.debug("Session-Timeout for '" + nextSession + "'");
sessions.remove(nextKey);
if (nextSession.getIO() != null) {
brokenSessions.remove(nextSession.getIO());
registerClosedSession(nextSession);
}
}
}
}
/** Closes IO to a terminal. */
private void closeTerminalIO(TerminalIOInterface io) {
try {
io.close();
}
catch (IOException ex) {
log.warn("Could not close TerminalIO: " + io);
}
}
// public methods
/** Adds a new Sesion. One IP is associated to one Session. */
public void addSession(Socket socket) {
Session newSession = null;
String sessionID = socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
if(config.getServerMaxSessionsPerHost() == 1){
sessionID = socket.getInetAddress().getHostAddress();
}
Session oldSession = (Session)sessions.get(sessionID);
int sessionCount = 0;
// New Session to not registered IP
if (oldSession == null) {
for(Iterator<String> iter = sessions.keySet().iterator(); iter.hasNext(); ){
String tmpKey = iter.next();
if(tmpKey.startsWith(socket.getInetAddress().getHostAddress()+ ":")){
sessionCount++;
}
}
if(sessionCount >= config.getServerMaxSessionsPerHost()){
log.debug("IP '" + sessionID + "' exceeds maximum connections --> drop");
try {
socket.close();
} catch (IOException e) {
//ignore
}
return;
} else {
log.debug("IP '" + sessionID + "' is not registered -> new Session");
newSession = new Session(socket);
sessions.put(sessionID, newSession);
}
}
// IP exists, but is closed -> close and create new Session
else if (oldSession.isFinished()) {
log.debug("IP '" + sessionID + "' exists, but is closed -> closing and new Session");
registerClosedSession(oldSession);
newSession = new Session(socket);
sessions.put(sessionID, newSession);
}
// IP exists, will be reused
else {
log.debug("IP '" + sessionID + "' exists -> reusing");
oldSession.bindSocket(socket);
newSession = oldSession;
}
// Start the new Session (as Thread)
newSession.startSession();
}
/**
* Closes the broken Session immediately. In difference to registerBrokenSession
* the IO of the Session will not be put in a Queue before closing, this happens here
* immediatly.
*/
public void closeBrokenSession(Session session) {
synchronized(brokenSessions) {
closeTerminalIO(session.getIO());
// remove it from the brokenSession-List, if available
brokenSessions.removeElement(session.getIO());
}
}
/** Placed an interrupted Connection in the broken Session List */
public void registerBrokenSession(TerminalIOInterface brokenIO) {
if (!brokenSessions.contains(brokenIO)) {
brokenSessions.addElement(brokenIO);
}
}
/** Placed a closed Session in the closed Session List, and removes it from the running Session List */
public void registerClosedSession(Session session) {
sessions.remove(session.getIO().getInetAdress() + ":" + session.getIO().getPort());
if (!closedSessions.contains(session)) {
closedSessions.addElement(session);
}
}
/** Shuts all Sessions down */
public void shutdown() {
// no automatic cleanup here anymore
cleanupActive = false;
// inform sessions (-> IO will be closed, as well as finish() in the SessionObject)
Enumeration enumSessions = sessions.elements();
while (enumSessions.hasMoreElements()) {
Session selectedSession = (Session)enumSessions.nextElement();
selectedSession.finish();
}
// finish global object
if (globalObject != null) {
globalObject.finish();
}
// execute cleanup last time
cleanup();
}
/** Returns the global object to which all Session have access. */
public GlobalObject getGlobalObject() {
return SessionManager.globalObject;
}
/** Sets the global object. */
public void setGlobalObject(GlobalObject globalObject) {
SessionManager.globalObject = globalObject;
}
// implementation of the interface Runnable
/** Cleans broken, closed as well as timed out Connections. */
public void run() {
while (cleanupActive) {
try {
cleanup();
try {
Thread.sleep(config.getServerCleanupInterval());
}
catch (InterruptedException ex) {
log.error(ex);
}
}
catch (Exception ex) {
log.error(ex);
}
}
}
}
|
package com.beust.jcommander;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class CmdTest {
@Parameters(commandNames = "--cmd-one")
public static class CmdOne {
}
@Parameters(commandNames = "--cmd-two")
class CmdTwo {
@Parameter
List<String> params = new java.util.LinkedList<String>();
}
public String parseArgs(boolean withDefault, String[] args) {
JCommander jc = new JCommander();
jc.addCommand(new CmdOne());
jc.addCommand(new CmdTwo());
if (withDefault) {
// First check if a command was given, when not prepend default
// command (--cmd-two")
// In version up to 1.23 JCommander throws an Exception in this
// line,
// which might be incorrect, at least its not reasonable if the
// method
// is named "WithoutValidation".
jc.parseWithoutValidation(args);
if (jc.getParsedCommand() == null) {
LinkedList<String> newArgs = new LinkedList<String>();
newArgs.add("--cmd-two");
newArgs.addAll(Arrays.asList(args));
jc.parse(newArgs.toArray(new String[0]));
}
} else {
jc.parse(args);
}
return jc.getParsedCommand();
}
@DataProvider
public Object[][] testData() {
return new Object[][] {
new Object[] { "--cmd-one", false, new String[] { "--cmd-one" } },
new Object[] { "--cmd-two", false, new String[] { "--cmd-two" } },
new Object[] { "--cmd-two", false,
new String[] { "--cmd-two", "param1", "param2" } },
// This is the relevant test case to test default commands
new Object[] { "--cmd-two", true,
new String[] { "param1", "param2" } } };
}
@Test(dataProvider = "testData")
public void testArgsWithoutDefaultCmd(String expected,
boolean requireDefault, String[] args) {
if (!requireDefault) {
Assert.assertEquals(parseArgs(false, args), expected);
}
}
@Test(dataProvider = "testData", expectedExceptions = MissingCommandException.class)
public void testArgsWithoutDefaultCmdFail(String expected,
boolean requireDefault, String[] args) {
if (requireDefault) {
try {
parseArgs(false, args);
} catch (MissingCommandException e) {
Assert.assertEquals(e.getUnknownCommand(), args[0]);
throw e;
}
} else {
throw new MissingCommandException("irrelevant test case");
}
}
// We do not expect a MissingCommandException!
@Test(dataProvider = "testData")
public void testArgsWithDefaultCmd(String expected, boolean requireDefault,
String[] args) {
Assert.assertEquals(parseArgs(true, args), expected);
}
}
|
package com.fivetran.javac;
import com.sun.source.tree.ClassTree;
import org.junit.Test;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class Recompile extends Fixtures {
@Test
public void compileTwice() {
DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>();
GetResourceFileObject file = new GetResourceFileObject("/CompileTwice.java");
JavacHolder compiler = new JavacHolder(Collections.emptyList(),
Collections.singletonList("src/test/resources"),
"out");
List<String> visits = new ArrayList<>();
compiler.afterAnalyze(new BridgeExpressionScanner() {
@Override
protected void visitClass(ClassTree node) {
super.visitClass(node);
visits.add(node.getSimpleName().toString());
}
});
compiler.onError(errors);
compiler.compile(compiler.parse(file));
assertThat(errors.getDiagnostics(), empty());
assertThat(visits, contains("CompileTwice"));
// Compile again
compiler.onError(errors);
compiler.compile(compiler.parse(file));
assertThat(errors.getDiagnostics(), empty());
assertThat(visits, contains("CompileTwice", "CompileTwice"));
}
@Test
public void fixParseError() {
Path path = Paths.get("FixParseError.java");
StringFileObject bad = new StringFileObject("public class FixParseError { public String foo() { return \"foo\"; }", path);
StringFileObject good = new StringFileObject("public class FixParseError { public String foo() { return \"foo\"; } }", path);
JavacHolder compiler = new JavacHolder(Collections.emptyList(),
Collections.singletonList("src/test/resources"),
"out");
DiagnosticCollector<JavaFileObject> badErrors = new DiagnosticCollector<>();
compiler.onError(badErrors);
compiler.parse(bad);
DiagnosticCollector<JavaFileObject> goodErrors = new DiagnosticCollector<>();
assertThat(badErrors.getDiagnostics(), not(empty()));
// Parse again
List<String> parsedClassNames = new ArrayList<>();
compiler.afterParse(new BridgeExpressionScanner() {
@Override
protected void visitClass(ClassTree node) {
super.visitClass(node);
parsedClassNames.add(node.getSimpleName().toString());
}
});
compiler.onError(goodErrors);
compiler.parse(good);
assertThat(goodErrors.getDiagnostics(), empty());
assertThat(parsedClassNames, contains("FixParseError"));
}
@Test
public void fixTypeError() {
Path path = Paths.get("FixTypeError.java");
StringFileObject bad = new StringFileObject("public class FixTypeError { public String foo() { return 1; } }", path);
StringFileObject good = new StringFileObject("public class FixTypeError { public String foo() { return \"foo\"; } }", path);
JavacHolder compiler = new JavacHolder(Collections.emptyList(),
Collections.singletonList("src/test/resources"),
"out");
DiagnosticCollector<JavaFileObject> badErrors = new DiagnosticCollector<>();
compiler.onError(badErrors);
compiler.compile(compiler.parse(bad));
DiagnosticCollector<JavaFileObject> goodErrors = new DiagnosticCollector<>();
assertThat(badErrors.getDiagnostics(), not(empty()));
// Parse again
List<String> parsedClassNames = new ArrayList<>();
compiler.afterAnalyze(new BridgeExpressionScanner() {
@Override
protected void visitClass(ClassTree node) {
super.visitClass(node);
parsedClassNames.add(node.getSimpleName().toString());
}
});
compiler.onError(goodErrors);
compiler.compile(compiler.parse(good));
assertThat(goodErrors.getDiagnostics(), empty());
assertThat(parsedClassNames, contains("FixTypeError"));
}
}
|
package de.dhbw.humbuch.util;
import static org.junit.Assert.assertEquals;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import org.junit.Test;
import au.com.bytecode.opencsv.CSVReader;
import de.dhbw.humbuch.model.GradeHandler;
import de.dhbw.humbuch.model.entity.Parent;
public class CSVTest {
@Test
public void testCreateStudentObjectsFromCSV(){
CSVReader csvReader;
try {
csvReader = new CSVReader(new FileReader("./src/test/java/de/dhbw/humbuch/util/schueler_stamm.csv"), ';', '\'', 0);
ArrayList<de.dhbw.humbuch.model.entity.Student> list = CSVHandler.createStudentObjectsFromCSV(csvReader);
assertEquals(99, list.size());
assertEquals("Zivko", list.get(1).getLastname());
assertEquals("5a", GradeHandler.getFullGrade(list.get(1).getGrade()));
assertEquals("Adelina", list.get(1).getFirstname());
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
assertEquals("02.01.1989", dateFormat.format(list.get(1).getBirthday()));
assertEquals("m", list.get(1).getGender());
//assertEquals("E", ProfileHandler.getLanguageProfile(list.get(1).getProfile()));
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package de.tum.in.cindy3dplugin.jogl;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.math.geometry.Vector3D;
import org.apache.commons.math.linear.RealMatrix;
import com.jogamp.opengl.util.glsl.ShaderCode;
public class Util {
public static float[] matrixToFloatArray(RealMatrix m) {
int rows = m.getRowDimension();
int cols = m.getColumnDimension();
float[] result = new float[rows*cols];
double[][] data = m.getData();
int offset = 0;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col, ++offset) {
result[offset] = (float) data[row][col];
}
}
return result;
}
public static float[] matrixToFloatArrayTransposed(RealMatrix m) {
int rows = m.getRowDimension();
int cols = m.getColumnDimension();
float[] result = new float[rows*cols];
double[][] data = m.getData();
int offset = 0;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col, ++offset) {
result[offset] = (float) data[col][row];
}
}
return result;
}
public static double[] vectorToDoubleArray(Vector3D v) {
return new double[] {v.getX(), v.getY(), v.getZ()};
}
public static void readShaderSource(ClassLoader context, URL url,
StringBuffer result) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("#pragma include ")) {
String includeFile = line.substring(16).trim();
// Try relative path first
URL nextURL = null;
try {
nextURL = new URL(url, includeFile);
} catch (MalformedURLException e) {
}
if (nextURL == null) {
// Try absolute path
try {
nextURL = new URL(includeFile);
} catch (MalformedURLException e) {
}
}
if (nextURL == null) {
// Fail
throw new FileNotFoundException(
"Can't find include file " + includeFile);
}
readShaderSource(context, nextURL, result);
} else {
result.append(line + "\n");
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static final String SHADER_PATH = "/de/tum/in/cindy3dplugin/resources/shader/";
public static ShaderCode loadShader(int type, String name) {
StringBuffer buffer = new StringBuffer();
URL url = Util.class.getResource(SHADER_PATH + name);
readShaderSource(Util.class.getClassLoader(), url, buffer);
ShaderCode shader = new ShaderCode(type, 1,
new String[][] { { buffer.toString() } });
return shader;
}
}
|
package org.biojava.bio.symbol;
import org.biojava.bio.BioException;
import org.biojava.utils.ParserException;
import org.biojava.bio.seq.io.SymbolTokenization;
/**
* This class creates PatternSearch.Pattern objects from
* String description of the object.
* @author David Huen
* @since 1.4
`*/
public class PatternMaker
{
private static class Range
{
private int min = 1;
private int max = 1;
private int getMin() { return min; }
private int getMax() { return max; }
private void setMin(int min) { this.min = min; }
private void setMax(int max) { this.max = max; }
}
private static class Tokenizer
{
private String packedTxt;
private int ptr = 0;
final static int EOL = -1;
final static int SYMBOL_TOKEN = 0;
final static int NUMERIC = 1;
final static int LEFT_BRACE = 2;
final static int RIGHT_BRACE = 3;
final static int COMMA = 4;
final static int LEFT_BRACKET = 5;
final static int RIGHT_BRACKET = 6;
final static int UNKNOWN = 999;
private Tokenizer(String target)
{
packedTxt = pack(target);
}
private char getToken()
throws IndexOutOfBoundsException
{
if (hasNext())
return packedTxt.charAt(ptr++);
else
throw new IndexOutOfBoundsException("text length: " + packedTxt.length() + " index: " + ptr);
}
private int nextTokenType()
{
if (!hasNext()) return EOL;
char nextCh = packedTxt.charAt(ptr);
// symbol tokens assumed to be alphas.
if (Character.isLetter(nextCh))
return SYMBOL_TOKEN;
if (Character.isDigit(nextCh))
return NUMERIC;
// now check for specific chars
if (nextCh == '{')
return LEFT_BRACE;
if (nextCh == '}')
return RIGHT_BRACE;
if (nextCh == ',')
return COMMA;
if (nextCh == '(')
return LEFT_BRACKET;
if (nextCh == ')')
return RIGHT_BRACKET;
return UNKNOWN;
}
private boolean hasNext()
{
return ptr < packedTxt.length();
}
/**
* produces a version of the String with whitespace removed.
*/
private String pack(String source)
{
StringBuffer packedString = new StringBuffer();
for (int i=0; i < source.length(); i++) {
char currCh;
if (!Character.isWhitespace(currCh = source.charAt(i))) {
packedString.append(currCh);
}
}
return packedString.toString();
}
}
/**
* a collection of data required during parsing.
*/
private static class Context
{
private Tokenizer toke;
private PatternSearch.Pattern pattern;
private SymbolTokenization symToke;
private FiniteAlphabet alfa;
}
/**
* Convert String into a PatternSearch.Pattern object in the specified alphabet.
*/
public static PatternSearch.Pattern parsePattern(String patternTxt, FiniteAlphabet alfa)
throws BioException, IllegalSymbolException, IllegalAlphabetException, ParserException
{
Context ctxt = new Context();
ctxt.toke = new Tokenizer(patternTxt);
ctxt.pattern = new PatternSearch.Pattern(patternTxt, alfa);
ctxt.symToke = alfa.getTokenization("token");
ctxt.alfa = alfa;
// check for empty pattern
if (!ctxt.toke.hasNext()) return null;
while (ctxt.toke.hasNext()) {
int tokenType = ctxt.toke.nextTokenType();
switch (tokenType) {
case Tokenizer.SYMBOL_TOKEN:
Symbol sym = ctxt.symToke.parseToken(Character.toString(ctxt.toke.getToken()));
if (ctxt.toke.nextTokenType() == Tokenizer.LEFT_BRACE) {
Range range = getIterations(ctxt);
PatternSearch.Pattern thisP = new PatternSearch.Pattern(ctxt.symToke.tokenizeSymbol(sym), alfa);
thisP.addSymbol(sym);
thisP.setMin(range.getMin());
thisP.setMax(range.getMax());
ctxt.pattern.addPattern(thisP);
}
else {
ctxt.pattern.addSymbol(sym);
}
break;
case Tokenizer.LEFT_BRACKET:
PatternSearch.Pattern thisP = parsePattern(ctxt);
if (ctxt.toke.nextTokenType() == Tokenizer.LEFT_BRACE) {
Range range = getIterations(ctxt);
thisP.setMin(range.getMin());
thisP.setMax(range.getMax());
}
ctxt.pattern.addPattern(thisP);
break;
default:
throw new ParserException(ctxt.toke.getToken() + " is not valid at this point.");
}
}
return ctxt.pattern;
}
private static Range getIterations(Context ctxt)
throws ParserException
{
Range range = new Range();
// consume the left brace
ctxt.toke.getToken();
// there can either be one or two numbers
boolean onSecondArg = false;
StringBuffer numString = new StringBuffer();
while (ctxt.toke.hasNext()) {
int tokenType = ctxt.toke.nextTokenType();
switch (tokenType) {
case Tokenizer.NUMERIC:
//System.out.println("adding symbol");
numString.append(ctxt.toke.getToken());
break;
case Tokenizer.COMMA:
ctxt.toke.getToken();
if (!onSecondArg) {
//System.out.println("numString is " + numString);
range.setMin(Integer.parseInt(numString.toString()));
numString = new StringBuffer();
onSecondArg = true;
}
else {
throw new ParserException("only two arguments permitted.");
}
break;
case Tokenizer.RIGHT_BRACE:
ctxt.toke.getToken();
if (onSecondArg) {
range.setMax(Integer.parseInt(numString.toString()));
}
else {
range.setMin(Integer.parseInt(numString.toString()));
range.setMax(range.getMin());
}
return range;
default:
throw new ParserException(ctxt.toke.getToken() + " is not valid at this point.");
}
}
throw new ParserException("unexpected error.");
}
private static PatternSearch.Pattern parsePattern(Context ctxt)
throws IllegalSymbolException, IllegalAlphabetException, ParserException
{
// consume left bracket
ctxt.toke.getToken();
PatternSearch.Pattern pattern = new PatternSearch.Pattern("", ctxt.alfa);
boolean hasContent = false;
while (ctxt.toke.hasNext()) {
int tokenType = ctxt.toke.nextTokenType();
switch (tokenType) {
case Tokenizer.SYMBOL_TOKEN:
Symbol sym = ctxt.symToke.parseToken(Character.toString(ctxt.toke.getToken()));
hasContent = true;
if (ctxt.toke.nextTokenType() == Tokenizer.LEFT_BRACE) {
Range range = getIterations(ctxt);
PatternSearch.Pattern thisP = new PatternSearch.Pattern("", ctxt.alfa);
thisP.addSymbol(sym);
thisP.setMin(range.getMin());
thisP.setMax(range.getMax());
pattern.addPattern(thisP);
}
else {
pattern.addSymbol(sym);
}
break;
case Tokenizer.LEFT_BRACKET:
PatternSearch.Pattern thisP = parsePattern(ctxt);
hasContent = true;
if (ctxt.toke.nextTokenType() == Tokenizer.LEFT_BRACE) {
Range range = getIterations(ctxt);
thisP.setMin(range.getMin());
thisP.setMax(range.getMax());
}
pattern.addPattern(thisP);
break;
case Tokenizer.RIGHT_BRACKET:
ctxt.toke.getToken();
if (hasContent)
return pattern;
else
throw new ParserException("empty pattern!");
default:
throw new ParserException(ctxt.toke.getToken() + " is not valid at this point.");
}
}
throw new ParserException("unexpected error.");
}
}
|
package ca.corefacility.bioinformatics.irida.service.analysis.workspace.galaxy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowParameterException;
import ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow;
import ca.corefacility.bioinformatics.irida.model.workflow.description.IridaToolParameter;
import ca.corefacility.bioinformatics.irida.model.workflow.description.IridaWorkflowParameter;
import ca.corefacility.bioinformatics.irida.model.workflow.execution.galaxy.WorkflowInputsGalaxy;
import ca.corefacility.bioinformatics.irida.service.analysis.workspace.AnalysisParameterService;
import com.github.jmchilton.blend4j.galaxy.beans.ToolParameter;
import com.github.jmchilton.blend4j.galaxy.beans.WorkflowInputs;
import com.google.common.collect.Sets;
/**
* A Galaxy implementation for preparing parameters for an analysis.
*
* @author Aaron Petkau <aaron.petkau@phac-aspc.gc.ca>
*
*/
@Service
public class AnalysisParameterServiceGalaxy implements AnalysisParameterService<WorkflowInputsGalaxy> {
private static final Logger logger = LoggerFactory.getLogger(AnalysisParameterServiceGalaxy.class);
/**
* {@inheritDoc}
*/
@Override
public WorkflowInputsGalaxy prepareAnalysisParameters(Map<String, String> parameters, IridaWorkflow iridaWorkflow)
throws IridaWorkflowParameterException {
checkNotNull(parameters, "parameters is null");
checkNotNull(iridaWorkflow, "iridaWorkflow is null");
WorkflowInputs inputs = new WorkflowInputs();
Set<String> parameterNamesUsed = Sets.newHashSet();
List<IridaWorkflowParameter> iridaParameters = iridaWorkflow.getWorkflowDescription().getParameters();
for (IridaWorkflowParameter iridaParameter : iridaParameters) {
String parameterName = iridaParameter.getName();
String value = parameters.get(parameterName);
parameterNamesUsed.add(parameterName);
if (value == null) {
if (iridaParameter.hasDefaultValue()) {
value = iridaParameter.getDefaultValue();
logger.debug("Parameter with name=" + parameterName + ", for workflow=" + iridaWorkflow
+ ", has no value set, using defaultValue=" + value);
} else {
logger.warn("Parameter with name=" + parameterName + ", for workflow=" + iridaWorkflow
+ ", has no value set and no default value defined, skipping.");
continue;
}
}
for (IridaToolParameter iridaToolParameter : iridaParameter.getToolParameters()) {
String toolId = iridaToolParameter.getToolId();
String galaxyParameterName = iridaToolParameter.getParameterName();
logger.debug("Setting parameter iridaName=" + parameterName + ", galaxyToolId=" + toolId + ", value="
+ value);
inputs.setToolParameter(toolId, new ToolParameter(galaxyParameterName, value));
}
}
Set<String> parameterNamesUnused = Sets.difference(parameters.keySet(), parameterNamesUsed);
if (!parameterNamesUnused.isEmpty()) {
throw new IridaWorkflowParameterException("The set of parameters " + parameterNamesUnused + " are not defined in " + iridaWorkflow);
} else {
return new WorkflowInputsGalaxy(inputs);
}
}
}
|
package org.dvare.dynamic;
import org.dvare.dynamic.compiler.DynamicCompiler;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class SourceTest {
private static final Logger log = LoggerFactory.getLogger(SourceTest.class);
@Test
public void compile_test() throws Exception {
DynamicCompiler dynamicCompiler = new DynamicCompiler();
String sourceCode = "package org.dvare.dynamic;" +
"public class SourceClass {" +
" public String test() { return \"inside test method\"; }" +
"}";
dynamicCompiler.addSource("org.dvare.dynamic.SourceClass", sourceCode);
Map<String, Class<?>> compiled = dynamicCompiler.build();
Class<?> aClass = compiled.get("org.dvare.dynamic.SourceClass");
Assert.assertNotNull(aClass);
Assert.assertEquals(1, aClass.getDeclaredMethods().length);
}
@Test
public void localDate_test() throws Exception {
String sourceCode = "package org.dvare.dynamic;" +
"import java.time.LocalDate;" +
"public class DateUtil {" +
" public static String getTestDate() { return LocalDate.of(2020,5,15).toString(); }" +
"}";
DynamicCompiler dynamicCompiler = new DynamicCompiler();
try {
Class.forName("com.sun.tools.sjavac.Module"); //if java module present
dynamicCompiler.addOption("--add-exports", "java.base/java.time=ALL-UNNAMED");
} catch (Exception ignored) {
}
dynamicCompiler.addSource("org.dvare.dynamic.DateUtil", sourceCode);
Map<String, Class<?>> compiled = dynamicCompiler.build();
Class<?> dateUtilClass = compiled.get("org.dvare.dynamic.DateUtil");
Assert.assertNotNull(dateUtilClass);
Assert.assertEquals(1, dateUtilClass.getDeclaredMethods().length);
Object dateUtil = dateUtilClass.newInstance();
Object result = dateUtilClass.getMethod("getTestDate").invoke(dateUtil);
Assert.assertEquals("2020-05-15", result);
}
@Test
public void compile_multiple_sources() throws Exception {
DynamicCompiler compiler = new DynamicCompiler();
String source1 = "public class SourceClass1 { public SourceClass2 getSourceClass2() { return new SourceClass2(); }}";
compiler.addSource("SourceClass1", source1);
String source2 = "public class SourceClass2 { public String toString() { return \"SourceClass2\"; }}";
compiler.addSource("SourceClass2", source2);
Map<String, Class<?>> compiled = compiler.build();
Assert.assertNotNull(compiled.get("SourceClass1"));
Assert.assertNotNull(compiled.get("SourceClass2"));
Class<?> aClass = compiled.get("SourceClass1");
Object instance = aClass.newInstance();
Object result = aClass.getMethod("getSourceClass2").invoke(instance);
Assert.assertEquals("SourceClass2", result.toString());
}
@Test
public void compile_innerCLass() throws Exception {
DynamicCompiler dynamicCompiler = new DynamicCompiler();
String sourceCode = "package org.dvare.dynamic;" +
"public class SourceClass {" +
" private static class InnerSourceClass { int inner; }" +
" public String hello() { return \"hello\"; }" +
"}";
dynamicCompiler.addSource("org.dvare.dynamic.SourceClass", sourceCode);
dynamicCompiler.build();
Class<?> aClass = Class.forName("org.dvare.dynamic.SourceClass",
false, dynamicCompiler.getClassLoader());
Assert.assertNotNull(aClass);
Assert.assertEquals(1, aClass.getDeclaredMethods().length);
Class<?> innerClass = Class.forName("org.dvare.dynamic.SourceClass$InnerSourceClass",
false, dynamicCompiler.getClassLoader());
Assert.assertNotNull(innerClass);
}
}
|
package org.broad.igv.data;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.exceptions.ParserException;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.track.TrackType;
import org.broad.igv.track.WindowFunction;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.ParsingUtils;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.collections.FloatArrayList;
import org.broad.igv.util.collections.IntArrayList;
import org.broad.igv.util.stream.IGVSeekableStreamFactory;
import org.broad.tribble.readers.AsciiLineReader;
import org.broad.tribble.util.SeekableStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class description
*
* @author Enter your name here...
* @version Enter version here..., 08/11/11
*/
public class IGVDatasetParser {
private static Logger log = Logger.getLogger(IGVDatasetParser.class);
private ResourceLocator dataResourceLocator;
private int chrColumn = -1;
private int startColumn = -1;
private int endColumn = -1;
private int firstDataColumn = -1;
private int lastDataColumn = -1;
private int probeColumn = -1;
private boolean hasEndLocations = false;
private boolean hasCalls = false;
private Genome genome;
private IGV igv;
private int startBase = 0;
public IGVDatasetParser(ResourceLocator copyNoFile, Genome genome) {
this.dataResourceLocator = copyNoFile;
this.genome = genome;
this.igv = IGV.hasInstance() ? IGV.getInstance() : null;
}
private void setColumnDefaults() {
String tmp = (dataResourceLocator.getPath().endsWith(".txt")
? dataResourceLocator.getPath().substring(0,
dataResourceLocator.getPath().length() - 4) : dataResourceLocator.getPath()).toLowerCase();
if (tmp.endsWith(".igv")) {
chrColumn = 0;
startColumn = 1;
endColumn = 2;
probeColumn = 3;
firstDataColumn = 4;
hasEndLocations = true;
hasCalls = false;
} else if (tmp.endsWith(".xcn") || tmp.endsWith("cn") || tmp.endsWith(".snp") || tmp.endsWith(".loh")) {
probeColumn = 0;
chrColumn = 1;
startColumn = 2;
endColumn = -1;
firstDataColumn = 3;
hasEndLocations = false;
hasCalls = tmp.endsWith(".xcn") || tmp.endsWith(".snp");
} else if (tmp.endsWith(".expr")) {
//gene_id bundle_id chr left right FPKM FPKM_conf_lo FPKM_conf_hi
probeColumn = 0;
chrColumn = 2;
startColumn = 3;
endColumn = 4;
startBase = 1;
firstDataColumn = 5;
lastDataColumn = 5;
hasEndLocations = true;
} else {
// TODO -- popup dialog and ask user to define columns, and csv vs tsv?
throw new ParserException("Unknown file type: ", 0);
}
}
public static boolean parsableMAGE_TAB(ResourceLocator file) throws IOException {
AsciiLineReader reader = null;
try {
reader = ParsingUtils.openAsciiReader(file);
String nextLine = null;
//skip first row
reader.readLine();
//check second row for MAGE_TAB identifiers
if ((nextLine = reader.readLine()) != null && (nextLine.contains("Reporter REF") || nextLine.contains("Composite Element REF") || nextLine.contains("Term Source REF") || nextLine.contains("CompositeElement REF") || nextLine.contains("TermSource REF") || nextLine.contains("Coordinates REF"))) {
int count = 0;
// check if this mage_tab data matrix can be parsed by this class
while ((nextLine = reader.readLine()) != null && count < 5) {
nextLine = nextLine.trim();
if (nextLine.startsWith("SNP_A") || nextLine.startsWith("CN_")) {
return true;
}
count++;
}
return false;
}
} finally {
if (reader != null) {
reader.close();
}
}
return false;
}
/**
* Scan the datafile for chromosome breaks.
*
* @param dataset
* @return
*/
public List<ChromosomeSummary> scan(IGVDataset dataset) {
int estLineCount = ParsingUtils.estimateLineCount(dataResourceLocator.getPath());
Map<String, Integer> longestFeatureMap = new HashMap();
float dataMin = 0;
float dataMax = 0;
InputStream is = null;
AsciiLineReader reader = null;
String nextLine = null;
ChromosomeSummary chrSummary = null;
List<ChromosomeSummary> chrSummaries = new ArrayList();
String[] headings = null;
WholeGenomeData wgData = null;
int nRows = 0;
int headerRows = 0;
int count = 0;
boolean logNormalized;
try {
int skipColumns = hasCalls ? 2 : 1;
// BufferedReader reader = ParsingUtils.openBufferedReader(dataResourceLocator);
is = ParsingUtils.openInputStreamGZ(dataResourceLocator);
reader = new AsciiLineReader(is);
// Infer datatype from extension. This can be overriden in the
// comment section
if (isCopyNumberFileExt(dataResourceLocator.getPath())) {
dataset.setTrackType(TrackType.COPY_NUMBER);
dataset.getTrackProperties().setWindowingFunction(WindowFunction.mean);
} else if (isLOHFileExt(dataResourceLocator.getPath())) {
dataset.setTrackType(TrackType.LOH);
dataset.getTrackProperties().setWindowingFunction(WindowFunction.mean);
} else {
dataset.getTrackProperties().setWindowingFunction(WindowFunction.mean);
}
// Parse comments and directives, if any
nextLine = reader.readLine();
while (nextLine.startsWith("#") || (nextLine.trim().length() == 0)) {
headerRows++;
if (nextLine.length() > 0) {
parseDirective(nextLine, dataset);
}
nextLine = reader.readLine();
}
if (chrColumn < 0) {
setColumnDefaults();
}
// Parse column headings
String[] data = nextLine.trim().split("\t");
// Set last data column
if (lastDataColumn < 0) {
lastDataColumn = data.length - 1;
}
headings = getHeadings(data, skipColumns);
dataset.setDataHeadings(headings);
// Infer if the data is logNormalized by looking for negative data values.
// Assume it is not until proven otherwise
logNormalized = false;
wgData = new WholeGenomeData(headings);
int chrRowCount = 0;
// Update
int updateCount = 5000;
long lastPosition = 0;
while ((nextLine = reader.readLine()) != null) {
if (igv != null && ++count % updateCount == 0) {
igv.setStatusBarMessage("Loaded: " + count + " / " + estLineCount + " (est)");
}
// Distance since last sample
String[] tokens = Globals.tabPattern.split(nextLine, -1);
int nTokens = tokens.length;
if (nTokens > 0) {
String thisChr = genome.getChromosomeAlias(tokens[chrColumn]);
if (chrSummary == null || !thisChr.equals(chrSummary.getName())) {
// Update whole genome and previous chromosome summary, unless this is
// the first chromosome
if (chrSummary != null) {
updateWholeGenome(chrSummary.getName(), dataset, headings, wgData);
chrSummary.setNDataPoints(nRows);
}
// Shart the next chromosome
chrSummary = new ChromosomeSummary(thisChr, lastPosition);
chrSummaries.add(chrSummary);
nRows = 0;
wgData = new WholeGenomeData(headings);
chrRowCount = 0;
}
lastPosition = reader.getPosition();
int location = -1;
try {
location = ParsingUtils.parseInt(tokens[startColumn]) - startBase;
} catch (NumberFormatException numberFormatException) {
log.error("Column " + tokens[startColumn] + " is not a number");
throw new ParserException("Column " + (startColumn + 1) +
" must contain an integer value." + " Found: " + tokens[startColumn],
count + headerRows, nextLine);
}
int length = 1;
if (hasEndLocations) {
try {
length = ParsingUtils.parseInt(tokens[endColumn].trim()) - location + 1;
} catch (NumberFormatException numberFormatException) {
log.error("Column " + tokens[endColumn] + " is not a number");
throw new ParserException("Column " + (endColumn + 1) +
" must contain an integer value." + " Found: " + tokens[endColumn],
count + headerRows, nextLine);
}
}
updateLongestFeature(longestFeatureMap, thisChr, length);
if (wgData.locations.size() > 0 && wgData.locations.get(wgData.locations.size() - 1) > location) {
throw new ParserException("File is not sorted, .igv and .cn files must be sorted by start position." +
" Use igvtools (File > Run igvtools..) to sort the file.", count + headerRows);
}
wgData.locations.add(location);
for (int idx = 0; idx < headings.length; idx++) {
int i = firstDataColumn + idx * skipColumns;
float copyNo = i < tokens.length ? readFloat(tokens[i]) : Float.NaN;
if (!Float.isNaN(copyNo)) {
dataMin = Math.min(dataMin, copyNo);
dataMax = Math.max(dataMax, copyNo);
}
if (copyNo < 0) {
logNormalized = true;
}
String heading = headings[idx];
wgData.data.get(heading).add(copyNo);
}
nRows++;
}
chrRowCount++;
}
dataset.setLongestFeatureMap(longestFeatureMap);
} catch (ParserException pe) {
throw pe;
} catch (FileNotFoundException e) {
// DialogUtils.showError("SNP file not found: " + dataSource.getCopyNoFile());
log.error("File not found: " + dataResourceLocator);
throw new RuntimeException(e);
} catch (Exception e) {
log.error("Exception when loading: " + dataResourceLocator.getPath(), e);
if (nextLine != null && (count + headerRows != 0)) {
throw new ParserException(e.getMessage(), e, count + headerRows, nextLine);
} else {
throw new RuntimeException(e);
}
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error("Error closing IGVDataset stream", e);
}
}
}
// Update last chromosome
if (chrSummary != null) {
updateWholeGenome(chrSummary.getName(), dataset, headings, wgData);
chrSummary.setNDataPoints(nRows);
}
dataset.setLogNormalized(logNormalized);
dataset.setDataMin(dataMin);
dataset.setDataMax(dataMax);
return chrSummaries;
}
private void updateLongestFeature(Map<String, Integer> longestFeatureMap, String thisChr, int length) {
if (longestFeatureMap.containsKey(thisChr)) {
longestFeatureMap.put(thisChr, Math.max(longestFeatureMap.get(thisChr), length));
} else {
longestFeatureMap.put(thisChr, length);
}
}
private float readFloat(String token) {
float copyNo = Float.NaN;
try {
if (token != null) {
copyNo = Float.parseFloat(token);
}
} catch (NumberFormatException e) {
// This is an expected condition.
}
return copyNo;
}
/**
* Load data for a single chromosome.
*
* @param chrSummary
* @param dataHeaders
* @return
*/
public ChromosomeData loadChromosomeData(ChromosomeSummary chrSummary, String[] dataHeaders) {
// InputStream is = null;
try {
int skipColumns = hasCalls ? 2 : 1;
// Get an estimate of the number of snps (rows). THIS IS ONLY AN ESTIMATE
int nRowsEst = chrSummary.getNDataPts();
SeekableStream is = IGVSeekableStreamFactory.getStreamFor(dataResourceLocator.getPath());
is.seek(chrSummary.getStartPosition());
AsciiLineReader reader = new AsciiLineReader(is);
// Create containers to hold data
IntArrayList startLocations = new IntArrayList(nRowsEst);
IntArrayList endLocations = (hasEndLocations ? new IntArrayList(nRowsEst) : null);
List<String> probes = new ArrayList(nRowsEst);
Map<String, FloatArrayList> dataMap = new HashMap();
for (String h : dataHeaders) {
dataMap.put(h, new FloatArrayList(nRowsEst));
}
// Begin loop through rows
String chromosome = chrSummary.getName();
boolean chromosomeStarted = false;
String nextLine = reader.readLine();
while ((nextLine != null) && (nextLine.trim().length() > 0)) {
if (!nextLine.startsWith("
try {
String[] tokens = Globals.tabPattern.split(nextLine, -1);
String thisChromosome = genome.getChromosomeAlias(tokens[chrColumn].trim());
if (thisChromosome.equals(chromosome)) {
chromosomeStarted = true;
// chromosomeData.setMarkerId(nRows, tokens[0]);
// The probe. A new string is created to prevent holding on to the entire row through a substring reference
String probe = new String(tokens[probeColumn]);
probes.add(probe);
int start = ParsingUtils.parseInt(tokens[startColumn].trim()) - startBase;
if (hasEndLocations) {
endLocations.add(ParsingUtils.parseInt(tokens[endColumn].trim()));
}
startLocations.add(start);
if(tokens.length <= firstDataColumn + (dataHeaders.length - 1)*skipColumns){
String msg = "Line has too few data columns: " + nextLine;
log.error(msg);
throw new RuntimeException(msg);
}
for (int idx = 0; idx < dataHeaders.length; idx++) {
int i = firstDataColumn + idx * skipColumns;
float copyNo = i <= lastDataColumn ? readFloat(tokens[i]) : Float.NaN;
String heading = dataHeaders[idx];
dataMap.get(heading).add(copyNo);
}
} else if (chromosomeStarted) {
break;
}
} catch (NumberFormatException numberFormatException) {
// Skip line
log.info("Skipping line (NumberFormatException) " + nextLine);
}
}
nextLine = reader.readLine();
}
// Loop complete
ChromosomeData cd = new ChromosomeData(chrSummary.getName());
cd.setProbes(probes.toArray(new String[]{}));
cd.setStartLocations(startLocations.toArray());
if (hasEndLocations) {
cd.setEndLocations(endLocations.toArray());
}
for (String h : dataHeaders) {
cd.setData(h, dataMap.get(h).toArray());
}
return cd;
} catch (IOException ex) {
log.error("Error parsing cn file", ex);
throw new RuntimeException("Error parsing cn file", ex);
}
}
/**
* Note: This is an exact copy of the method in ExpressionFileParser. Refactor to merge these
* two parsers, or share a common base class.
*
* @param comment
* @param dataset
*/
private void parseDirective(String comment, IGVDataset dataset) {
String tmp = comment.substring(1, comment.length());
if (tmp.startsWith("track")) {
ParsingUtils.parseTrackLine(tmp, dataset.getTrackProperties());
} else if (tmp.startsWith("columns")) {
parseColumnLine(tmp);
} else {
String[] tokens = tmp.split("=");
if (tokens.length != 2) {
return;
}
String key = tokens[0].trim().toLowerCase();
if (key.equals("name")) {
dataset.setName(tokens[1].trim());
} else if (key.equals("type")) {
try {
dataset.setTrackType(TrackType.valueOf(tokens[1].trim().toUpperCase()));
} catch (Exception exception) {
// Ignore
}
} else if (key.equals("coords")) {
startBase = Integer.parseInt(tokens[1].trim());
}
}
}
private boolean isCopyNumberFileExt(String filename) {
String tmp = ((filename.endsWith(".txt") || filename.endsWith(".tab") || filename.endsWith(".xls")
? filename.substring(0, filename.length() - 4) : filename)).toLowerCase();
return tmp.endsWith(".cn") || tmp.endsWith(".xcn") || tmp.endsWith(".snp");
}
private boolean isLOHFileExt(String filename) {
String tmp = (filename.endsWith(".txt") || filename.endsWith(".tab") || filename.endsWith(".xls")
? filename.substring(0, filename.length() - 4) : filename);
return tmp.endsWith(".loh");
}
/**
* Return the sample headings for the copy number file.
*
* @param tokens
* @param skipColumns
* @return
*/
public String[] getHeadings(String[] tokens, int skipColumns) {
return getHeadings(tokens, skipColumns, false);
}
/**
* Return the sample headings for the copy number file.
*
* @param tokens
* @param skipColumns
* @param removeDuplicates , whether to remove any duplicate headings
* @return
*/
public String[] getHeadings(String[] tokens, int skipColumns, boolean removeDuplicates) {
ArrayList headings = new ArrayList();
String previousHeading = null;
for (int i = firstDataColumn; i <= lastDataColumn; i += skipColumns) {
if (removeDuplicates) {
if (previousHeading != null && tokens[i].equals(previousHeading) || tokens[i].equals("")) {
continue;
}
previousHeading = tokens[i];
}
headings.add(tokens[i].trim());
}
return (String[]) headings.toArray(new String[0]);
}
private void parseColumnLine(String tmp) {
String[] tokens = tmp.split("\\s+");
String neg_colnum = "Error parsing column line: " + tmp + "<br>Column numbers must be > 0";
if (tokens.length > 1) {
for (int i = 1; i < tokens.length; i++) {
String[] kv = tokens[i].split("=");
if (kv.length == 2) {
if (kv[0].toLowerCase().equals("chr")) {
int c = Integer.parseInt(kv[1]);
if (c < 1) {
MessageUtils.showMessage(neg_colnum);
} else {
chrColumn = c - 1;
}
} else if (kv[0].toLowerCase().equals("start")) {
int c = Integer.parseInt(kv[1]);
if (c < 1) {
MessageUtils.showMessage(neg_colnum);
} else {
startColumn = c - 1;
}
} else if (kv[0].toLowerCase().equals("end")) {
int c = Integer.parseInt(kv[1]);
if (c < 1) {
MessageUtils.showMessage(neg_colnum);
} else {
endColumn = c - 1;
hasEndLocations = true;
}
} else if (kv[0].toLowerCase().equals("probe")) {
int c = Integer.parseInt(kv[1]);
if (c < 1) {
MessageUtils.showMessage(neg_colnum);
} else {
probeColumn = c - 1;
}
} else if (kv[0].toLowerCase().equals("data")) {
// examples 4, 4-8, 4-
String[] se = kv[1].split("-");
int c = Integer.parseInt(se[0]);
if (c < 1) {
MessageUtils.showMessage(neg_colnum);
} else {
this.firstDataColumn = c - 1;
}
if (se.length > 1) {
c = Integer.parseInt(se[1]);
if (c < 1) {
MessageUtils.showMessage(neg_colnum);
} else {
this.lastDataColumn = c - 1;
}
}
}
}
}
}
}
private void updateWholeGenome(String currentChromosome, IGVDataset dataset, String[] headings,
IGVDatasetParser.WholeGenomeData wgData) {
if (!genome.getHomeChromosome().equals(Globals.CHR_ALL)) {
return;
}
// Update whole genome data
int[] locations = wgData.locations.toArray();
if (locations.length > 0) {
Map<String, float[]> tmp = new HashMap(wgData.data.size());
for (String s : wgData.headings) {
tmp.put(s, wgData.data.get(s).toArray());
}
GenomeSummaryData genomeSummary = dataset.getGenomeSummary();
if (genomeSummary == null) {
genomeSummary = new GenomeSummaryData(genome, headings);
dataset.setGenomeSummary(genomeSummary);
}
genomeSummary.addData(currentChromosome, locations, tmp);
}
}
class WholeGenomeData {
String[] headings;
IntArrayList locations = new IntArrayList(50000);
Map<String, FloatArrayList> data = new HashMap();
WholeGenomeData(String[] headings) {
this.headings = headings;
for (String h : headings) {
data.put(h, new FloatArrayList(50000));
}
}
int size() {
return locations.size();
}
}
}
|
package org.knowm.sundial;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.knowm.sundial.exceptions.JobInterruptException;
import org.quartz.exceptions.SchedulerException;
/** This doesn't really test much. But at least it allows us to inspect the job output on errors. */
public class BadJobTest {
public static class BadJob extends Job {
@Override
public void doRun() throws JobInterruptException {
throw new RuntimeException("I'm bad to the bone");
}
}
@BeforeClass
public void setup() {
SundialJobScheduler.startScheduler(1, null); // null -> don't load anything
List<String> names = SundialJobScheduler.getAllJobNames();
// We get the jobs from the XML for free
// assertTrue( names.isEmpty() );
}
@AfterClass
public static void shutdownScheduler() {
SundialJobScheduler.shutdown();
}
@Test
public void testJobsNeverFail() throws InterruptedException, SchedulerException {
BadJob bj = new BadJob();
SundialJobScheduler.addJob(BadJob.class.getSimpleName(), BadJob.class);
SundialJobScheduler.addSimpleTrigger("bj-trigger", BadJob.class.getSimpleName(), 0, 1);
List<String> names = SundialJobScheduler.getAllJobNames();
Thread.sleep(100);
}
}
|
package org.apache.derby.impl.sql.execute.operations;
import com.google.common.collect.Maps;
import com.splicemachine.derby.test.DerbyTestRule;
import com.splicemachine.utils.SpliceLogUtils;
import org.apache.log4j.Logger;
import org.junit.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Tests aggregations around multi-group entries
* @author Scott Fines
*
*/
public class MultiGroupGroupedAggregateOperationTest {
private static Logger LOG = Logger.getLogger(SingleGroupGroupedAggregateOperationTest.class);
static Map<String,String> tableSchemaMap = Maps.newHashMap();
static{
tableSchemaMap.put("multigrouptest","uname varchar(40),fruit varchar(40),bushels int");
}
@Rule public static DerbyTestRule rule = new DerbyTestRule(tableSchemaMap,false,LOG);
@BeforeClass
public static void setup() throws Exception{
DerbyTestRule.start();
rule.createTables();
insertData();
}
@AfterClass
public static void shutdown() throws Exception {
rule.dropTables();
DerbyTestRule.shutdown();
}
private static Map<Pair,Stats> pairStats = new HashMap<Pair,Stats>();
private static Map<String,Stats> unameStats = new HashMap<String,Stats>();
private static Map<String,Stats> fruitStats = new HashMap<String,Stats>();
private static Stats totalStats = new Stats();
private static final int size = 10;
public static void insertData() throws Exception{
PreparedStatement ps = rule.prepareStatement("insert into multigrouptest (uname, fruit,bushels) values (?,?,?)");
List<String> fruits = Arrays.asList("strawberries","bananas","cherries");
List<String> users = Arrays.asList("jzhang","sfines","jleach");
for(int i=0;i< size;i++){
List<Integer> values = Arrays.asList(i*5,i*10,i*15);
for(String user:users){
for(int pos=0;pos<fruits.size();pos++){
String fruit = fruits.get(pos);
int value = values.get(pos);
Pair pair = Pair.newPair(user,fruit);
if(!pairStats.containsKey(pair))
pairStats.put(pair,new Stats());
pairStats.get(pair).add(value);
if(!unameStats.containsKey(user))
unameStats.put(user,new Stats());
unameStats.get(user).add(value);
if(!fruitStats.containsKey(fruit))
fruitStats.put(fruit,new Stats());
fruitStats.get(fruit).add(value);
ps.setString(1, user);
ps.setString(2, fruit);
ps.setInt(3, value);
ps.executeUpdate();
totalStats.add(value);
}
}
}
rule.commit();
//make sure that we have multiple regions to split across
rule.splitTable("multigrouptest",size/3);
}
@Test
public void testGroupedByFirstCountOperation() throws Exception{
ResultSet rs = rule.executeQuery("select uname, count(bushels) from multigrouptest group by uname");
int rowCount =0;
while(rs.next()){
String uname = rs.getString(1);
int count = rs.getInt(2);
Assert.assertNotNull("no uname returned!",uname);
Assert.assertEquals("Incorrect count for uname "+ uname,unameStats.get(uname).getCount(),count);
rowCount++;
}
Assert.assertEquals("Not all groups found!",unameStats.size(),rowCount);
}
@Test
public void testGroupedByFirstShownBySecondCountOperation() throws Exception{
ResultSet rs = rule.executeQuery("select count(bushels) from multigrouptest group by uname");
int rowCount=0;
while(rs.next()){
int count = rs.getInt(1);
rowCount++;
}
Assert.assertEquals("Not all groups found!",unameStats.size(),rowCount);
}
@Test
public void testGroupedBySecondCountOperation() throws Exception{
ResultSet rs = rule.executeQuery("select fruit,count(bushels) from multigrouptest group by fruit");
int rowCount=0;
while(rs.next()){
String fruit = rs.getString(1);
int count = rs.getInt(2);
Assert.assertNotNull("no fruit returned!",fruit);
Assert.assertEquals("Incorrect count for fruit "+ fruit,fruitStats.get(fruit).getCount(),count);
rowCount++;
}
Assert.assertEquals("Not all groups found!",fruitStats.size(),rowCount);
}
@Test
public void testGroupedByFirstCountAllOperation() throws Exception {
ResultSet rs = rule.executeQuery("select uname, count(*) from multigrouptest group by uname");
int rowCount=0;
while(rs.next()){
String uname = rs.getString(1);
Assert.assertNotNull("No uname returned!",uname);
int count = rs.getInt(2);
Assert.assertEquals("Incorrect count for uname "+ uname,unameStats.get(uname).getCount(),count);
rowCount++;
}
Assert.assertEquals("Not all groups found",unameStats.size(),rowCount);
}
@Test
public void testGroupedBySecondCountAllOperation() throws Exception{
ResultSet rs = rule.executeQuery("select fruit,count(*) from multigrouptest group by fruit");
int rowCount=0;
while(rs.next()){
String fruit = rs.getString(1);
int count = rs.getInt(2);
Assert.assertNotNull("no fruit returned!",fruit);
Assert.assertEquals("Incorrect count for fruit "+ fruit,fruitStats.get(fruit).getCount(),count);
rowCount++;
}
Assert.assertEquals("Not all groups found!",fruitStats.size(),rowCount);
}
@Test
public void testGroupedByFirstSumOperation() throws Exception{
ResultSet rs = rule.executeQuery("select uname,sum(bushels) from multigrouptest group by uname");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
int sum = rs.getInt(2);
int correctSum = unameStats.get(uname).getSum();
SpliceLogUtils.trace(LOG, "uname=%s, sum=%d, correctSum=%d",uname,sum,correctSum);
Assert.assertEquals("Incorrect sum for uname "+ uname,correctSum,sum);
row++;
}
Assert.assertEquals("Not all groups found!", unameStats.size(),row);
}
@Test
@Ignore("Known broken but checking in for communication purposes")
public void testGroupedByRestrictedFirstSumOperation() throws Exception{
ResultSet rs = rule.executeQuery("select uname, sum(bushels) from multigrouptest group by uname having sum(bushels) < 5000");
int rowCount=0;
while(rs.next()){
String uname = rs.getString(1);
int sum = rs.getInt(2);
Assert.assertTrue("sum > 50!",sum<500);
rowCount++;
}
Assert.assertEquals("not all groups found!",unameStats.size(),rowCount);
}
@Test
public void testGroupedBySecondSumOperation() throws Exception{
ResultSet rs = rule.executeQuery("select fruit,sum(bushels) from multigrouptest group by fruit");
int row =0;
while(rs.next()){
String fruit = rs.getString(1);
int sum = rs.getInt(2);
int correctSum = fruitStats.get(fruit).getSum();
SpliceLogUtils.trace(LOG, "fruit=%s, sum=%d, correctSum=%d",fruit,sum,correctSum);
Assert.assertEquals("Incorrect sum for fruit "+ fruit,correctSum,sum);
row++;
}
Assert.assertEquals("Not all groups found!", fruitStats.size(),row);
}
@Test
public void testGroupedByTwoKeysSumOperation() throws Exception{
ResultSet rs = rule.executeQuery("select uname,fruit, sum(bushels) from multigrouptest group by uname,fruit");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
String fruit = rs.getString(2);
int sum = rs.getInt(3);
int correctSum = pairStats.get(Pair.newPair(uname, fruit)).getSum();
SpliceLogUtils.trace(LOG, "uname=%s,fruit=%s, sum=%d, correctSum=%d",uname,fruit,sum,correctSum);
Assert.assertEquals("Incorrect sum for uname"+ uname+", fruit "+fruit,correctSum,sum);
row++;
}
Assert.assertEquals("Not all groups found!", pairStats.size(),row);
}
@Test
public void testGroupedByFirstAvgOperation() throws Exception{
ResultSet rs =rule.executeQuery("select uname,avg(bushels) from multigrouptest group by uname");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
int avg = rs.getInt(2);
int correctAvg = unameStats.get(uname).getAvg();
SpliceLogUtils.trace(LOG, "uname=%s, avg=%d, correctAvg=%d",uname,avg,correctAvg);
Assert.assertEquals("Incorrect avg for uname "+ uname,correctAvg,avg);
row++;
}
Assert.assertEquals("Not all groups found!", unameStats.size(),row);
}
@Test
public void testGroupedBySecondAvgOperation() throws Exception{
ResultSet rs =rule.executeQuery("select fruit,avg(bushels) from multigrouptest group by fruit");
int row =0;
while(rs.next()){
String fruit = rs.getString(1);
int avg = rs.getInt(2);
int correctAvg = fruitStats.get(fruit).getAvg();
SpliceLogUtils.trace(LOG, "fruit=%s, avg=%d, correctAvg=%d",fruit,avg,correctAvg);
Assert.assertEquals("Incorrect avg for fruit "+ fruit,correctAvg,avg);
row++;
}
Assert.assertEquals("Not all groups found!", fruitStats.size(),row);
}
@Test
public void testGroupedByTwoKeysAvgOperation() throws Exception{
ResultSet rs =rule.executeQuery("select uname,fruit, avg(bushels) from multigrouptest group by uname,fruit");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
String fruit = rs.getString(2);
Pair pair = Pair.newPair(uname,fruit);
int avg = rs.getInt(3);
int correctAvg = pairStats.get(pair).getAvg();
SpliceLogUtils.trace(LOG, "pair=%s, avg=%d, correctAvg=%d",pair,avg,correctAvg);
Assert.assertEquals("Incorrect avg for pair "+pair,correctAvg,avg);
row++;
}
Assert.assertEquals("Not all groups found!", pairStats.size(),row);
}
@Test
public void testGroupedByFirstMaxOperation() throws Exception{
ResultSet rs =rule.executeQuery("select uname,max(bushels) from multigrouptest group by uname");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
int max = rs.getInt(2);
int correctMax = unameStats.get(uname).getMax();
SpliceLogUtils.trace(LOG, "uname=%s, max=%d, correctMax=%d",uname,max,correctMax);
Assert.assertEquals("Incorrect max for uname "+ uname,correctMax,max);
row++;
}
Assert.assertEquals("Not all groups found!", unameStats.size(),row);
}
@Test
public void testGroupedBySecondMaxOperation() throws Exception{
ResultSet rs =rule.executeQuery("select fruit,max(bushels) from multigrouptest group by fruit");
int row =0;
while(rs.next()){
String fruit = rs.getString(1);
int max = rs.getInt(2);
int correctMax = fruitStats.get(fruit).getMax();
SpliceLogUtils.trace(LOG, "fruit=%s, max=%d, correctMax=%d",fruit,max,correctMax);
Assert.assertEquals("Incorrect max for fruit "+ fruit,correctMax,max);
row++;
}
Assert.assertEquals("Not all groups found!", fruitStats.size(),row);
}
@Test
public void testGroupedByTwoKeysMaxOperation() throws Exception{
ResultSet rs =rule.executeQuery("select uname,fruit, max(bushels) from multigrouptest group by uname,fruit");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
String fruit = rs.getString(2);
int max = rs.getInt(3);
int correctMax = pairStats.get(Pair.newPair(uname, fruit)).getMax();
SpliceLogUtils.trace(LOG, "uname=%s,fruit=%s, max=%d, correctMax=%d",uname,fruit,max,correctMax);
Assert.assertEquals("Incorrect max for uname"+ uname+", fruit "+fruit,correctMax,max);
row++;
}
Assert.assertEquals("Not all groups found!", pairStats.size(),row);
}
@Test
public void testGroupedByFirstMinOperation() throws Exception{
ResultSet rs =rule.executeQuery("select uname,min(bushels) from multigrouptest group by uname");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
int min = rs.getInt(2);
int correctMin = unameStats.get(uname).getMin();
SpliceLogUtils.trace(LOG, "uname=%s, min=%d, correctMin=%d",uname,min,correctMin);
Assert.assertEquals("Incorrect min for uname "+ uname,correctMin,min);
row++;
}
Assert.assertEquals("Not all groups found!", unameStats.size(),row);
}
@Test
public void testGroupedBySecondMinOperation() throws Exception{
ResultSet rs =rule.executeQuery("select fruit,min(bushels) from multigrouptest group by fruit");
int row =0;
while(rs.next()){
String fruit = rs.getString(1);
int min = rs.getInt(2);
int correctMin = fruitStats.get(fruit).getMin();
SpliceLogUtils.trace(LOG, "fruit=%s, min=%d, correctMin=%d",fruit,min,correctMin);
Assert.assertEquals("Incorrect min for fruit "+ fruit,correctMin,min);
row++;
}
Assert.assertEquals("Not all groups found!", fruitStats.size(),row);
}
@Test
public void testGroupedByTwoKeysMinOperation() throws Exception{
ResultSet rs =rule.executeQuery("select uname,fruit, min(bushels) from multigrouptest group by uname,fruit");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
String fruit = rs.getString(2);
int min = rs.getInt(3);
int correctMin = pairStats.get(Pair.newPair(uname, fruit)).getMin();
SpliceLogUtils.trace(LOG, "uname=%s,fruit=%s, min=%d, correctMin=%d",uname,fruit,min,correctMin);
Assert.assertEquals("Incorrect min for uname"+ uname+", fruit "+fruit,correctMin,min);
row++;
}
Assert.assertEquals("Not all groups found!", pairStats.size(),row);
}
@Test
public void testGroupedByFirstAllOperations() throws Exception{
ResultSet rs =rule.executeQuery("select uname,sum(bushels),avg(bushels),min(bushels),max(bushels) from multigrouptest group by uname");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
int sum = rs.getInt(2);
int avg = rs.getInt(3);
int min = rs.getInt(4);
int max = rs.getInt(5);
Stats cStats= unameStats.get(uname);
int cMin = cStats.getMin();
int cMax = cStats.getMax();
int cSum = cStats.getSum();
int cAvg = cStats.getAvg();
SpliceLogUtils.trace(LOG, "uname=%s, sum=%d,avg=%d,min=%d,max=%d, cSum=%d,cAvg=%d,cMin=%d,cMax=%d",uname,sum,avg,min,max,cSum,cAvg,cMin,cMax);
Assert.assertEquals("Incorrect min for uname "+ uname,cMin,min);
Assert.assertEquals("Incorrect max for uname "+ uname,cMax,max);
Assert.assertEquals("Incorrect avg for uname "+ uname,cAvg,avg);
Assert.assertEquals("Incorrect sum for uname "+ uname,cSum,sum);
row++;
}
Assert.assertEquals("Not all groups found!", unameStats.size(),row);
}
@Test
public void testGroupedBySecondAllOperations() throws Exception{
ResultSet rs =rule.executeQuery("select fruit,sum(bushels),avg(bushels),min(bushels),max(bushels) from multigrouptest group by fruit");
int row =0;
while(rs.next()){
String fruit = rs.getString(1);
int sum = rs.getInt(2);
int avg = rs.getInt(3);
int min = rs.getInt(4);
int max = rs.getInt(5);
Stats cStats= fruitStats.get(fruit);
int cMin = cStats.getMin();
int cMax = cStats.getMax();
int cSum = cStats.getSum();
int cAvg = cStats.getAvg();
SpliceLogUtils.trace(LOG, "fruit=%s, sum=%d,avg=%d,min=%d,max=%d, cSum=%d,cAvg=%d,cMin=%d,cMax=%d",fruit,sum,avg,min,max,cSum,cAvg,cMin,cMax);
Assert.assertEquals("Incorrect min for fruit "+ fruit,cMin,min);
Assert.assertEquals("Incorrect max for fruit "+ fruit,cMax,max);
Assert.assertEquals("Incorrect avg for fruit "+ fruit,cAvg,avg);
Assert.assertEquals("Incorrect sum for fruit "+ fruit,cSum,sum);
row++;
}
Assert.assertEquals("Not all groups found!", fruitStats.size(),row);
}
@Test
public void testGroupedByTwoKeysAllOperations() throws Exception{
ResultSet rs =rule.executeQuery("select uname,fruit,sum(bushels),avg(bushels),min(bushels),max(bushels) from multigrouptest group by uname,fruit");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
String fruit = rs.getString(2);
Pair pair = Pair.newPair(uname, fruit);
int sum = rs.getInt(3);
int avg = rs.getInt(4);
int min = rs.getInt(5);
int max = rs.getInt(6);
Stats cStats= pairStats.get(pair);
int cMin = cStats.getMin();
int cMax = cStats.getMax();
int cSum = cStats.getSum();
int cAvg = cStats.getAvg();
SpliceLogUtils.trace(LOG, "pair=%s, sum=%d,avg=%d,min=%d,max=%d, cSum=%d,cAvg=%d,cMin=%d,cMax=%d",pair,sum,avg,min,max,cSum,cAvg,cMin,cMax);
Assert.assertEquals("Incorrect min for pair "+ pair,cMin,min);
Assert.assertEquals("Incorrect max for pair "+ pair,cMax,max);
Assert.assertEquals("Incorrect avg for pair "+ pair,cAvg,avg);
Assert.assertEquals("Incorrect sum for pair "+ pair,cSum,sum);
row++;
}
Assert.assertEquals("Not all groups found!", pairStats.size(),row);
}
@Test
@Ignore
public void testRollupAllOperations() throws Exception{
ResultSet rs = rule.executeQuery("select uname, fruit,sum(bushels),avg(bushels),min(bushels),max(bushels) " +
"from multigrouptest group by rollup(uname,fruit)");
int row =0;
while(rs.next()){
String uname = rs.getString(1);
String fruit = rs.getString(2);
Pair pair = Pair.newPair(uname, fruit);
Stats cStats = null;
if(uname==null){
if(fruit==null)
cStats = totalStats;
}else{
if(fruit==null)
cStats = unameStats.get(uname);
else{
cStats = pairStats.get(pair);
}
}
int sum = rs.getInt(3);
int avg = rs.getInt(4);
int min = rs.getInt(5);
int max = rs.getInt(6);
int cMin = cStats.getMin();
int cMax = cStats.getMax();
int cSum = cStats.getSum();
int cAvg = cStats.getAvg();
SpliceLogUtils.trace(LOG, "pair=%s, sum=%d,avg=%d,min=%d,max=%d, cSum=%d,cAvg=%d,cMin=%d,cMax=%d",pair,sum,avg,min,max,cSum,cAvg,cMin,cMax);
Assert.assertEquals("Incorrect min for pair "+ pair,cMin,min);
Assert.assertEquals("Incorrect max for pair "+ pair,cMax,max);
Assert.assertEquals("Incorrect avg for pair "+ pair,cAvg,avg);
Assert.assertEquals("Incorrect sum for pair "+ pair,cSum,sum);
row++;
}
Assert.assertEquals("Not all groups found!", pairStats.size()+unameStats.size()+1,row);
}
private static class Pair {
private final String key1;
private final String key2;
private Pair(String key1,String key2){
this.key1 = key1;
this.key2 = key2;
}
public static Pair newPair(String key1,String key2){
return new Pair(key1,key2);
}
public String first(){ return key1;}
public String second() { return key2;}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key1 == null) ? 0 : key1.hashCode());
result = prime * result + ((key2 == null) ? 0 : key2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Pair))
return false;
Pair other = (Pair) obj;
if (key1 == null) {
if (other.key1 != null)
return false;
} else if (!key1.equals(other.key1))
return false;
if (key2 == null) {
if (other.key2 != null)
return false;
} else if (!key2.equals(other.key2))
return false;
return true;
}
@Override
public String toString() {
return "("+key1+","+key2+")";
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.sam;
import com.google.common.base.Predicate;
import org.apache.log4j.Logger;
import org.broad.igv.data.Interval;
import org.broad.igv.feature.FeatureUtils;
import org.broad.igv.feature.Locus;
import org.broad.igv.feature.SpliceJunctionFeature;
import org.broad.igv.feature.Strand;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.tribble.Feature;
import java.util.*;
import static org.broad.igv.util.collections.CollUtils.filter;
/**
* @author jrobinso
*/
public class AlignmentInterval extends Locus implements Interval {
private static Logger log = Logger.getLogger(AlignmentInterval.class);
Genome genome;
private int maxCount = 0;
private AlignmentCounts counts;
private LinkedHashMap<String, List<Row>> groupedAlignmentRows; // The alignments
private List<SpliceJunctionFeature> spliceJunctions;
private List<DownsampledInterval> downsampledIntervals;
private AlignmentTrack.RenderOptions renderOptions;
public AlignmentInterval(String chr, int start, int end,
LinkedHashMap<String, List<Row>> groupedAlignmentRows,
AlignmentCounts counts,
List<SpliceJunctionFeature> spliceJunctions,
List<DownsampledInterval> downsampledIntervals,
AlignmentTrack.RenderOptions renderOptions) {
super(chr, start, end);
this.groupedAlignmentRows = groupedAlignmentRows;
genome = GenomeManager.getInstance().getCurrentGenome();
//reference = genome.getSequence(chr, start, end);
this.counts = counts;
this.maxCount = counts.getMaxCount();
this.spliceJunctions = spliceJunctions;
this.downsampledIntervals = downsampledIntervals;
this.renderOptions = renderOptions;
}
static AlignmentInterval emptyAlignmentInterval(String chr, int start, int end) {
return new AlignmentInterval(chr, start, end, null, null, null, null, null);
}
static Alignment getFeatureContaining(List<Alignment> features, int right) {
int leftBounds = 0;
int rightBounds = features.size() - 1;
int idx = features.size() / 2;
int lastIdx = -1;
while (idx != lastIdx) {
lastIdx = idx;
Alignment f = features.get(idx);
if (f.contains(right)) {
return f;
}
if (f.getStart() > right) {
rightBounds = idx;
idx = (leftBounds + idx) / 2;
} else {
leftBounds = idx;
idx = (rightBounds + idx) / 2;
}
}
// Check the extremes
if (features.get(0).contains(right)) {
return features.get(0);
}
if (features.get(rightBounds).contains(right)) {
return features.get(rightBounds);
}
return null;
}
/**
* The "packed" alignments in this interval
*/
public LinkedHashMap<String, List<Row>> getGroupedAlignments() {
return groupedAlignmentRows;
}
public int getGroupCount() {
return groupedAlignmentRows == null ? 0 : groupedAlignmentRows.size();
}
public void setAlignmentRows(LinkedHashMap<String, List<Row>> alignmentRows, AlignmentTrack.RenderOptions renderOptions) {
this.groupedAlignmentRows = alignmentRows;
this.renderOptions = renderOptions;
}
public void sortRows(AlignmentTrack.SortOption option, ReferenceFrame referenceFrame, String tag) {
double center = referenceFrame.getCenter();
sortRows(option, center, tag);
}
/**
* Sort rows group by group
*
* @param option
* @param location
*/
public void sortRows(AlignmentTrack.SortOption option, double location, String tag) {
if (groupedAlignmentRows == null) {
return;
}
for (List<AlignmentInterval.Row> alignmentRows : groupedAlignmentRows.values()) {
for (AlignmentInterval.Row row : alignmentRows) {
row.updateScore(option, location, this, tag);
}
Collections.sort(alignmentRows);
}
}
public byte getReference(int pos) {
if (genome == null) {
return 0;
}
return genome.getReference(getChr(), pos);
}
public AlignmentCounts getCounts() {
return counts;
}
/**
* Return the count of the specified nucleotide
*
* @param pos genomic position
* @param b nucleotide
* @return
*/
public int getCount(int pos, byte b) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getCount(pos, b);
}
return 0;
}
public int getMaxCount() {
return maxCount;
}
public AlignmentCounts getAlignmentCounts(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c;
}
return null;
}
public int getTotalCount(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getTotalCount(pos);
}
return 0;
}
public int getNegCount(int pos, byte b) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getNegCount(pos, b);
}
return 0;
}
public int getPosCount(int pos, byte b) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getPosCount(pos, b);
}
return 0;
}
public int getDelCount(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getDelCount(pos);
}
return 0;
}
public int getInsCount(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getInsCount(pos);
}
return 0;
}
public Iterator<Alignment> getAlignmentIterator() {
return new AlignmentIterator();
}
public List<SpliceJunctionFeature> getSpliceJunctions() {
return spliceJunctions;
}
public List<DownsampledInterval> getDownsampledIntervals() {
return downsampledIntervals;
}
@Override
public boolean contains(String chr, int start, int end, int zoom) {
return super.contains(chr, start, end);
}
@Override
public boolean overlaps(String chr, int start, int end, int zoom) {
return super.overlaps(chr, start, end);
}
@Override
public boolean canMerge(Interval i) {
if (!super.overlaps(i.getChr(), i.getStart(), i.getEnd())
|| !(i instanceof AlignmentInterval)) {
return false;
}
return getCounts().getClass().equals(((AlignmentInterval) i).getCounts().getClass());
}
@Override
public boolean merge(Interval i) {
boolean canMerge = this.canMerge(i);
if (!canMerge) return false;
AlignmentInterval other = (AlignmentInterval) i;
List<Alignment> allAlignments = (List<Alignment>) FeatureUtils.combineSortedFeatureListsNoDups(
getAlignmentIterator(), other.getAlignmentIterator(), start, end);
this.counts = counts.merge(other.getCounts(), renderOptions.bisulfiteContext);
this.spliceJunctions = FeatureUtils.combineSortedFeatureListsNoDups(this.spliceJunctions, other.getSpliceJunctions(), start, end);
this.downsampledIntervals = FeatureUtils.combineSortedFeatureListsNoDups(this.downsampledIntervals, other.getDownsampledIntervals(), start, end);
//This must be done AFTER calling combineSortedFeatureListsNoDups for the last time,
//because we rely on the original start/end
this.start = Math.min(getStart(), i.getStart());
this.end = Math.max(getEnd(), i.getEnd());
this.maxCount = Math.max(this.getMaxCount(), other.getMaxCount());
AlignmentPacker packer = new AlignmentPacker();
this.groupedAlignmentRows = packer.packAlignments(allAlignments.iterator(), this.end, renderOptions);
return true;
}
/**
* Remove data outside the specified interval.
* This interval must contain the specified interval.
*
* @param chr
* @param start
* @param end
* @param zoom
* @return true if any trimming was performed, false if not
*/
public boolean trimTo(final String chr, final int start, final int end, int zoom) {
boolean toRet = false;
if (!this.contains(chr, start, end, zoom)) {
return false;
}
for (String groupKey : groupedAlignmentRows.keySet()) {
for (AlignmentInterval.Row row : groupedAlignmentRows.get(groupKey)) {
Iterator<Alignment> alIter = row.alignments.iterator();
Alignment al;
while (alIter.hasNext()) {
al = alIter.next();
if (al.getEnd() < start || al.getStart() > end) {
alIter.remove();
toRet |= true;
}
}
}
}
Predicate<Feature> overlapPredicate = FeatureUtils.getOverlapPredicate(chr, start, end);
//getCounts().trimTo(chr, start, end);
filter(this.getDownsampledIntervals(), overlapPredicate);
filter(this.getSpliceJunctions(), overlapPredicate);
this.start = Math.max(this.start, start);
this.end = Math.min(this.end, end);
return toRet;
}
private List addToListNoDups(List self, List other) {
if (self == null) self = new ArrayList();
if (other != null) {
Set selfSet = new HashSet(self);
selfSet.addAll(other);
self = new ArrayList(selfSet);
FeatureUtils.sortFeatureList(self);
}
return self;
}
/**
* AlignmentInterval data is independent of zoom
*
* @return
*/
@Override
public int getZoom() {
return -1;
}
public static class Row implements Comparable<Row> {
int nextIdx;
private double score = 0;
List<Alignment> alignments;
private int start;
private int lastEnd;
public Row() {
nextIdx = 0;
this.alignments = new ArrayList(100);
}
public void addAlignment(Alignment alignment) {
if (alignments.isEmpty()) {
this.start = alignment.getStart();
}
alignments.add(alignment);
lastEnd = alignment.getEnd();
}
public void updateScore(AlignmentTrack.SortOption option, double center, AlignmentInterval interval, String tag) {
int adjustedCenter = (int) center;
Alignment centerAlignment = getFeatureContaining(alignments, adjustedCenter);
if (centerAlignment == null) {
setScore(Double.MAX_VALUE);
} else {
switch (option) {
case START:
setScore(centerAlignment.getStart());
break;
case STRAND:
setScore(centerAlignment.isNegativeStrand() ? -1 : 1);
break;
case FIRST_OF_PAIR_STRAND:
Strand strand = centerAlignment.getFirstOfPairStrand();
int score = 2;
if (strand != Strand.NONE) {
score = strand == Strand.NEGATIVE ? 1 : -1;
}
setScore(score);
break;
case NUCELOTIDE:
byte base = centerAlignment.getBase(adjustedCenter);
byte ref = interval.getReference(adjustedCenter);
if (base == 'N' || base == 'n') {
setScore(Integer.MAX_VALUE - 2); // Base is "n"
} else if (base == ref) {
setScore(Integer.MAX_VALUE - 1); // Base is reference
} else {
//If base is 0, base not covered (splice junction) or is deletion
if (base == 0) {
int delCount = interval.getDelCount(adjustedCenter);
if (delCount > 0) {
setScore(-delCount);
} else {
//Base not covered, NOT a deletion
setScore(Integer.MAX_VALUE);
}
} else {
int count = interval.getCount(adjustedCenter, base);
byte phred = centerAlignment.getPhred(adjustedCenter);
setScore(-(count + (phred / 100.0f)));
}
}
break;
case QUALITY:
setScore(-centerAlignment.getMappingQuality());
break;
case SAMPLE:
String sample = centerAlignment.getSample();
score = sample == null ? 0 : sample.hashCode();
setScore(score);
break;
case READ_GROUP:
String readGroup = centerAlignment.getReadGroup();
score = readGroup == null ? 0 : readGroup.hashCode();
setScore(score);
break;
case INSERT_SIZE:
setScore(-Math.abs(centerAlignment.getInferredInsertSize()));
break;
case MATE_CHR:
ReadMate mate = centerAlignment.getMate();
if (mate == null) {
setScore(Integer.MAX_VALUE);
} else {
if (mate.getChr().equals(centerAlignment.getChr())) {
setScore(Integer.MAX_VALUE - 1);
} else {
setScore(mate.getChr().hashCode());
}
}
break;
case TAG:
Object tagValue = centerAlignment.getAttribute(tag);
score = tagValue == null ? 0 : tagValue.hashCode();
setScore(score);
break;
}
}
}
// Used for iterating over all alignments, e.g. for packing
public Alignment nextAlignment() {
if (nextIdx < alignments.size()) {
Alignment tmp = alignments.get(nextIdx);
nextIdx++;
return tmp;
} else {
return null;
}
}
public int getNextStartPos() {
if (nextIdx < alignments.size()) {
return alignments.get(nextIdx).getStart();
} else {
return Integer.MAX_VALUE;
}
}
public boolean hasNext() {
return nextIdx < alignments.size();
}
public void resetIdx() {
nextIdx = 0;
}
/**
* @return the score
*/
public double getScore() {
return score;
}
/**
* @param score the score to set
*/
public void setScore(double score) {
this.score = score;
}
public int getStart() {
return start;
}
public int getLastEnd() {
return lastEnd;
}
@Override
public int compareTo(Row o) {
return (int) Math.signum(getScore() - o.getScore());
}
// @Override
// public boolean equals(Object object){
// if(!(object instanceof Row)){
// return false;
// Row other = (Row) object;
// boolean equals = this.getStart() == other.getStart();
// equals &= this.getLastEnd() == other.getLastEnd();
// equals &= this.getScore() == other.getScore();
// return equals;
// @Override
// public int hashCode(){
// int score = (int) getScore();
// score = score != 0 ? score : 1;
// return (getStart() * getLastEnd() * score);
} // end class row
/**
* An alignment iterator that iterates over packed rows. Used for
* "repacking". Using the iterator avoids the need to copy alignments
* from the rows
*/
class AlignmentIterator implements Iterator<Alignment> {
PriorityQueue<AlignmentInterval.Row> rows;
Alignment nextAlignment;
AlignmentIterator() {
rows = new PriorityQueue(5, new Comparator<AlignmentInterval.Row>() {
public int compare(AlignmentInterval.Row o1, AlignmentInterval.Row o2) {
return o1.getNextStartPos() - o2.getNextStartPos();
}
});
for (List<AlignmentInterval.Row> alignmentRows : groupedAlignmentRows.values()) {
for (AlignmentInterval.Row r : alignmentRows) {
r.resetIdx();
rows.add(r);
}
}
advance();
}
public boolean hasNext() {
return nextAlignment != null;
}
public Alignment next() {
Alignment tmp = nextAlignment;
if (tmp != null) {
advance();
}
return tmp;
}
private void advance() {
nextAlignment = null;
AlignmentInterval.Row nextRow = null;
while (nextAlignment == null && !rows.isEmpty()) {
while ((nextRow = rows.poll()) != null) {
if (nextRow.hasNext()) {
nextAlignment = nextRow.nextAlignment();
break;
}
}
}
if (nextRow != null && nextAlignment != null) {
rows.add(nextRow);
}
}
public void remove() {
// ignore
}
}
}
|
package de.digitalcollections.blueprints.webapp.springboot;
import java.io.IOException;
import java.net.URI;
import java.util.Base64;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import redis.embedded.RedisServer;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {"management.server.port=0"}) // set random management port
public class ApplicationTest {
@TestConfiguration
public static class EmbeddedRedisTestConfiguration {
private final RedisServer redisServer;
public EmbeddedRedisTestConfiguration(@Value("${spring.redis.port}") final int redisPort, @Value("${spring.redis.password}") final String redisPassword) throws IOException {
redisServer = RedisServer.builder().port(redisPort).setting("requirepass " + redisPassword).build();
}
@PostConstruct
public void startRedis() {
this.redisServer.start();
}
@PreDestroy
public void stopRedis() {
this.redisServer.stop();
}
}
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private RedisTemplate<String, String> redisTemplate;
// "local" is not profile name, it is needed to use random port
@LocalManagementPort //("${local.management.port}")
private int monitoringPort;
@Test
public void shouldReturn401WhenSendingUnauthorizedRequestToSensitiveManagementEndpoint() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.getForEntity(
"http://localhost:" + this.monitoringPort + "/monitoring/env", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void ensureSessionIdDoesNotChangeWhichMeansThatSessionHandlingViaRedisWorks() throws Exception {
URI uri = URI.create("http://localhost:" + this.monitoringPort + "/monitoring/env");
// First request with authentication
HttpHeaders headers1 = new HttpHeaders();
headers1.set("Authorization", "Basic " + Base64.getEncoder().encodeToString("admin:secret".getBytes()));
RequestEntity<Object> request1 = new RequestEntity(headers1, HttpMethod.GET, uri);
ResponseEntity<String> response1 = restTemplate.exchange(request1, String.class);
assertThat(response1.getStatusCode()).isEqualTo(HttpStatus.OK);
String firstSessionId = response1.getBody();
String cookie = response1.getHeaders().getFirst("Set-Cookie");
// Second requests uses sessionId but does not authenticate again
HttpHeaders headers2 = new HttpHeaders();
headers2.set("Cookie", cookie);
RequestEntity<Object> request2 = new RequestEntity(headers2, HttpMethod.GET, uri);
ResponseEntity<String> response2 = restTemplate.exchange(request2, String.class);
assertThat(response2.getStatusCode()).isEqualTo(HttpStatus.OK);
String secondSessionId = response2.getBody();
assertThat(firstSessionId).isEqualTo(secondSessionId);
}
}
|
package org.broad.igv.sam;
import org.apache.log4j.Logger;
import org.broad.igv.PreferenceManager;
import org.broad.igv.feature.Strand;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.renderer.GraphicUtils;
import org.broad.igv.sam.AlignmentTrack.ColorOption;
import org.broad.igv.sam.AlignmentTrack.RenderOptions;
import org.broad.igv.sam.BisulfiteBaseInfo.DisplayStatus;
import org.broad.igv.track.RenderContext;
import org.broad.igv.ui.FontManager;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.color.ColorPalette;
import org.broad.igv.ui.color.ColorTable;
import org.broad.igv.ui.color.ColorUtilities;
import org.broad.igv.ui.color.PaletteColorTable;
import org.broad.igv.util.ChromosomeColors;
import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author jrobinso
*/
public class AlignmentRenderer implements FeatureRenderer {
private static Logger log = Logger.getLogger(AlignmentRenderer.class);
public static Map<Character, Color> nucleotideColors;
private static Color smallISizeColor = new Color(0, 0, 150);
private static Color largeISizeColor = new Color(150, 0, 0);
private static Color purple = new Color(118, 24, 220);
private static Color deletionColor = Color.black;
private static Color skippedColor = new Color(150, 184, 200);
public static Color grey1 = new Color(200, 200, 200);
private static Stroke thickStroke = new BasicStroke(2.0f);
// Bisulfite constants
public static final Color bisulfiteColorFw1 = new Color(195, 195, 195); // A bit lighter than normal LR_COLOR
public static final Color bisulfiteColorRev1 = new Color(195, 210, 195); // A bit lighter than normal LR_COLOR
public static final Color bisulfiteColorRev2 = new Color(210, 210, 210); // A bit lighter than normal LR_COLOR
public static final Color bisulfiteColorFw2 = new Color(210, 222, 210); // A bit lighter than normal LR_COLOR
public static final Color nomeseqColor = new Color(195, 195, 195); // A bit lighter than normal LR_COLOR
public static final Color negStrandColor = new Color(190, 190, 205); // A bit lighter than normal LR_COLOR
public static final Color posStrandColor = new Color(205, 190, 190); // A bit lighter than normal LR_COLOR
//public static final Color negStrandColor = new Color(150, 150, 200);
// public static final Color posStrandColor = new Color(200, 150, 150);
private static ColorTable readGroupColors;
private static ColorTable sampleColors;
private static ColorTable tagValueColors;
private static final Color LR_COLOR = grey1; // "Normal" alignment color
private static final Color RL_COLOR = new Color(0, 150, 0);
private static final Color RR_COLOR = new Color(0, 0, 150);
private static final Color LL_COLOR = new Color(0, 150, 150);
private static final Color OUTLINE_COLOR = new Color(185, 185, 185);
public static final Color GROUP_DIVIDER_COLOR = new Color(200, 200, 200);
static Map<String, Color> frOrientationColors;
static Map<String, Color> ffOrientationColors;
static Map<String, Color> rfOrientationColors;
PreferenceManager prefs;
static {
nucleotideColors = new HashMap();
nucleotideColors.put('A', Color.GREEN);
nucleotideColors.put('a', Color.GREEN);
nucleotideColors.put('C', Color.BLUE);
nucleotideColors.put('c', Color.BLUE);
nucleotideColors.put('T', Color.RED);
nucleotideColors.put('t', Color.RED);
nucleotideColors.put('G', new Color(209, 113, 5));
nucleotideColors.put('g', new Color(209, 113, 5));
nucleotideColors.put('N', Color.gray.brighter());
nucleotideColors.put('n', Color.gray.brighter());
// fr Orienations (e.g. Illumina paired-end libraries)
frOrientationColors = new HashMap();
frOrientationColors.put("F1R2", LR_COLOR);
frOrientationColors.put("F2R1", LR_COLOR);
frOrientationColors.put("F R ", LR_COLOR);
frOrientationColors.put("FR", LR_COLOR);
frOrientationColors.put("F1F2", LL_COLOR);
frOrientationColors.put("F2F1", LL_COLOR);
frOrientationColors.put("F F ", LL_COLOR);
frOrientationColors.put("FF", LL_COLOR);
frOrientationColors.put("R1R2", RR_COLOR);
frOrientationColors.put("R2R1", RR_COLOR);
frOrientationColors.put("R R ", RR_COLOR);
frOrientationColors.put("RR", RR_COLOR);
frOrientationColors.put("R1F2", RL_COLOR);
frOrientationColors.put("R2F1", RL_COLOR);
frOrientationColors.put("R F ", RL_COLOR);
frOrientationColors.put("RF", RL_COLOR);
// rf orienation (e.g. Illumina mate-pair libraries)
rfOrientationColors = new HashMap();
rfOrientationColors.put("R1F2", LR_COLOR);
rfOrientationColors.put("R2F1", LR_COLOR);
rfOrientationColors.put("R F ", LR_COLOR);
rfOrientationColors.put("RF", LR_COLOR);
rfOrientationColors.put("R1R2", LL_COLOR);
rfOrientationColors.put("R2R1", LL_COLOR);
rfOrientationColors.put("R R ", LL_COLOR);
rfOrientationColors.put("RR ", LL_COLOR);
rfOrientationColors.put("F1F2", RR_COLOR);
rfOrientationColors.put("F2F1", RR_COLOR);
rfOrientationColors.put("F F ", RR_COLOR);
rfOrientationColors.put("FF", RR_COLOR);
rfOrientationColors.put("F1R2", RL_COLOR);
rfOrientationColors.put("F2R1", RL_COLOR);
rfOrientationColors.put("F R ", RL_COLOR);
rfOrientationColors.put("FR", RL_COLOR);
// ff orienation (e.g. SOLID libraries)
ffOrientationColors = new HashMap();
ffOrientationColors.put("F1F2", LR_COLOR);
ffOrientationColors.put("R2R1", LR_COLOR);
//LL -- switched with RR color per Bob's instructions
ffOrientationColors.put("F1R2", RR_COLOR);
ffOrientationColors.put("R2F1", RR_COLOR);
ffOrientationColors.put("R1F2", LL_COLOR);
ffOrientationColors.put("F2R1", LL_COLOR);
ffOrientationColors.put("R1R2", RL_COLOR);
ffOrientationColors.put("F2F1", RL_COLOR);
}
public AlignmentRenderer() {
this.prefs = PreferenceManager.getInstance();
if (readGroupColors == null) {
initializeTagColors();
}
}
private static synchronized void initializeTagColors() {
ColorPalette palette = ColorUtilities.getPalette("Pastel 1"); // TODO let user choose
readGroupColors = new PaletteColorTable(palette);
sampleColors = new PaletteColorTable(palette);
tagValueColors = new PaletteColorTable(palette);
}
/**
* Render a row of alignments in the given rectangle.
*/
public void renderAlignments(List<Alignment> alignments,
RenderContext context,
Rectangle rect,
AlignmentTrack.RenderOptions renderOptions,
boolean leaveMargin,
Map<String, Color> selectedReadNames) {
double origin = context.getOrigin();
double locScale = context.getScale();
Rectangle screenRect = context.getVisibleRect();
Font font = FontManager.getFont(10);
if ((alignments != null) && (alignments.size() > 0)) {
//final SAMPreferences prefs = PreferenceManager.getInstance().getSAMPreferences();
//int insertSizeThreshold = renderOptions.insertSizeThreshold;
for (Alignment alignment : alignments) {
// Compute the start and dend of the alignment in pixels
double pixelStart = ((alignment.getStart() - origin) / locScale);
double pixelEnd = ((alignment.getEnd() - origin) / locScale);
// If the any part of the feature fits in the track rectangle draw it
if (pixelEnd < rect.x) {
continue;
} else if (pixelStart > rect.getMaxX()) {
break;
}
// If the alignment is 3 pixels or less, draw alignment as a single block,
// further detail would not be seen and just add to drawing overhead
// Does the change for Bisulfite kill some machines?
double pixelWidth = pixelEnd - pixelStart;
if ((pixelWidth < 4) && !(AlignmentTrack.isBisulfiteColorType(renderOptions.getColorOption()) && (pixelWidth >= 1))) {
Color alignmentColor = getAlignmentColor(alignment, renderOptions);
Graphics2D g = context.getGraphic2DForColor(alignmentColor);
g.setFont(font);
int w = Math.max(1, (int) (pixelWidth));
int h = (int) Math.max(1, rect.getHeight() - 2);
int y = (int) (rect.getY() + (rect.getHeight() - h) / 2);
g.fillRect((int) pixelStart, y, w, h);
} else if (alignment instanceof PairedAlignment) {
drawPairedAlignment((PairedAlignment) alignment, rect, context, renderOptions, leaveMargin, selectedReadNames, font);
} else {
Color alignmentColor = getAlignmentColor(alignment, renderOptions);
Graphics2D g = context.getGraphic2DForColor(alignmentColor);
g.setFont(font);
drawAlignment(alignment, rect, g, context, alignmentColor, renderOptions, leaveMargin, selectedReadNames);
}
}
// Optionally draw a border around the center base
boolean showCenterLine = prefs.getAsBoolean(PreferenceManager.SAM_SHOW_CENTER_LINE);
final int bottom = rect.y + rect.height;
if (locScale < 5 && showCenterLine) {
// Calculate center lines
double center = (int) (context.getReferenceFrame().getCenter() - origin);
int centerLeftP = (int) (center / locScale);
int centerRightP = (int) ((center + 1) / locScale);
//float transparency = Math.max(0.5f, (float) Math.round(10 * (1 - .75 * locScale)) / 10);
Graphics2D gBlack = context.getGraphic2DForColor(Color.black); //new Color(0, 0, 0, transparency));
GraphicUtils.drawDottedDashLine(gBlack, centerLeftP, rect.y, centerLeftP, bottom);
if ((centerRightP - centerLeftP > 2)) {
GraphicUtils.drawDottedDashLine(gBlack, centerRightP, rect.y, centerRightP, bottom);
}
}
}
}
/**
* Method for drawing alignments without "blocks" (e.g. DotAlignedAlignment)
*/
private void drawSimpleAlignment(Alignment alignment,
Rectangle rect,
Graphics2D g,
RenderContext context,
boolean flagUnmappedPair) {
double origin = context.getOrigin();
double locScale = context.getScale();
int x = (int) ((alignment.getStart() - origin) / locScale);
int length = alignment.getEnd() - alignment.getStart();
int w = (int) Math.ceil(length / locScale);
int h = (int) Math.max(1, rect.getHeight() - 2);
int y = (int) (rect.getY() + (rect.getHeight() - h) / 2);
int arrowLength = Math.min(5, w / 6);
int[] xPoly = null;
int[] yPoly = {y, y, y + h / 2, y + h, y + h};
// Don't draw off edge of clipping rect
if (x < rect.x && (x + w) > (rect.x + rect.width)) {
x = rect.x;
w = rect.width;
arrowLength = 0;
} else if (x < rect.x) {
int delta = rect.x - x;
x = rect.x;
w -= delta;
if (alignment.isNegativeStrand()) {
arrowLength = 0;
}
} else if ((x + w) > (rect.x + rect.width)) {
w -= ((x + w) - (rect.x + rect.width));
if (!alignment.isNegativeStrand()) {
arrowLength = 0;
}
}
if (alignment.isNegativeStrand()) {
// 2 1
// 5 5
xPoly = new int[]{x + w, x, x - arrowLength, x, x + w};
} else {
// 1 2
// 5 4
xPoly = new int[]{x, x + w, x + w + arrowLength, x + w, x};
}
g.fillPolygon(xPoly, yPoly, xPoly.length);
if (flagUnmappedPair && alignment.isPaired() && !alignment.getMate().isMapped()) {
Graphics2D cRed = context.getGraphic2DForColor(Color.red);
cRed.drawPolygon(xPoly, yPoly, xPoly.length);
}
}
/**
* Draw a pair of alignments as a single "template".
*
* @param pair
* @param rect
* @param context
* @param renderOptions
* @param leaveMargin
* @param selectedReadNames
* @param font
*/
private void drawPairedAlignment(
PairedAlignment pair,
Rectangle rect,
RenderContext context,
AlignmentTrack.RenderOptions renderOptions,
boolean leaveMargin,
Map<String, Color> selectedReadNames,
Font font) {
double locScale = context.getScale();
Color alignmentColor = getAlignmentColor(pair.firstAlignment, renderOptions);
Graphics2D g = context.getGraphic2DForColor(alignmentColor);
g.setFont(font);
drawAlignment(pair.firstAlignment, rect, g, context, alignmentColor, renderOptions, leaveMargin, selectedReadNames);
if (pair.secondAlignment != null) {
alignmentColor = getAlignmentColor(pair.secondAlignment, renderOptions);
g = context.getGraphic2DForColor(alignmentColor);
drawAlignment(pair.secondAlignment, rect, g, context, alignmentColor, renderOptions, leaveMargin, selectedReadNames);
Graphics2D gLine = context.getGraphic2DForColor(grey1);
double origin = context.getOrigin();
int startX = (int) ((pair.firstAlignment.getEnd() - origin) / locScale);
startX = Math.max(rect.x, startX);
int endX = (int) ((pair.secondAlignment.getStart() - origin) / locScale);
endX = Math.min(rect.x + rect.width, endX);
int h = (int) Math.max(1, rect.getHeight() - (leaveMargin ? 2 : 0));
int y = (int) (rect.getY()); // + (rect.getHeight() - h) / 2);
gLine.drawLine(startX, y + h / 2, endX, y + h / 2);
}
}
/**
* Draw a (possible) gapped alignment
*
* @param alignment
* @param rect
* @param g
* @param context
* @param alignmentColor
* @param renderOptions
* @param leaveMargin
* @param selectedReadNames
*/
private void drawAlignment(
Alignment alignment,
Rectangle rect,
Graphics2D g,
RenderContext context,
Color alignmentColor,
AlignmentTrack.RenderOptions renderOptions,
boolean leaveMargin,
Map<String, Color> selectedReadNames) {
double origin = context.getOrigin();
double locScale = context.getScale();
AlignmentBlock[] blocks = alignment.getAlignmentBlocks();
// No blocks. Note: SAM/BAM alignments always have at least 1 block
if (blocks == null || blocks.length == 0) {
drawSimpleAlignment(alignment, rect, g, context, renderOptions.flagUnmappedPairs);
return;
}
// Get the terminal block (last block with respect to read direction). This will have an "arrow" attached.
AlignmentBlock terminalBlock = alignment.isNegativeStrand() ? blocks[0] : blocks[blocks.length - 1];
int lastBlockEnd = Integer.MIN_VALUE;
int blockNumber = -1;
char[] gapTypes = alignment.getGapTypes();
boolean highZoom = locScale < 0.1251;
for (AlignmentBlock aBlock : alignment.getAlignmentBlocks()) {
blockNumber++;
int x = (int) ((aBlock.getStart() - origin) / locScale);
int w = (int) Math.ceil(aBlock.getBases().length / locScale);
int h = (int) Math.max(1, rect.getHeight() - (leaveMargin ? 2 : 0));
int y = (int) (rect.getY()); // + (rect.getHeight() - h) / 2);
// Get a graphics context for outlining reads
Graphics2D outlineGraphics = context.getGraphic2DForColor(OUTLINE_COLOR);
// Create polygon to represent the alignment.
boolean isZeroQuality = alignment.getMappingQuality() == 0 && renderOptions.flagZeroQualityAlignments;
// If we're zoomed in and this is a large block clip a pixel off each end. TODO - why?
if (highZoom && w > 10) {
x++;
w -= 2;
}
// If block is out of view skip -- this is important in the case of PacBio and other platforms with very long reads
if (x + w >= rect.x && x <= rect.getMaxX()) {
Shape blockShape = null;
// If this is a terminal block draw the "arrow" to indicate strand position. Otherwise draw a rectangle.
if ((aBlock == terminalBlock) && w > 10 && h > 10) {
int arrowLength = Math.min(5, w / 6);
// Don't draw off edge of clipping rect
if (x < rect.x && (x + w) > (rect.x + rect.width)) {
x = rect.x;
w = rect.width;
arrowLength = 0;
} else if (x < rect.x) {
int delta = rect.x - x;
x = rect.x;
w -= delta;
if (alignment.isNegativeStrand()) {
arrowLength = 0;
}
} else if ((x + w) > (rect.x + rect.width)) {
w -= ((x + w) - (rect.x + rect.width));
if (!alignment.isNegativeStrand()) {
arrowLength = 0;
}
}
int[] xPoly;
int[] yPoly = {y, y, y + h / 2, y + h, y + h};
if (alignment.isNegativeStrand()) {
xPoly = new int[]{x + w, x, x - arrowLength, x, x + w};
} else {
xPoly = new int[]{x, x + w, x + w + arrowLength, x + w, x};
}
blockShape = new Polygon(xPoly, yPoly, xPoly.length);
} else {
// Not a terminal block, or too small for arrow
blockShape = new Rectangle(x, y, w, h);
}
g.fill(blockShape);
if (isZeroQuality) {
outlineGraphics.draw(blockShape);
}
if (renderOptions.flagUnmappedPairs && alignment.isPaired() && !alignment.getMate().isMapped()) {
Graphics2D cRed = context.getGraphic2DForColor(Color.red);
cRed.draw(blockShape);
}
if (selectedReadNames.containsKey(alignment.getReadName())) {
Color c = selectedReadNames.get(alignment.getReadName());
if (c == null) {
c = Color.blue;
}
Graphics2D cBlue = context.getGraphic2DForColor(c);
Stroke s = cBlue.getStroke();
cBlue.setStroke(thickStroke);
cBlue.draw(blockShape);
cBlue.setStroke(s);
}
}
if ((locScale < 5) || (AlignmentTrack.isBisulfiteColorType(renderOptions.getColorOption()) && (locScale < 100))) // Is 100 here going to kill some machines? bpb
{
if (renderOptions.showMismatches || renderOptions.showAllBases) {
drawBases(context, rect, aBlock, alignmentColor, renderOptions);
}
}
// Draw connecting lines between blocks, if in view
if (lastBlockEnd > Integer.MIN_VALUE && x > rect.x) {
Graphics2D gLine;
Stroke stroke;
int gapIdx = blockNumber - 1;
Color gapLineColor = deletionColor;
if (gapTypes != null && gapIdx < gapTypes.length && gapTypes[gapIdx] == SamAlignment.SKIPPED_REGION) {
gLine = context.getGraphic2DForColor(skippedColor);
stroke = gLine.getStroke();
} else {
gLine = context.getGraphic2DForColor(gapLineColor);
stroke = gLine.getStroke();
//gLine.setStroke(dashedStroke);
gLine.setStroke(thickStroke);
}
int startX = Math.max(rect.x, lastBlockEnd);
int endX = Math.min(rect.x + rect.width, x);
gLine.drawLine(startX, y + h / 2, endX, y + h / 2);
gLine.setStroke(stroke);
}
lastBlockEnd = x + w;
// Next block cannot start before lastBlockEnd. If its out of view we are done.
if (lastBlockEnd > rect.getMaxX()) {
break;
}
}
// Render insertions if locScale ~ 0.25 (base level)
if (locScale < 0.25) {
drawInsertions(origin, rect, locScale, alignment, context);
}
}
/**
* Draw bases for an alignment block. The bases are "overlaid" on the block with a transparency value (alpha)
* that is proportional to the base quality score.
*
* @param context
* @param rect
* @param block
* @param alignmentColor
*/
private void drawBases(RenderContext context,
Rectangle rect,
AlignmentBlock block,
Color alignmentColor,
RenderOptions renderOptions) {
boolean shadeBases = renderOptions.shadeBases;
ColorOption colorOption = renderOptions.getColorOption();
// Disable showAllBases in bisulfite mode
boolean showAllBases = renderOptions.showAllBases &&
!(colorOption == ColorOption.BISULFITE || colorOption == ColorOption.NOMESEQ);
double locScale = context.getScale();
double origin = context.getOrigin();
String chr = context.getChr();
//String genomeId = context.getGenomeId();
Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome();
byte[] read = block.getBases();
boolean isSoftClipped = block.isSoftClipped();
int start = block.getStart();
int end = start + read.length;
byte[] reference = isSoftClipped ? null : genome.getSequence(chr, start, end);
if (read != null && read.length > 0 && reference != null) {
// Compute bounds, get a graphics to use, and compute a font
int pY = (int) rect.getY();
int dY = (int) rect.getHeight();
int dX = (int) Math.max(1, (1.0 / locScale));
Graphics2D g = (Graphics2D) context.getGraphics().create();
if (dX >= 8) {
Font f = FontManager.getFont(Font.BOLD, Math.min(dX, 12));
g.setFont(f);
}
// Get the base qualities, start/end, and reference sequence
BisulfiteBaseInfo bisinfo = null;
boolean nomeseqMode = (renderOptions.getColorOption().equals(AlignmentTrack.ColorOption.NOMESEQ));
boolean bisulfiteMode = AlignmentTrack.isBisulfiteColorType(renderOptions.getColorOption());
if (nomeseqMode) {
bisinfo = new BisulfiteBaseInfoNOMeseq(reference, block, renderOptions.bisulfiteContext);
} else if (bisulfiteMode) {
bisinfo = new BisulfiteBaseInfo(reference, block, renderOptions.bisulfiteContext);
}
// Loop through base pair coordinates
for (int loc = start; loc < end; loc++) {
// Index into read array, just the genomic location offset by
// the start of this block
int idx = loc - start;
// Is this base a mismatch? Note '=' means indicates a match by definition
// If we do not have a valid reference we assume a match. Soft clipped
// bases are considered mismatched by definition
boolean misMatch;
if (isSoftClipped) {
misMatch = true; // <= by definition, any matches are coincidence
} else {
final byte refbase = reference[idx];
final byte readbase = read[idx];
misMatch = readbase != '=' &&
reference != null &&
idx < reference.length &&
refbase != 0 &&
!AlignmentUtils.compareBases(refbase, readbase);
}
if (showAllBases || (!bisulfiteMode && misMatch) ||
(bisulfiteMode && (!DisplayStatus.NOTHING.equals(bisinfo.getDisplayStatus(idx))))) {
char c = (char) read[idx];
Color color = nucleotideColors.get(c);
if (bisulfiteMode) color = bisinfo.getDisplayColor(idx);
if (color == null) {
color = Color.black;
}
if (shadeBases) {
byte qual = block.qualities[loc - start];
color = getShadedColor(qual, color, alignmentColor, prefs);
}
double bisulfiteXaxisShift = (bisulfiteMode) ? bisinfo.getXaxisShift(idx) : 0;
// If there is room for text draw the character, otherwise
// just draw a rectangle to represent the
int pX0 = (int) (((double) loc + bisulfiteXaxisShift - (double) origin) / (double) locScale);
// Don't draw out of clipping rect
if (pX0 > rect.getMaxX()) {
break;
} else if (pX0 + dX < rect.getX()) {
continue;
}
BisulfiteBaseInfo.DisplayStatus bisstatus = (bisinfo == null) ? null : bisinfo.getDisplayStatus(idx);
// System.err.printf("Draw text? dY=%d, dX=%d, bismode=%s, dispStatus=%s\n",dY,dX,!bisulfiteMode || bisulfiteMode,bisstatus);
if (((dY >= 12) && (dX >= 8)) && (!bisulfiteMode || (bisulfiteMode && bisstatus.equals(DisplayStatus.CHARACTER)))) {
g.setColor(color);
GraphicUtils.drawCenteredText(g, new char[]{c}, pX0, pY + 1, dX, dY - 2);
} else {
int pX0i = pX0, dXi = dX;
// If bisulfite mode, we expand the rectangle to make it more visible
if (bisulfiteMode && bisstatus.equals(DisplayStatus.COLOR)) {
if (dXi < 3) {
int expansion = dXi;
pX0i -= expansion;
dXi += (2 * expansion);
}
}
int dW = (dXi > 4 ? dXi - 1 : dXi);
if (color != null) {
g.setColor(color);
if (dY < 10) {
g.fillRect(pX0i, pY, dXi, dY);
} else {
g.fillRect(pX0i, pY + 1, dW, dY - 3);
}
}
}
}
}
}
}
private Color getShadedColor(byte qual, Color foregroundColor, Color backgroundColor, PreferenceManager prefs) {
float alpha = 0;
int minQ = prefs.getAsInt(PreferenceManager.SAM_BASE_QUALITY_MIN);
if (qual < minQ) {
alpha = 0.1f;
} else {
int maxQ = prefs.getAsInt(PreferenceManager.SAM_BASE_QUALITY_MAX);
alpha = Math.max(0.1f, Math.min(1.0f, 0.1f + 0.9f * (qual - minQ) / (maxQ - minQ)));
}
// Round alpha to nearest 0.1
alpha = ((int) (alpha * 10 + 0.5f)) / 10.0f;
if (alpha >= 1) {
return foregroundColor;
}
Color color = ColorUtilities.getCompositeColor(backgroundColor, foregroundColor, alpha);
return color;
}
private void drawInsertions(double origin, Rectangle rect, double locScale, Alignment alignment, RenderContext context) {
Graphics2D gInsertion = context.getGraphic2DForColor(purple);
AlignmentBlock[] insertions = alignment.getInsertions();
if (insertions != null) {
for (AlignmentBlock aBlock : insertions) {
int x = (int) ((aBlock.getStart() - origin) / locScale);
int h = (int) Math.max(1, rect.getHeight() - 2);
int y = (int) (rect.getY() + (rect.getHeight() - h) / 2);
// Don't draw out of clipping rect
if (x > rect.getMaxX()) {
break;
} else if (x < rect.getX()) {
continue;
}
gInsertion.fillRect(x - 2, y, 4, 2);
gInsertion.fillRect(x - 1, y, 2, h);
gInsertion.fillRect(x - 2, y + h - 2, 4, 2);
}
}
}
private Color getAlignmentColor(Alignment alignment, AlignmentTrack.RenderOptions renderOptions) {
// Set color used to draw the feature. Highlight features that intersect the
// center line. Also restorePersistentState row "score" if alignment intersects center line
String lb = alignment.getLibrary();
if (lb == null) lb = "null";
PEStats peStats = renderOptions.peStats.get(lb);
Color c = alignment.getDefaultColor();
switch (renderOptions.getColorOption()) {
case BISULFITE:
// Just a simple forward/reverse strand color scheme that won't clash with the
// methylation rectangles.
c = (alignment.getFirstOfPairStrand() == Strand.POSITIVE) ? bisulfiteColorFw1 : bisulfiteColorRev1;
// if (alignment.isNegativeStrand()) {
// c = (alignment.isSecondOfPair()) ? bisulfiteColorRev2 : bisulfiteColorRev1;
// } else {
// c = (alignment.isSecondOfPair()) ? bisulfiteColorFw2 : bisulfiteColorFw1;
break;
case NOMESEQ:
c = nomeseqColor;
break;
case INSERT_SIZE:
boolean isPairedAlignment = alignment instanceof PairedAlignment;
if (alignment.isPaired() && alignment.getMate().isMapped() || isPairedAlignment) {
boolean sameChr = isPairedAlignment ||
alignment.getMate().getChr().equals(alignment.getChr());
if (sameChr) {
int readDistance = Math.abs(alignment.getInferredInsertSize());
if (readDistance > 0) {
int minThreshold = renderOptions.getMinInsertSize();
int maxThreshold = renderOptions.getMaxInsertSize();
if (renderOptions.isComputeIsizes() && renderOptions.peStats != null) {
if (peStats != null) {
minThreshold = peStats.getMinThreshold();
maxThreshold = peStats.getMaxThreshold();
}
}
if (readDistance < minThreshold) {
c = smallISizeColor;
} else if (readDistance > maxThreshold) {
c = largeISizeColor;
}
//return renderOptions.insertSizeColorScale.getColor(readDistance);
}
} else {
c = ChromosomeColors.getColor(alignment.getMate().getChr());
if (c == null) {
c = Color.black;
}
}
}
break;
case PAIR_ORIENTATION:
c = getOrientationColor(alignment, peStats);
break;
case READ_STRAND:
if (alignment.isNegativeStrand()) {
c = negStrandColor;
} else {
c = posStrandColor;
}
break;
case FIRST_OF_PAIR_STRAND:
final Strand fragmentStrand = alignment.getFirstOfPairStrand();
if (fragmentStrand == Strand.NEGATIVE) {
c = negStrandColor;
} else if (fragmentStrand == Strand.POSITIVE) {
c = posStrandColor;
}
break;
case READ_GROUP:
String rg = alignment.getReadGroup();
if (rg != null) {
c = readGroupColors.get(rg);
}
break;
case SAMPLE:
String sample = alignment.getSample();
if (sample != null) {
c = sampleColors.get(sample);
}
break;
case TAG:
final String tag = renderOptions.getColorByTag();
if (tag != null) {
Object tagValue = alignment.getAttribute(tag);
if (tagValue != null) {
c = tagValueColors.get(tagValue.toString());
}
}
break;
default:
// if (renderOptions.shadeCenters && center >= alignment.getStart() && center <= alignment.getEnd()) {
// if (locScale < 1) {
// c = grey2;
}
if (c == null) c = grey1;
if (alignment.getMappingQuality() == 0 && renderOptions.flagZeroQualityAlignments) {
// Maping Q = 0
float alpha = 0.15f;
// Assuming white background TODO -- this should probably be passed in
return ColorUtilities.getCompositeColor(Color.white, c, alpha);
}
return c;
}
/**
* @return
*/
private Color getOrientationColor(Alignment alignment, PEStats peStats) {
Color c = null;
if (alignment.isPaired() && !alignment.isProperPair()) {
final String pairOrientation = alignment.getPairOrientation();
if (peStats != null) {
PEStats.Orientation libraryOrientation = peStats.getOrientation();
switch (libraryOrientation) {
case FR:
if (!alignment.isSmallInsert()) {
// if the isize < read length the reads might overlap, invalidating this test
c = frOrientationColors.get(pairOrientation);
}
break;
case RF:
c = rfOrientationColors.get(pairOrientation);
break;
case FF:
c = ffOrientationColors.get(pairOrientation);
break;
}
} else {
// No peStats for this library
if (alignment.getAttribute("CS") != null) {
c = ffOrientationColors.get(pairOrientation);
} else {
c = frOrientationColors.get(pairOrientation);
}
}
}
return c == null ? grey1 : c;
}
}
|
package org.xwiki.script.internal.service;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.script.service.ScriptService;
import org.xwiki.script.service.ScriptServiceManager;
/**
* Locate Script Services by name dynamically at runtime by looking them up agains the Component Manager.
*
* @version $Id$
* @since 2.3M1
*/
@Component
@Singleton
public class DefaultScriptServiceManager implements ScriptServiceManager
{
/**
* Used to locate Script Services dynamically. Note that since the lookup is done dynamically new Script Services
* can be added on the fly in the classloader and they'll be found (after they've been registered against the
* component manager obviously).
*/
@Inject
@Named("context")
private Provider<ComponentManager> componentManager;
/**
* The logger to log.
*/
@Inject
private Logger logger;
@Override
public ScriptService get(String serviceName)
{
ScriptService scriptService = null;
if (this.componentManager.get().hasComponent(ScriptService.class, serviceName)) {
try {
scriptService = this.componentManager.get().getInstance(ScriptService.class, serviceName);
} catch (Exception e) {
this.logger.error("Failed to lookup script service for role hint [{}]", serviceName, e);
}
} else {
this.logger.debug("No script service registered for role hint [{}]", serviceName);
}
return scriptService;
}
}
|
package org.exist.security;
import java.util.Set;
import org.exist.config.Configuration;
import org.exist.config.ConfigurationException;
import org.exist.security.realm.Realm;
import org.exist.storage.DBBroker;
public class EffectiveSubject implements Subject {
private final Account account;
public EffectiveSubject(final Account account) {
this.account = account;
}
@Override
public String getRealmId() {
return account.getRealmId();
}
@Override
public Realm getRealm() {
return account.getRealm();
}
@Override
public int getId() {
return account.getId(); //TODO is this correct or need own reserved id?
}
@Override
public String getUsername() {
return "_effective_" + account.getUsername();
}
@Override
public String getName() {
return "Effective: " + account.getName();
}
@Override
public boolean authenticate(final Object credentials) {
return false;
}
//<editor-fold desc="account status">
@Override
public boolean isAuthenticated() {
return false;
}
@Override
public boolean isExternallyAuthenticated() {
return false;
}
@Override
public boolean isAccountNonExpired() {
return account.isAccountNonExpired();
}
@Override
public boolean isAccountNonLocked() {
return account.isAccountNonLocked();
}
@Override
public boolean isCredentialsNonExpired() {
return account.isCredentialsNonExpired();
}
@Override
public boolean isEnabled() {
return account.isEnabled();
}
@Override
public void setEnabled(final boolean enabled) {
throw new UnsupportedOperationException("You cannot change the Enabled status of the Effective User.");
}
//</editor-fold>
@Override
public String getSessionId() {
throw new UnsupportedOperationException("The Effective User has no session!");
}
@Override
public Session getSession() {
throw new UnsupportedOperationException("The Effective User has no session!");
}
//<editor-fold desc="group functions">
@Override
public String[] getGroups() {
return account.getGroups();
}
@Override
public int[] getGroupIds() {
return account.getGroupIds();
}
@Override
public boolean hasDbaRole() {
return account.hasDbaRole();
}
@Override
public String getPrimaryGroup() {
return account.getPrimaryGroup();
}
@Override
public Group getDefaultGroup() {
return account.getDefaultGroup();
}
@Override
public boolean hasGroup(final String group) {
return account.hasGroup(group);
}
@Override
public Group addGroup(final String name) throws PermissionDeniedException {
throw new UnsupportedOperationException("You cannot add a group to the Effective User");
}
@Override
public Group addGroup(final Group group) throws PermissionDeniedException {
throw new UnsupportedOperationException("You cannot add a group to the Effective User");
}
@Override
public void setPrimaryGroup(final Group group) throws PermissionDeniedException {
throw new UnsupportedOperationException("You cannot add a group to the Effective User");
}
@Override
public void setGroups(final String[] groups) {
throw new UnsupportedOperationException("You cannot set the groups of the Effective User");
}
@Override
public void remGroup(final String group) throws PermissionDeniedException {
throw new UnsupportedOperationException("You cannot remove a group from the Effective User");
}
//</editor-fold>
@Override
public void setPassword(final String passwd) {
throw new UnsupportedOperationException("The Effective User has no password!");
}
@Override
public String getPassword() {
throw new UnsupportedOperationException("The Effective User has no password!");
}
@Override
public String getDigestPassword() {
throw new UnsupportedOperationException("The Effective User has no password!");
}
@Override
public void assertCanModifyAccount(final Account user) throws PermissionDeniedException {
throw new PermissionDeniedException("The Effective User account cannot be modified");
}
@Override
public int getUserMask() {
return account.getUserMask();
}
@Override
public void setUserMask(final int umask) {
throw new UnsupportedOperationException("You cannot set the UserMask of the Effective User"); //To change body of generated methods, choose Tools | Templates.
}
//<editor-fold desc="metadata">
@Override
public String getMetadataValue(final SchemaType schemaType) {
return account.getMetadataValue(schemaType);
}
@Override
public Set<SchemaType> getMetadataKeys() {
return account.getMetadataKeys();
}
@Override
public void setMetadataValue(SchemaType schemaType, String value) {
throw new UnsupportedOperationException("You cannot modify the metadata of the Effective User");
}
@Override
public void clearMetadata() {
throw new UnsupportedOperationException("You cannot modify the metadata of the Effective User");
}
//</editor-fold>
//<editor-fold desc="persistence">
@Override
public void save() throws ConfigurationException, PermissionDeniedException {
throw new UnsupportedOperationException("You cannot perist the Effective User.");
}
@Override
public void save(final DBBroker broker) throws ConfigurationException, PermissionDeniedException {
throw new UnsupportedOperationException("You cannot perist the Effective User.");
}
@Override
public boolean isConfigured() {
return true; //the effective user does not need configuring
}
@Override
public Configuration getConfiguration() {
return null; //the effective user does not need configuring
}
//</editor-fold>
}
|
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.Filter;
import org.jdesktop.swingx.decorator.FilterPipeline;
import org.jdesktop.swingx.decorator.PatternFilter;
import org.jdesktop.swingx.decorator.ShuttleSorter;
import org.jdesktop.swingx.decorator.Sorter;
/**
* @author Jeanette Winzenburg
*/
public class JXTableIssues extends InteractiveTestCase {
public JXTableIssues() {
super("JXTableIssues");
// TODO Auto-generated constructor stub
}
/**
* Issue #155-swingx: lost setting of initial scrollBarPolicy.
*
*/
public void testConserveVerticalScrollBarPolicy() {
JXTable table = new JXTable(0, 3);
JScrollPane scrollPane1 = new JScrollPane(table);
scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JXFrame frame = new JXFrame();
frame.add(scrollPane1);
frame.setSize(500, 400);
frame.setVisible(true);
assertEquals("vertical scrollbar policy must be always",
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
scrollPane1.getVerticalScrollBarPolicy());
}
/**
* Issue #223 - part d)
*
* test if selection is cleared after receiving a dataChanged.
* Need to specify behaviour: lead/anchor of selectionModel are
* not changed in clearSelection(). So modelSelection has old
* lead which is mapped as a selection in the view (may be out-of
* range). Hmmm...
*
*/
public void testSelectionAfterDataChanged() {
DefaultTableModel ascendingModel = createAscendingModel(0, 20, 5, false);
JXTable table = new JXTable(ascendingModel);
int selectedRow = table.getRowCount() - 1;
table.setRowSelectionInterval(selectedRow, selectedRow);
// sanity
assertEquals("last row must be selected", selectedRow, table.getSelectedRow());
ascendingModel.fireTableDataChanged();
assertEquals("selection must be cleared", -1, table.getSelectedRow());
}
/**
* Issue #223 - part d)
*
* test if selection is cleared after receiving a dataChanged.
*
*/
public void testCoreTableSelectionAfterDataChanged() {
DefaultTableModel ascendingModel = createAscendingModel(0, 20, 5, false);
JTable table = new JTable(ascendingModel);
int selectedRow = table.getRowCount() - 1;
table.setRowSelectionInterval(selectedRow, selectedRow);
// sanity
assertEquals("last row must be selected", selectedRow, table.getSelectedRow());
ascendingModel.fireTableDataChanged();
assertEquals("selection must be cleared", -1, table.getSelectedRow());
}
/**
* Issue #119: Exception if sorter on last column and setting
* model with fewer columns.
*
* JW: related to #53-swingx - sorter not removed on column removed.
*
* PatternFilter does not throw - checks with modelToView if the
* column is visible and returns false match if not. Hmm...
*
*
*/
public void testFilterInChainOnModelChange() {
JXTable table = new JXTable(createAscendingModel(0, 10, 5, true));
int columnCount = table.getColumnCount();
assertEquals(5, columnCount);
Filter filter = new PatternFilter(".*", 0, columnCount - 1);
FilterPipeline pipeline = new FilterPipeline(new Filter[] {filter});
table.setFilters(pipeline);
assertEquals(10, pipeline.getOutputSize());
table.setModel(new DefaultTableModel(10, columnCount - 1));
}
/**
* Issue #119: Exception if sorter on last column and setting
* model with fewer columns.
*
*
* JW: related to #53-swingx - sorter not removed on column removed.
*
* Similar if sorter in filter pipeline -- absolutely need mutable
* pipeline!!
* Filed the latter part as Issue #55-swingx
*
*/
public void testSorterInChainOnModelChange() {
JXTable table = new JXTable(new DefaultTableModel(10, 5));
int columnCount = table.getColumnCount();
Sorter sorter = new ShuttleSorter(columnCount - 1, false);
FilterPipeline pipeline = new FilterPipeline(new Filter[] {sorter});
table.setFilters(pipeline);
table.setModel(new DefaultTableModel(10, columnCount - 1));
}
public void testComponentAdapterCoordinates() {
JXTable table = new JXTable(createModel(0, 10));
Object originalFirstRowValue = table.getValueAt(0,0);
Object originalLastRowValue = table.getValueAt(table.getRowCount() - 1, 0);
assertEquals("view row coordinate equals model row coordinate",
table.getModel().getValueAt(0, 0), originalFirstRowValue);
// sort first column - actually does not change anything order
table.setSorter(0);
// sanity asssert
assertEquals("view order must be unchanged ",
table.getValueAt(0, 0), originalFirstRowValue);
// invert sort
table.setSorter(0);
// sanity assert
assertEquals("view order must be reversed changed ",
table.getValueAt(0, 0), originalLastRowValue);
ComponentAdapter adapter = table.getComponentAdapter();
assertEquals("adapter filteredValue expects view coordinates",
table.getValueAt(0, 0), adapter.getFilteredValueAt(0, 0));
// adapter coordinates are view coordinates
adapter.row = 0;
adapter.column = 0;
assertEquals("adapter filteredValue expects view coordinates",
table.getValueAt(0, 0), adapter.getValue());
}
//-------------------- adapted jesse wilson: #223
/**
* Enhancement: modifying (= filtering by resetting the content) should keep
* selection
*
*/
public void testModifyTableContentAndSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(2, 5);
Object[] selectedObjects = new Object[] { "C", "D", "E", "F" };
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" });
Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" });
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterModify);
}
/**
* Enhancement: modifying (= filtering by resetting the content) should keep
* selection
*/
public void testModifyXTableContentAndSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.xTable.getSelectionModel().setSelectionInterval(2, 5);
Object[] selectedObjects = new Object[] { "C", "D", "E", "F" };
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" });
Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" });
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterModify);
}
/**
* Issue #223: deleting row above selection does not
* update the view selection correctly.
*
* fixed - PENDING: move to normal test (need to move special models as well)
*
*/
public void testDeleteRowAboveSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(2, 5);
compare.xTable.getSelectionModel().setSelectionInterval(2, 5);
Object[] selectedObjects = new Object[] { "C", "D", "E", "F" };
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
compare.tableModel.removeRow(0);
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
}
/**
* test: deleting row below selection - should not change
*/
public void testDeleteRowBelowSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(2, 5);
compare.xTable.getSelectionModel().setSelectionInterval(2, 5);
Object[] selectedObjects = new Object[] { "C", "D", "E", "F" };
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1);
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
}
/**
* test: deleting last row in selection - should remove last item from selection.
*/
public void testDeleteLastRowInSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(7, 8);
compare.xTable.getSelectionModel().setSelectionInterval(7, 8);
Object[] selectedObjects = new Object[] { "H", "I" };
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1);
Object[] selectedObjectsAfterDelete = new Object[] { "H" };
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterDelete);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterDelete);
}
private void assertSelection(TableModel tableModel, ListSelectionModel selectionModel, Object[] expected) {
List selected = new ArrayList();
for(int r = 0; r < tableModel.getRowCount(); r++) {
if(selectionModel.isSelectedIndex(r)) selected.add(tableModel.getValueAt(r, 0));
}
List expectedList = Arrays.asList(expected);
assertEquals("selected Objects must be as expected", expectedList, selected);
}
public void interactiveDeleteRowAboveSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(2, 5);
compare.xTable.getSelectionModel().setSelectionInterval(2, 5);
JComponent box = createContent(compare, createRowDeleteAction(0, compare.tableModel));
JFrame frame = wrapInFrame(box, "delete above selection");
frame.setVisible(true);
}
public void interactiveDeleteRowBelowSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(6, 7);
compare.xTable.getSelectionModel().setSelectionInterval(6, 7);
JComponent box = createContent(compare, createRowDeleteAction(-1, compare.tableModel));
JFrame frame = wrapInFrame(box, "delete below selection");
frame.setVisible(true);
}
public void interactiveDataChanged() {
final DefaultTableModel model = createAscendingModel(0, 10, 5, false);
JXTable xtable = new JXTable(model);
xtable.setRowSelectionInterval(0, 0);
JTable table = new JTable(model);
table.setRowSelectionInterval(0, 0);
AbstractAction action = new AbstractAction("fire dataChanged") {
public void actionPerformed(ActionEvent e) {
model.fireTableDataChanged();
}
};
JXFrame frame = wrapWithScrollingInFrame(xtable, table, "selection after data changed");
addAction(frame, action);
frame.setVisible(true);
}
private JComponent createContent(CompareTableBehaviour compare, Action action) {
JComponent box = new JPanel(new BorderLayout());
box.add(new JScrollPane(compare.table), BorderLayout.WEST);
box.add(new JScrollPane(compare.xTable), BorderLayout.EAST);
box.add(new JButton(action), BorderLayout.SOUTH);
return box;
}
private Action createRowDeleteAction(final int row, final ReallySimpleTableModel simpleTableModel) {
Action delete = new AbstractAction("DeleteRow " + ((row < 0) ? "last" : "" + row)) {
public void actionPerformed(ActionEvent e) {
int rowToDelete = row;
if (row < 0) {
rowToDelete = simpleTableModel.getRowCount() - 1;
}
if ((rowToDelete < 0) || (rowToDelete >= simpleTableModel.getRowCount())) {
return;
}
simpleTableModel.removeRow(rowToDelete);
if (simpleTableModel.getRowCount() == 0) {
setEnabled(false);
}
}
};
return delete;
}
public static class CompareTableBehaviour {
public ReallySimpleTableModel tableModel;
public JTable table;
public JXTable xTable;
public CompareTableBehaviour(Object[] model) {
tableModel = new ReallySimpleTableModel();
tableModel.setContents(model);
table = new JTable(tableModel);
xTable = new JXTable(tableModel);
table.getColumnModel().getColumn(0).setHeaderValue("JTable");
xTable.getColumnModel().getColumn(0).setHeaderValue("JXTable");
}
};
/**
* A one column table model where all the data is in an Object[] array.
*/
static class ReallySimpleTableModel extends AbstractTableModel {
private List contents = new ArrayList();
public void setContents(List contents) {
this.contents.clear();
this.contents.addAll(contents);
fireTableDataChanged();
}
public void setContents(Object[] contents) {
setContents(Arrays.asList(contents));
}
public void removeRow(int row) {
contents.remove(row);
fireTableRowsDeleted(row, row);
}
public int getRowCount() {
return contents.size();
}
public int getColumnCount() {
return 1;
}
public Object getValueAt(int row, int column) {
if(column != 0) throw new IllegalArgumentException();
return contents.get(row);
}
}
/**
* returns a tableModel with count rows filled with
* ascending integers in first column
* starting from startRow.
* @param startRow the value of the first row
* @param rowCount the number of rows
* @return
*/
private DefaultTableModel createAscendingModel(int startRow, final int rowCount,
final int columnCount, boolean fillLast) {
DefaultTableModel model = new DefaultTableModel(rowCount, columnCount) {
public Class getColumnClass(int column) {
Object value = rowCount > 0 ? getValueAt(0, column) : null;
return value != null ? value.getClass() : super.getColumnClass(column);
}
};
int filledColumn = fillLast ? columnCount - 1 : 0;
for (int i = 0; i < model.getRowCount(); i++) {
model.setValueAt(new Integer(startRow++), i, filledColumn);
}
return model;
}
private DefaultTableModel createModel(int startRow, int count) {
DefaultTableModel model = new DefaultTableModel(count, 5);
for (int i = 0; i < model.getRowCount(); i++) {
model.setValueAt(new Integer(startRow++), i, 0);
}
return model;
}
/**
* JW: Still needed? moved to main testCase?
*
*/
public void testNewRendererInstance() {
JXTable table = new JXTable();
TableCellRenderer newRenderer = table.getNewDefaultRenderer(Boolean.class);
TableCellRenderer sharedRenderer = table.getDefaultRenderer(Boolean.class);
assertNotNull(newRenderer);
assertNotSame("new renderer must be different from shared", sharedRenderer, newRenderer);
assertNotSame("new renderer must be different from object renderer",
table.getDefaultRenderer(Object.class), newRenderer);
}
/**
* Issue #??: JXTable pattern search differs from
* PatternHighlighter/Filter.
*
* Fixing the issue (respect the pattern as is by calling
* pattern.matcher().matches instead of the find()) must
* make sure that the search methods taking the string
* include wildcards.
*
* Note: this method passes as long as the issue is not
* fixed!
*/
public void testWildCardInSearchByString() {
JXTable table = new JXTable(createModel(0, 11));
int row = 1;
String lastName = table.getValueAt(row, 0).toString();
int found = table.getSearchable().search(lastName, -1);
assertEquals("found must be equal to row", row, found);
found = table.getSearchable().search(lastName, found);
assertEquals("search must succeed", 10, found);
}
public static void main(String args[]) {
JXTableIssues test = new JXTableIssues();
try {
test.runInteractiveTests();
// test.runInteractiveTests("interactive.*Siz.*");
// test.runInteractiveTests("interactive.*Render.*");
// test.runInteractiveTests("interactive.*Toggle.*");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
}
|
package org.csstudio.channelfinder.views;
import gov.bnl.channelfinder.api.Channel;
import gov.bnl.channelfinder.api.ChannelUtil;
import java.util.ArrayList;
import java.util.Collection;
import org.csstudio.channelfinder.util.FindChannels;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.part.ViewPart;
import com.swtdesigner.TableViewerColumnSorter;
public class ChannelFinderView extends ViewPart {
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "org.csstudio.channelfinder.views.ChannelfinderView";
private static int instance;
private Text text;
private Button search;
private GridLayout layout;
// private Collection<ICSSChannel> channelsList = new
private Table table;
private TableViewer tableViewer;
// Simple Model
Collection<Channel> channels = new ArrayList<Channel>();
/*
* The content provider class is responsible for providing objects to the
* view. It can wrap existing objects in adapters or simply return objects
* as-is. These objects may be sensitive to the current input of the view,
* or ignore it and always show the same content (like Task List, for
* example).
*/
/**
* The constructor.
*/
public ChannelFinderView() {
}
/**
* This is a callback that will allow us to create the viewer and initialize
* it.
*/
public void createPartControl(Composite parent) {
createGUI(parent);
tableViewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION
| SWT.MULTI | SWT.VIRTUAL);
table = tableViewer.getTable();
table.setLinesVisible(true);
table.setHeaderVisible(true);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
TableViewerColumn channelNameColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
channelNameColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
cell.setText(((Channel) cell.getElement()).getName());
}
});
new TableViewerColumnSorter(channelNameColumn) {
@Override
protected Object getValue(Object o) {
return ((Channel) o).getName();
}
};
TableColumn tblclmnChannelName = channelNameColumn.getColumn();
tblclmnChannelName.setWidth(100);
tblclmnChannelName.setText("Channel Name");
TableViewerColumn channelOwnerColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
channelOwnerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
cell.setText(((Channel) cell.getElement()).getOwner());
}
});
new TableViewerColumnSorter(channelOwnerColumn) {
@Override
protected Object getValue(Object o) {
return ((Channel) o).getOwner();
}
};
TableColumn tblclmnOwner = channelOwnerColumn.getColumn();
tblclmnOwner.setWidth(100);
tblclmnOwner.setText("Owner");
tableViewer.setContentProvider(new ChannelContentProvider());
// tableViewer.setLabelProvider(new ChannelLabelProvider());
// Add this table as a selection provider
getSite().setSelectionProvider(tableViewer);
hookContextMenu();
}
/** @return a new view instance */
public static String createNewInstance() {
++instance;
return Integer.toString(instance);
}
private void createGUI(Composite parent) {
layout = new GridLayout(2, false);
parent.setLayout(layout);
text = new Text(parent, SWT.SINGLE | SWT.BORDER | SWT.SEARCH);
text.setToolTipText("space seperated search criterias, patterns may include * and ? wildcards\r\nchannelNamePatter\r\npropertyName=propertyValuePattern1,propertyValuePattern2\r\nTags=tagNamePattern\r\n");
GridData gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
text.setLayoutData(gd);
search = new Button(parent, SWT.PUSH);
search.setText("Search");
search.setToolTipText("search for channels");
search.setEnabled(false);
GridData viewerGD = new GridData();
viewerGD.horizontalSpan = 2;
viewerGD.grabExcessHorizontalSpace = true;
viewerGD.grabExcessVerticalSpace = true;
viewerGD.horizontalAlignment = SWT.FILL;
viewerGD.verticalAlignment = SWT.FILL;
int col = 0;
col++;
text.addSelectionListener(new SelectionAdapter() {
public void widgetDefaultSelected(SelectionEvent e) {
if (e.detail == SWT.CANCEL) {
System.out.println("Search cancelled");
} else {
System.out.println("Searching for: " + text.getText());
search(text.getText());
}
}
});
text.addListener(SWT.KeyUp, new Listener() {
@Override
public void handleEvent(Event event) {
if (text.getText().toCharArray().length > 0) {
search.setEnabled(true);
} else {
search.setEnabled(false);
}
}
});
search.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
search(text.getText());
}
});
}
private void search(String text) {
if (text.equalsIgnoreCase("*")) {
if (!MessageDialog.openConfirm(getSite().getShell(),
"Confirm Search",
"Are you sure you want to search for all channels?"))
return;
}
Job job = new FindChannels("search", text, this);
job.schedule();
}
private void hookContextMenu() {
MenuManager menuManager = new MenuManager();
menuManager.setRemoveAllWhenShown(true);
// Set the MenuManager
fillContextMenu(menuManager);
}
private void fillContextMenu(IMenuManager manager) {
// Other plug-ins can contribute there actions here
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
tableViewer.getControl().setFocus();
}
public synchronized void updateList(Collection<Channel> newChannels) {
// Clear the channel list;
channels.clear();
channels.addAll(newChannels);
tableViewer.setInput(channels.toArray());
tableViewer.setItemCount(channels.size());
// Remove all old columns
// TODO add the additional columns in the correct sorted order.
while (tableViewer.getTable().getColumnCount() > 2) {
tableViewer.getTable().getColumn(table.getColumnCount() - 1)
.dispose();
}
// Add a new column for each property
for (String propertyName : ChannelUtil.getPropertyNames(newChannels)) {
// Property Column
TableViewerColumn channelPropertyColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
channelPropertyColumn
.setLabelProvider(new PropertyCellLabelProvider(
propertyName));
new TableViewerChannelPropertySorter(channelPropertyColumn,
propertyName);
TableColumn tblclmnNumericprop = channelPropertyColumn.getColumn();
// tcl_composite.setColumnData(tblclmnNumericprop, new
// ColumnPixelData(
// 100, true, true));
tblclmnNumericprop.setText(propertyName);
tblclmnNumericprop.setWidth(100);
}
// Add a new column for each Tag
for (String tagName : ChannelUtil.getAllTagNames(newChannels)) {
// Tag Column
TableViewerColumn channelTagColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
channelTagColumn
.setLabelProvider(new TagCellLabelProvider(tagName));
new TableViewerChannelTagSorter(channelTagColumn, tagName);
TableColumn tblclmnNumericprop = channelTagColumn.getColumn();
// tcl_composite.setColumnData(tblclmnNumericprop, new
// ColumnPixelData(
// 100, true, true));
tblclmnNumericprop.setText(tagName);
tblclmnNumericprop.setWidth(100);
}
tableViewer.refresh();
}
}
|
package org.ihtsdo.otf.rest.client.ims;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IMSRestClient {
private static final String DOT_SEPARATOR = ".";
private static final String IMS_PATTERN = "ims-ihtsdo=";
private static final String SEMICOLON_SEPARATOR = ";";
private static final String SET_COOKIE = "Set-Cookie";
private final RestTemplate restTemplate;
private final String imsUrl;
private final ObjectMapper objectMapper;
public IMSRestClient(String imsUrl) {
this.imsUrl = imsUrl;
this.restTemplate = new RestTemplate();
objectMapper = new ObjectMapper();
}
/**
* A REST endpoint to login and get token for an user.
* @param username
* @param password
* @return Token - The token of login user
* @throws URISyntaxException
* @throws MalformedURLException
* @throws IOException
*/
public String login(String username, String password) throws URISyntaxException, IOException {
Map<String, String> bodyMap = new HashMap<>();
bodyMap.put("login", username);
bodyMap.put("password", password);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept", "application/json, text/plain, */*");
HttpEntity<String> request = new HttpEntity<>(objectMapper.writeValueAsString(bodyMap), headers);
ResponseEntity<String> model = restTemplate.exchange(imsUrl + "/authenticate", HttpMethod.POST, request, String.class);
return getAuthenticationToken(model.getHeaders());
}
public String loginForceNewSession(String username, String password) throws IOException, URISyntaxException {
String token = login(username, password);
logout(token);
return login(username, password);
}
private void logout(String token) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.COOKIE, token);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(headers);
restTemplate.exchange(imsUrl + "/account/logout", HttpMethod.POST, request, String.class);
}
private String getAuthenticationToken(HttpHeaders responseHeader) throws URISyntaxException {
String cookies = responseHeader.get(SET_COOKIE).toString();
String[] strArr = cookies.substring(1, cookies.length() - 1).split(SEMICOLON_SEPARATOR);
Pattern r = Pattern.compile(IMS_PATTERN);
List<String> tokens = new ArrayList<>();
for (String str : strArr) {
Matcher m = r.matcher(str);
if (m.find()) {
tokens.add(str);
}
}
// find corresponding token with IMS environment
URI uri = new URI(imsUrl);
String imsHost = uri.getHost();
String imsEnvironment = imsHost.substring(0, imsHost.indexOf(DOT_SEPARATOR));
for (String token : tokens) {
if (token.contains(imsEnvironment)) {
return token;
}
}
return "";
}
}
|
package org.exist.xquery.value;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.Collator;
import java.util.regex.Pattern;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.exist.xquery.Constants;
import org.exist.xquery.XPathException;
import org.exist.util.FastStringBuffer;
/**
* @author wolf
*/
public class DecimalValue extends NumericValue {
private static final BigDecimal ZERO_BIGDECIMAL = new BigDecimal("0");
//Copied from Saxon 8.6.1
private static final int DIVIDE_PRECISION = 18;
//Copied from Saxon 8.7
private static final Pattern decimalPattern = Pattern.compile("(\\-|\\+)?((\\.[0-9]+)|([0-9]+(\\.[0-9]*)?))");
//Copied from Saxon 8.8
private static boolean stripTrailingZerosMethodUnavailable = false;
private static Method stripTrailingZerosMethod = null;
private static final Object[] EMPTY_OBJECT_ARRAY = {};
public static final BigInteger BIG_INTEGER_TEN = BigInteger.valueOf(10);
BigDecimal value;
public DecimalValue(BigDecimal decimal) {
this.value = stripTrailingZeros(decimal);
}
public DecimalValue(String str) throws XPathException {
str = StringValue.trimWhitespace(str);
try {
if (!decimalPattern.matcher(str).matches()) {
throw new XPathException("FORG0001: cannot construct " + Type.getTypeName(this.getItemType()) +
" from \"" + str + "\"");
}
value = stripTrailingZeros(new BigDecimal(str));
} catch (NumberFormatException e) {
throw new XPathException("FORG0001: cannot construct " + Type.getTypeName(this.getItemType()) +
" from \"" + getStringValue() + "\"");
}
}
public DecimalValue(double val) {
value = stripTrailingZeros(new BigDecimal(val));
}
/* (non-Javadoc)
* @see org.exist.xquery.value.AtomicValue#getType()
*/
public int getType() {
return Type.DECIMAL;
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#getStringValue()
*/
public String getStringValue() throws XPathException {
/*
String s = value.toString();
while (s.length() > 0 && s.indexOf('.') != Constants.STRING_NOT_FOUND &&
s.charAt(s.length() - 1) == '0') {
s = s.substring(0, s.length() - 1);
}
if (s.length() > 0 && s.charAt(s.length() - 1 ) == '.')
s = s.substring(0, s.length() - 1);
return s;
*/
//Copied from Saxon 8.8
// Can't use the plain BigDecimal#toString() under JDK 1.5 because this produces values like "1E-5".
// JDK 1.5 offers BigDecimal#toPlainString() which might do the job directly
int scale = value.scale();
if (scale == 0) {
return value.toString();
} else if (scale < 0) {
String s = value.abs().unscaledValue().toString();
FastStringBuffer sb = new FastStringBuffer(s.length() + (-scale) + 2);
if (value.signum() < 0) {
sb.append('-');
}
sb.append(s);
//Provisional hack : 10.0 mod 10.0 to trigger the bug
if (!"0".equals(s)){
for (int i=0; i<(-scale); i++) {
sb.append('0');
}
}
return sb.toString();
} else {
String s = value.abs().unscaledValue().toString();
if (s.equals("0")) {
return s;
}
int len = s.length();
FastStringBuffer sb = new FastStringBuffer(len+1);
if (value.signum() < 0) {
sb.append('-');
}
if (scale >= len) {
sb.append("0.");
for (int i=len; i<scale; i++) {
sb.append('0');
}
sb.append(s);
} else {
sb.append(s.substring(0, len-scale));
sb.append('.');
sb.append(s.substring(len-scale));
}
return sb.toString();
}
//End of copy
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#convertTo(int)
*/
public AtomicValue convertTo(int requiredType) throws XPathException {
switch (requiredType) {
case Type.ATOMIC :
case Type.ITEM :
case Type.NUMBER :
case Type.DECIMAL :
return this;
case Type.DOUBLE :
return new DoubleValue(value.doubleValue());
case Type.FLOAT :
return new FloatValue(value.floatValue());
case Type.STRING :
return new StringValue(getStringValue());
case Type.UNTYPED_ATOMIC :
return new UntypedAtomicValue(getStringValue());
case Type.INTEGER :
case Type.NON_POSITIVE_INTEGER :
case Type.NEGATIVE_INTEGER :
case Type.LONG :
case Type.INT :
case Type.SHORT :
case Type.BYTE :
case Type.NON_NEGATIVE_INTEGER :
case Type.UNSIGNED_LONG :
case Type.UNSIGNED_INT :
case Type.UNSIGNED_SHORT :
case Type.UNSIGNED_BYTE :
case Type.POSITIVE_INTEGER :
return new IntegerValue(value.longValue(), requiredType);
case Type.BOOLEAN :
return value.signum() == 0 ? BooleanValue.FALSE : BooleanValue.TRUE;
default :
throw new XPathException(
"cannot convert double value '"
+ value
+ "' into "
+ Type.getTypeName(requiredType));
}
}
/* (non-Javadoc)
* @see org.exist.xquery.value.AtomicValue#effectiveBooleanValue()
*/
public boolean effectiveBooleanValue() throws XPathException {
return value.signum() != 0;
}
public boolean isNaN() {
return false;
}
public boolean isInfinite() {
return false;
}
public boolean isZero() {
return value.compareTo(ZERO_BIGDECIMAL) == Constants.EQUAL;
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#negate()
*/
public NumericValue negate() throws XPathException {
return new DecimalValue(value.negate());
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#ceiling()
*/
public NumericValue ceiling() throws XPathException {
return new DecimalValue(value.setScale(0, BigDecimal.ROUND_CEILING));
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#floor()
*/
public NumericValue floor() throws XPathException {
return new DecimalValue(value.setScale(0, BigDecimal.ROUND_FLOOR));
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#round()
*/
public NumericValue round() throws XPathException {
switch (value.signum()) {
case -1 :
return new DecimalValue(value.setScale(0, BigDecimal.ROUND_HALF_DOWN));
case 0 :
return this;
case 1 :
return new DecimalValue(value.setScale(0, BigDecimal.ROUND_HALF_UP));
default :
return this;
}
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#round(org.exist.xquery.value.IntegerValue)
*/
public NumericValue round(IntegerValue precision) throws XPathException {
int pre = precision.getInt();
if ( pre >= 0 )
return new DecimalValue(value.setScale(pre, BigDecimal.ROUND_HALF_EVEN));
else
return new DecimalValue(
value.movePointRight(pre).
setScale(0, BigDecimal.ROUND_HALF_EVEN).
movePointLeft(pre));
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#minus(org.exist.xquery.value.NumericValue)
*/
public ComputableValue minus(ComputableValue other) throws XPathException {
switch(other.getType()) {
case Type.DECIMAL:
return new DecimalValue(value.subtract(((DecimalValue) other).value));
case Type.INTEGER:
return minus((ComputableValue) other.convertTo(getType()));
default:
return ((ComputableValue) convertTo(other.getType())).minus(other);
}
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#plus(org.exist.xquery.value.NumericValue)
*/
public ComputableValue plus(ComputableValue other) throws XPathException {
switch(other.getType()) {
case Type.DECIMAL:
return new DecimalValue(value.add(((DecimalValue) other).value));
case Type.INTEGER:
return plus((ComputableValue) other.convertTo(getType()));
default:
return ((ComputableValue) convertTo(other.getType())).plus(other);
}
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#mult(org.exist.xquery.value.NumericValue)
*/
public ComputableValue mult(ComputableValue other) throws XPathException {
switch(other.getType()) {
case Type.DECIMAL:
return new DecimalValue(value.multiply(((DecimalValue) other).value));
case Type.INTEGER:
return mult((ComputableValue) other.convertTo(getType()));
case Type.DAY_TIME_DURATION:
case Type.YEAR_MONTH_DURATION:
return other.mult(this);
default:
return ((ComputableValue) convertTo(other.getType())).mult(other);
}
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#div(org.exist.xquery.value.NumericValue)
*/
public ComputableValue div(ComputableValue other) throws XPathException {
switch(other.getType()) {
//case Type.DECIMAL:
//return new DecimalValue(value.divide(((DecimalValue) other).value, BigDecimal.ROUND_HALF_UP));
case Type.INTEGER:
return div((ComputableValue) other.convertTo(getType()));
default:
if (!(other instanceof DecimalValue)) {
final ComputableValue n = (ComputableValue)this.convertTo(other.getType());
return ((ComputableValue)n).div(other);
}
//Copied from Saxon 8.6.1
int scale = Math.max(DIVIDE_PRECISION, Math.max(value.scale(), ((DecimalValue)other).value.scale()));
BigDecimal result = value.divide(((DecimalValue)other).value, scale, BigDecimal.ROUND_HALF_DOWN);
return new DecimalValue(result);
//End of copy
}
}
public IntegerValue idiv(NumericValue other) throws XPathException {
DecimalValue dv = (DecimalValue)other.convertTo(Type.DECIMAL);
if (dv.value.signum() == 0)
throw new XPathException("FOAR0001: division by zero");
BigInteger quot = value.divide(dv.value, 0, BigDecimal.ROUND_DOWN).toBigInteger();
return new IntegerValue(quot);
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#mod(org.exist.xquery.value.NumericValue)
*/
public NumericValue mod(NumericValue other) throws XPathException {
if (other.getType() == Type.DECIMAL) {
BigDecimal quotient = value.divide(((DecimalValue)other).value, 0, BigDecimal.ROUND_DOWN);
BigDecimal remainder = value.subtract(quotient.setScale(0, BigDecimal.ROUND_DOWN).multiply(((DecimalValue) other).value));
return new DecimalValue(remainder);
} else
return ((NumericValue) convertTo(other.getType())).mod(other);
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#abs(org.exist.xquery.value.NumericValue)
*/
public NumericValue abs() throws XPathException {
return new DecimalValue(value.abs());
}
/* (non-Javadoc)
* @see org.exist.xquery.value.NumericValue#max(org.exist.xquery.value.AtomicValue)
*/
public AtomicValue max(Collator collator, AtomicValue other) throws XPathException {
if (other.getType() == Type.DECIMAL) {
return new DecimalValue(value.max(((DecimalValue) other).value));
} else
return new DecimalValue(
value.max(((DecimalValue) other.convertTo(Type.DECIMAL)).value));
}
public AtomicValue min(Collator collator, AtomicValue other) throws XPathException {
if (other.getType() == Type.DECIMAL) {
return new DecimalValue(value.min(((DecimalValue) other).value));
} else {
return new DecimalValue(
value.min(((DecimalValue) other.convertTo(Type.DECIMAL)).value));
}
}
public int compareTo(Object o) {
final AtomicValue other = (AtomicValue)o;
if(Type.subTypeOf(other.getType(), Type.DECIMAL)) {
DecimalValue otherAsDecimal = null;
try {
otherAsDecimal = (DecimalValue)other.convertTo(Type.DECIMAL);
} catch (XPathException e) {
//TODO : is this relevant ?
return Constants.INFERIOR;
}
return value.compareTo(otherAsDecimal.value);
} else
return getType() < other.getType() ? Constants.INFERIOR : Constants.SUPERIOR;
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Item#conversionPreference(java.lang.Class)
*/
public int conversionPreference(Class javaClass) {
if (javaClass.isAssignableFrom(DecimalValue.class))
return 0;
if (javaClass == BigDecimal.class)
return 1;
if (javaClass == Long.class || javaClass == long.class)
return 4;
if (javaClass == Integer.class || javaClass == int.class)
return 5;
if (javaClass == Short.class || javaClass == short.class)
return 6;
if (javaClass == Byte.class || javaClass == byte.class)
return 7;
if (javaClass == Double.class || javaClass == double.class)
return 2;
if (javaClass == Float.class || javaClass == float.class)
return 3;
if (javaClass == String.class)
return 8;
if (javaClass == Boolean.class || javaClass == boolean.class)
return 9;
if (javaClass == Object.class)
return 20;
return Integer.MAX_VALUE;
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Item#toJavaObject(java.lang.Class)
*/
public Object toJavaObject(Class target) throws XPathException {
if (target.isAssignableFrom(DecimalValue.class))
return this;
else if(target == BigDecimal.class)
return value;
else if (target == Double.class || target == double.class)
return new Double(value.doubleValue());
else if (target == Float.class || target == float.class)
return new Float(value.floatValue());
else if (target == Long.class || target == long.class) {
return new Long( ((IntegerValue) convertTo(Type.LONG)).getValue() );
} else if (target == Integer.class || target == int.class) {
IntegerValue v = (IntegerValue) convertTo(Type.INT);
return new Integer((int) v.getValue());
} else if (target == Short.class || target == short.class) {
IntegerValue v = (IntegerValue) convertTo(Type.SHORT);
return new Short((short) v.getValue());
} else if (target == Byte.class || target == byte.class) {
IntegerValue v = (IntegerValue) convertTo(Type.BYTE);
return new Byte((byte) v.getValue());
} else if (target == String.class)
return getStringValue();
else if (target == Boolean.class)
return Boolean.valueOf(effectiveBooleanValue());
throw new XPathException(
"cannot convert value of type "
+ Type.getTypeName(getType())
+ " to Java object of type "
+ target.getName());
}
//Copied from Saxon 8.8
/**
* Remove insignificant trailing zeros (the Java BigDecimal class retains trailing zeros,
* but the XPath 2.0 xs:decimal type does not). The BigDecimal#stripTrailingZeros() method
* was introduced in JDK 1.5: we use it if available, and simulate it if not.
*/
private static BigDecimal stripTrailingZeros(BigDecimal value) {
if (stripTrailingZerosMethodUnavailable) {
return stripTrailingZerosFallback(value);
}
try {
if (stripTrailingZerosMethod == null) {
Class[] argTypes = {};
stripTrailingZerosMethod = BigDecimal.class.getMethod("stripTrailingZeros", argTypes);
}
Object result = stripTrailingZerosMethod.invoke(value, EMPTY_OBJECT_ARRAY);
return (BigDecimal)result;
} catch (NoSuchMethodException e) {
stripTrailingZerosMethodUnavailable = true;
return stripTrailingZerosFallback(value);
} catch (IllegalAccessException e) {
stripTrailingZerosMethodUnavailable = true;
return stripTrailingZerosFallback(value);
} catch (InvocationTargetException e) {
stripTrailingZerosMethodUnavailable = true;
return stripTrailingZerosFallback(value);
}
}
private static BigDecimal stripTrailingZerosFallback(BigDecimal value) {
// The code below differs from JDK 1.5 stripTrailingZeros in that it does not remove trailing zeros
// from integers, for example 1000 is not changed to 1E3.
int scale = value.scale();
if (scale > 0) {
BigInteger i = value.unscaledValue();
while (true) {
BigInteger[] dr = i.divideAndRemainder(BIG_INTEGER_TEN);
if (dr[1].equals(BigInteger.ZERO)) {
i = dr[0];
scale
if (scale==0) {
break;
}
} else {
break;
}
}
if (scale != value.scale()) {
value = new BigDecimal(i, scale);
}
}
return value;
}
//End of copy
}
|
package org.csstudio.opibuilder.widgets.editparts;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DecimalFormat;
import java.text.ParseException;
import org.csstudio.opibuilder.OPIBuilderPlugin;
import org.csstudio.opibuilder.editparts.ExecutionMode;
import org.csstudio.opibuilder.model.AbstractContainerModel;
import org.csstudio.opibuilder.model.AbstractPVWidgetModel;
import org.csstudio.opibuilder.properties.IWidgetPropertyChangeHandler;
import org.csstudio.opibuilder.scriptUtil.GUIUtil;
import org.csstudio.opibuilder.util.ConsoleService;
import org.csstudio.opibuilder.widgets.model.ActionButtonModel.Style;
import org.csstudio.opibuilder.widgets.model.LabelModel;
import org.csstudio.opibuilder.widgets.model.TextInputModel;
import org.csstudio.simplepv.FormatEnum;
import org.csstudio.simplepv.IPV;
import org.csstudio.simplepv.IPVListener;
import org.csstudio.simplepv.VTypeHelper;
import org.csstudio.swt.widgets.figures.TextFigure;
import org.csstudio.swt.widgets.figures.TextInputFigure;
import org.csstudio.swt.widgets.figures.TextInputFigure.SelectorType;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.DragTracker;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.tools.SelectEditPartTracker;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Display;
import org.epics.vtype.Array;
import org.epics.vtype.Scalar;
import org.epics.vtype.VEnum;
import org.epics.vtype.VNumberArray;
import org.epics.vtype.VType;
/**
* The editpart for text input widget.)
*
* @author Xihui Chen
*
*/
public class TextInputEditpart extends TextUpdateEditPart {
private static final char SPACE = ' '; //$NON-NLS-1$
private static DecimalFormat DECIMAL_FORMAT = new DecimalFormat();
private IPVListener pvLoadLimitsListener;
private org.epics.vtype.Display meta = null;
private ITextInputEditPartDelegate delegate;
@Override
public TextInputModel getWidgetModel() {
return (TextInputModel) getModel();
}
@Override
protected IFigure doCreateFigure() {
initFields();
if(shouldBeTextInputFigure()){
TextInputFigure textInputFigure = (TextInputFigure) createTextFigure();
initTextFigure(textInputFigure);
delegate = new Draw2DTextInputEditpartDelegate(
this, getWidgetModel(), textInputFigure);
}else{
delegate = new NativeTextEditpartDelegate(this, getWidgetModel());
}
getPVWidgetEditpartDelegate().setUpdateSuppressTime(-1);
updatePropSheet();
return delegate.doCreateFigure();
}
/**
* @return true if it should use Draw2D {@link TextInputFigure}.
*/
private boolean shouldBeTextInputFigure(){
TextInputModel model = getWidgetModel();
if(model.getStyle() == Style.NATIVE)
return false;
// Always use native text in webopi if it doesn't need TextInputFigure functions
if (OPIBuilderPlugin.isRAP() && !model.isTransparent()
&& model.getRotationAngle() == 0
&& model.getSelectorType() == SelectorType.NONE){
model.setPropertyValue(TextInputModel.PROP_SHOW_NATIVE_BORDER, false);
return false;
}
return true;
}
@Override
protected TextFigure createTextFigure() {
return new TextInputFigure(getExecutionMode() == ExecutionMode.RUN_MODE);
}
@Override
protected void createEditPolicies() {
super.createEditPolicies();
delegate.createEditPolicies();
}
@Override
public void activate() {
markAsControlPV(AbstractPVWidgetModel.PROP_PVNAME,
AbstractPVWidgetModel.PROP_PVVALUE);
super.activate();
}
@Override
protected void doActivate() {
super.doActivate();
registerLoadLimitsListener();
}
private void registerLoadLimitsListener() {
if (getExecutionMode() == ExecutionMode.RUN_MODE) {
final TextInputModel model = getWidgetModel();
if (model.isLimitsFromPV()) {
IPV pv = getPV(AbstractPVWidgetModel.PROP_PVNAME);
if (pv != null) {
if (pvLoadLimitsListener == null)
pvLoadLimitsListener = new IPVListener.Stub() {
public void valueChanged(IPV pv) {
VType value = pv.getValue();
if (value != null
&& VTypeHelper.getDisplayInfo(value)!=null) {
org.epics.vtype.Display new_meta =VTypeHelper.getDisplayInfo(value);
if (meta == null || !meta.equals(new_meta)) {
meta = new_meta;
model.setPropertyValue(
TextInputModel.PROP_MAX,
meta.getUpperDisplayLimit());
model.setPropertyValue(
TextInputModel.PROP_MIN,
meta.getLowerDisplayLimit());
}
}
}
};
pv.addListener(pvLoadLimitsListener);
}
}
}
}
/**
* @param text
*/
public void outputPVValue(String text) {
if(!getWidgetModel().getConfirmMessage().isEmpty())
if(!GUIUtil.openConfirmDialog("PV Name: " + getPVName() +
"\nNew Value: "+ text+ "\n\n"+
getWidgetModel().getConfirmMessage()))
return;
try {
Object result;
if(getWidgetModel().getFormat() != FormatEnum.STRING
&& text.trim().indexOf(SPACE)!=-1){
result = parseStringArray(text);
}else
result = parseString(text);
setPVValue(AbstractPVWidgetModel.PROP_PVNAME, result);
} catch (Exception e) {
String msg = NLS
.bind("Failed to write value to PV {0} from widget {1}.\nIllegal input : {2} \n",
new String[] {
getPVName(),
getWidgetModel().getName(),
text })
+ e.toString();
ConsoleService.getInstance().writeError(msg);
}
}
@Override
protected void registerPropertyChangeHandlers() {
super.registerPropertyChangeHandlers();
if (getExecutionMode() == ExecutionMode.RUN_MODE) {
removeAllPropertyChangeHandlers(LabelModel.PROP_TEXT);
IWidgetPropertyChangeHandler handler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(Object oldValue, Object newValue,
final IFigure figure) {
String text = (String) newValue;
if(getPV() == null){
setFigureText(text);
if(getWidgetModel().isAutoSize()){
Display.getCurrent().timerExec(10, new Runnable() {
public void run() {
performAutoSize();
}
});
}
}
//Output pv value even if pv name is empty, so setPVValuelistener can be triggered.
outputPVValue(text);
return false;
}
};
setPropertyChangeHandler(LabelModel.PROP_TEXT, handler);
}
IWidgetPropertyChangeHandler pvNameHandler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(Object oldValue, Object newValue,
IFigure figure) {
registerLoadLimitsListener();
return false;
}
};
setPropertyChangeHandler(AbstractPVWidgetModel.PROP_PVNAME,
pvNameHandler);
PropertyChangeListener updatePropSheetListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent arg0) {
updatePropSheet();
}
};
getWidgetModel().getProperty(TextInputModel.PROP_LIMITS_FROM_PV)
.addPropertyChangeListener(updatePropSheetListener);
getWidgetModel().getProperty(TextInputModel.PROP_SELECTOR_TYPE)
.addPropertyChangeListener(updatePropSheetListener);
PropertyChangeListener reCreateWidgetListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
reCreateWidget();
}
};
getWidgetModel().getProperty(TextInputModel.PROP_STYLE)
.addPropertyChangeListener(reCreateWidgetListener);
delegate.registerPropertyChangeHandlers();
}
private void reCreateWidget(){
TextInputModel model = getWidgetModel();
AbstractContainerModel parent = model.getParent();
parent.removeChild(model);
parent.addChild(model);
parent.selectWidget(model, true);
}
public DragTracker getDragTracker(Request request) {
if (getExecutionMode() == ExecutionMode.RUN_MODE &&
delegate instanceof Draw2DTextInputEditpartDelegate) {
return new SelectEditPartTracker(this) {
@Override
protected boolean handleButtonUp(int button) {
if (button == 1) {
//make widget in edit mode by single click
performOpen();
}
return super.handleButtonUp(button);
}
};
}else
return super.getDragTracker(request);
}
@Override
public void performRequest(Request request) {
if (getFigure().isEnabled()
&&((request.getType() == RequestConstants.REQ_DIRECT_EDIT &&
getExecutionMode() != ExecutionMode.RUN_MODE)||
request.getType() == RequestConstants.REQ_OPEN))
performDirectEdit();
}
protected void performDirectEdit() {
new TextEditManager(this, new LabelCellEditorLocator(
(Figure) getFigure()), getWidgetModel().isMultilineInput()).show();
}
/**If the text has spaces in the string and the PV is numeric array type,
* it will return an array of numeric values.
* @param text
* @return
* @throws ParseException
*/
private Object parseStringArray(final String text) throws ParseException{
String[] texts = text.split(" +"); //$NON-NLS-1$
VType pvValue = getPVValue(AbstractPVWidgetModel.PROP_PVNAME);
if(pvValue instanceof VNumberArray){
double[] result = new double[texts.length];
for (int i = 0; i < texts.length; i++) {
Object o = parseString(texts[i]);
if (o instanceof Number)
result[i] = ((Number) o).doubleValue();
else
throw new ParseException(texts[i] + " cannot be parsed as a number!", i);
}
return result;
}
return parseString(text);
}
/**
* Parse string to a value according PV value type and format
*
* @param text
* @return value
* @throws ParseException
*/
private Object parseString(final String text) throws ParseException {
VType pvValue = getPVValue(AbstractPVWidgetModel.PROP_PVNAME);
FormatEnum formatEnum = getWidgetModel().getFormat();
if(pvValue == null)
return text;
return parseStringForPVManagerPV(formatEnum, text, pvValue);
}
private Object parseStringForPVManagerPV(FormatEnum formatEnum,
final String text, VType pvValue) throws ParseException {
if(pvValue instanceof Scalar){
Object value = ((Scalar)pvValue).getValue();
if (value instanceof Number) {
switch (formatEnum) {
case HEX:
case HEX64:
return parseHEX(text, true);
case STRING:
return text;
case DECIMAL:
case COMPACT:
case EXP:
return parseDouble(text,true);
case DEFAULT:
default:
try {
return parseDouble(text, true);
} catch (ParseException e) {
return text;
}
}
}else if(value instanceof String){
if(pvValue instanceof VEnum){
switch (formatEnum) {
case HEX:
case HEX64:
return parseHEX(text, true);
case STRING:
return text;
case DECIMAL:
case EXP:
case COMPACT:
return parseDouble(text, true);
case DEFAULT:
default:
try {
return parseDouble(text, true);
} catch (ParseException e) {
return text;
}
}
}else
return text;
}
}else if(pvValue instanceof Array){
if(pvValue instanceof VNumberArray){
switch (formatEnum) {
case HEX:
case HEX64:
return parseHEX(text, true);
case STRING:
return parseCharArray(text, ((VNumberArray)pvValue).getData().size());
case DECIMAL:
case EXP:
case COMPACT:
return parseDouble(text, true);
case DEFAULT:
default:
try {
return parseDouble(text, true);
} catch (ParseException e) {
return text;
}
}
}else {
return text;
}
}
return text;
}
private int[] parseCharArray(final String text, int currentLength) {
int[] iString = new int[currentLength];
char[] textChars = text.toCharArray();
for (int ii = 0; ii < text.length(); ii++) {
iString[ii] = Integer.valueOf(textChars[ii]);
}
for (int ii = text.length(); ii < currentLength; ii++) {
iString[ii] = 0;
}
return iString;
}
private double parseDouble(final String text, final boolean coerce)
throws ParseException {
if(text.contains("\n")&&!text.endsWith("\n"))
throw new ParseException(NLS.bind("{0} cannot be parsed to double", text),text.indexOf("\n"));
double value = DECIMAL_FORMAT.parse(text.replace('e', 'E')).doubleValue(); //$NON-NLS-1$ //$NON-NLS-2$
if (coerce) {
double min = getWidgetModel().getMinimum();
double max = getWidgetModel().getMaximum();
if (value < min) {
value = min;
} else if (value > max)
value = max;
}
return value;
}
private int parseHEX(final String text, final boolean coerce) {
String valueText = text.trim();
if (text.startsWith(TextUpdateEditPart.HEX_PREFIX)) {
valueText = text.substring(TextUpdateEditPart.HEX_PREFIX.length());
}
if (valueText.contains(" ")) { //$NON-NLS-1$
valueText = valueText.substring(0, valueText.indexOf(SPACE));
}
long i = Long.parseLong(valueText, 16);
if (coerce) {
double min = getWidgetModel().getMinimum();
double max = getWidgetModel().getMaximum();
if (i < min) {
i = (long) min;
} else if (i > max)
i = (long) max;
}
return (int) i; // EPICS_V3_PV doesn't support Long
}
@Override
protected String formatValue(Object newValue, String propId) {
String text = super.formatValue(newValue, propId);
getWidgetModel()
.setPropertyValue(TextInputModel.PROP_TEXT, text, false);
return text;
}
/**
* @param newValue
*/
protected void updatePropSheet() {
TextInputModel model = getWidgetModel();
model.setPropertyVisible(
TextInputModel.PROP_MAX, !getWidgetModel().isLimitsFromPV());
model.setPropertyVisible(
TextInputModel.PROP_MIN, !getWidgetModel().isLimitsFromPV());
//set native text related properties visibility
boolean isNative = delegate instanceof NativeTextEditpartDelegate;
model.setPropertyVisible(TextInputModel.PROP_SHOW_NATIVE_BORDER,
isNative);
model.setPropertyVisible(TextInputModel.PROP_PASSWORD_INPUT, isNative);
model.setPropertyVisible(TextInputModel.PROP_READ_ONLY, isNative);
model.setPropertyVisible(TextInputModel.PROP_SHOW_H_SCROLL, isNative);
model.setPropertyVisible(TextInputModel.PROP_SHOW_V_SCROLL, isNative);
model.setPropertyVisible(TextInputModel.PROP_NEXT_FOCUS, isNative);
model.setPropertyVisible(TextInputModel.PROP_WRAP_WORDS, isNative);
//set classic text figure related properties visibility
model.setPropertyVisible(TextInputModel.PROP_TRANSPARENT, !isNative);
model.setPropertyVisible(TextInputModel.PROP_ROTATION, !isNative);
model.setPropertyVisible(TextInputModel.PROP_SELECTOR_TYPE, !isNative);
delegate.updatePropSheet();
}
@Override
protected void setFigureText(String text) {
if(delegate instanceof NativeTextEditpartDelegate)
((NativeTextEditpartDelegate)delegate).setFigureText(text);
else
super.setFigureText(text);
}
@Override
protected void performAutoSize() {
if(delegate instanceof NativeTextEditpartDelegate)
((NativeTextEditpartDelegate)delegate).performAutoSize();
else
super.performAutoSize();
}
@Override
public String getValue() {
if(delegate instanceof NativeTextEditpartDelegate)
return ((NativeTextEditpartDelegate)delegate).getValue();
else
return super.getValue();
}
}
|
package org.jgroups.blocks.cs;
import org.jgroups.Address;
import org.jgroups.Version;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.ThreadFactory;
import org.jgroups.util.Util;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
/**
* Blocking IO (BIO) connection. Starts 1 reader thread for the peer socket and blocks until data is available.
* Calls {@link TcpServer#receive(Address,byte[],int,int)} when data has been received.
* @author Bela Ban
* @since 3.6.5
*/
public class TcpConnection extends Connection {
protected final Socket sock; // socket to/from peer (result of srv_sock.accept() or new Socket())
protected final ReentrantLock send_lock=new ReentrantLock(); // serialize send()
protected DataOutputStream out;
protected DataInputStream in;
protected volatile Receiver receiver;
protected final TcpBaseServer server;
protected final AtomicInteger writers=new AtomicInteger(0); // to determine the last writer to flush
protected boolean connected;
/** Creates a connection stub and binds it, use {@link #connect(Address)} to connect */
public TcpConnection(Address peer_addr, TcpBaseServer server) throws Exception {
this.server=server;
if(peer_addr == null)
throw new IllegalArgumentException("Invalid parameter peer_addr="+ peer_addr);
this.peer_addr=peer_addr;
this.sock=server.socketFactory().createSocket("jgroups.tcp.sock");
setSocketParameters(sock);
last_access=getTimestamp(); // last time a message was sent or received (ns)
}
public TcpConnection(Socket s, TcpServer server) throws Exception {
this.sock=s;
this.server=server;
if(s == null)
throw new IllegalArgumentException("Invalid parameter s=" + s);
setSocketParameters(s);
this.out=new DataOutputStream(createBufferedOutputStream(s.getOutputStream()));
this.in=new DataInputStream(createBufferedInputStream(s.getInputStream()));
this.connected=sock.isConnected();
this.peer_addr=server.usePeerConnections()? readPeerAddress(s)
: new IpAddress((InetSocketAddress)s.getRemoteSocketAddress());
last_access=getTimestamp(); // last time a message was sent or received (ns)
}
public Address localAddress() {
InetSocketAddress local_addr=sock != null? (InetSocketAddress)sock.getLocalSocketAddress() : null;
return local_addr != null? new IpAddress(local_addr) : null;
}
public Address peerAddress() {
return peer_addr;
}
protected long getTimestamp() {
return server.timeService() != null? server.timeService().timestamp() : System.nanoTime();
}
protected String getSockAddress() {
StringBuilder sb=new StringBuilder();
if(sock != null) {
sb.append(sock.getLocalAddress().getHostAddress()).append(':').append(sock.getLocalPort());
sb.append(" - ").append(sock.getInetAddress().getHostAddress()).append(':').append(sock.getPort());
}
return sb.toString();
}
protected void updateLastAccessed() {
if(server.connExpireTime() > 0)
last_access=getTimestamp();
}
public void connect(Address dest) throws Exception {
connect(dest, server.usePeerConnections());
}
protected void connect(Address dest, boolean send_local_addr) throws Exception {
SocketAddress destAddr=new InetSocketAddress(((IpAddress)dest).getIpAddress(), ((IpAddress)dest).getPort());
try {
if(!server.defer_client_binding)
this.sock.bind(new InetSocketAddress(server.client_bind_addr, server.client_bind_port));
Util.connect(this.sock, destAddr, server.sock_conn_timeout);
if(this.sock.getLocalSocketAddress() != null && this.sock.getLocalSocketAddress().equals(destAddr))
throw new IllegalStateException("socket's bind and connect address are the same: " + destAddr);
this.out=new DataOutputStream(createBufferedOutputStream(sock.getOutputStream()));
this.in=new DataInputStream(createBufferedInputStream(sock.getInputStream()));
connected=sock.isConnected();
if(send_local_addr)
sendLocalAddress(server.localAddress());
}
catch(Exception t) {
Util.close(this.sock);
connected=false;
throw t;
}
}
public void start() {
if(receiver != null)
receiver.stop();
receiver=new Receiver(server.factory).start();
}
/**
*
* @param data Guaranteed to be non null
* @param offset
* @param length
*/
public void send(byte[] data, int offset, int length) throws Exception {
if(out == null)
return;
writers.incrementAndGet();
send_lock.lock();
try {
doSend(data, offset, length);
updateLastAccessed();
}
catch(InterruptedException iex) {
Thread.currentThread().interrupt(); // set interrupt flag again
}
finally {
send_lock.unlock();
if(writers.decrementAndGet() == 0) // only the last active writer thread calls flush()
flush(); // won't throw an exception
}
}
public void send(ByteBuffer buf) throws Exception {
if(buf == null)
return;
int offset=buf.hasArray()? buf.arrayOffset() + buf.position() : buf.position(),
len=buf.remaining();
if(!buf.isDirect())
send(buf.array(), offset, len);
else { // by default use a copy; but of course implementers of Receiver can override this
byte[] tmp=new byte[len];
buf.get(tmp, 0, len);
send(tmp, 0, len); // will get copied again if send-queues are enabled
}
}
protected void doSend(byte[] data, int offset, int length) throws Exception {
out.writeInt(length); // write the length of the data buffer first
out.write(data,offset,length);
}
public void flush() {
try {
out.flush();
}
catch(Throwable t) {
}
}
protected OutputStream createBufferedOutputStream(OutputStream out) {
int size=(server instanceof TcpServer)? ((TcpServer)server).getBufferedOutputStreamSize() : 0;
return size == 0? new BufferedOutputStream(out) : new BufferedOutputStream(out, size);
}
protected InputStream createBufferedInputStream(InputStream in) {
int size=(server instanceof TcpServer)? ((TcpServer)server).getBufferedInputStreamSize() : 0;
return size == 0? new BufferedInputStream(in) : new BufferedInputStream(in, size);
}
protected void setSocketParameters(Socket client_sock) throws SocketException {
try {
if(server.send_buf_size > 0)
client_sock.setSendBufferSize(server.send_buf_size);
}
catch(IllegalArgumentException ex) {
server.log.error("%s: exception setting send buffer to %d bytes: %s", server.local_addr, server.send_buf_size, ex);
}
try {
if(server.recv_buf_size > 0)
client_sock.setReceiveBufferSize(server.recv_buf_size);
}
catch(IllegalArgumentException ex) {
server.log.error("%s: exception setting receive buffer to %d bytes: %s", server.local_addr, server.recv_buf_size, ex);
}
client_sock.setKeepAlive(true);
client_sock.setTcpNoDelay(server.tcp_nodelay);
try {
if(server.linger > 0)
client_sock.setSoLinger(true, server.linger);
else
client_sock.setSoLinger(false, -1);
}
catch(Throwable t) {
server.log().warn("%s: failed setting SO_LINGER option: %s", server.localAddress(), t);
}
}
/**
* Send the cookie first, then the our port number. If the cookie
* doesn't match the receiver's cookie, the receiver will reject the
* connection and close it.
*/
protected void sendLocalAddress(Address local_addr) throws Exception {
try {
// write the cookie
out.write(cookie, 0, cookie.length);
// write the version
out.writeShort(Version.version);
out.writeShort(local_addr.serializedSize()); // address size
local_addr.writeTo(out);
out.flush(); // needed ?
updateLastAccessed();
}
catch(Exception ex) {
server.socket_factory.close(this.sock);
connected=false;
throw ex;
}
}
/**
* Reads the peer's address. First a cookie has to be sent which has to
* match my own cookie, otherwise the connection will be refused
*/
protected Address readPeerAddress(Socket client_sock) throws Exception {
int timeout=client_sock.getSoTimeout();
client_sock.setSoTimeout(server.peerAddressReadTimeout());
try {
// read the cookie first
byte[] input_cookie=new byte[cookie.length];
in.readFully(input_cookie, 0, input_cookie.length);
if(!Arrays.equals(cookie, input_cookie))
throw new SocketException(String.format("%s: BaseServer.TcpConnection.readPeerAddress(): cookie sent by " +
"%s:%d does not match own cookie; terminating connection",
server.localAddress(), client_sock.getInetAddress(), client_sock.getPort()));
// then read the version
short version=in.readShort();
if(!Version.isBinaryCompatible(version))
throw new IOException("packet from " + client_sock.getInetAddress() + ":" + client_sock.getPort() +
" has different version (" + Version.print(version) +
") from ours (" + Version.printVersion() + "); discarding it");
in.readShort(); // address length is only needed by NioConnection
Address client_peer_addr=new IpAddress();
client_peer_addr.readFrom(in);
updateLastAccessed();
return client_peer_addr;
}
finally {
client_sock.setSoTimeout(timeout);
}
}
protected class Receiver implements Runnable {
protected final Thread recv;
protected volatile boolean receiving=true;
protected byte[] buffer; // no need to be volatile, only accessed by this thread
public Receiver(ThreadFactory f) {
recv=f.newThread(this,"Connection.Receiver [" + getSockAddress() + "]");
}
public Receiver start() {
receiving=true;
recv.start();
return this;
}
public Receiver stop() {
receiving=false;
return this;
}
public boolean isRunning() {return receiving;}
public boolean canRun() {return isRunning() && isConnected();}
public int bufferSize() {return buffer != null? buffer.length : 0;}
public void run() {
try {
while(canRun()) {
int len=in.readInt(); // needed to read messages from TCP_NIO2
server.receive(peer_addr, in, len);
updateLastAccessed();
}
}
catch(EOFException | SocketException ex) {
; // regular use case when a peer closes its connection - we don't want to log this as exception
}
catch(Exception e) {
server.log.warn("failed handling message", e);
}
finally {
server.notifyConnectionClosed(TcpConnection.this);
}
}
}
public String toString() {
Socket tmp_sock=sock;
if(tmp_sock == null)
return "<null socket>";
InetAddress local=tmp_sock.getLocalAddress(), remote=tmp_sock.getInetAddress();
String local_str=local != null? Util.shortName(local) : "<null>";
String remote_str=remote != null? Util.shortName(remote) : "<null>";
return String.format("%s:%s --> %s:%s (%d secs old) [%s] [recv_buf=%d]",
local_str, tmp_sock.getLocalPort(), remote_str, tmp_sock.getPort(),
TimeUnit.SECONDS.convert(getTimestamp() - last_access, TimeUnit.NANOSECONDS),
status(), receiver != null? receiver.bufferSize() : 0);
}
@Override
public String status() {
if(sock == null) return "n/a";
if(isConnected()) return "connected";
if(isOpen()) return "open";
return "closed";
}
public boolean isExpired(long now) {
return server.conn_expire_time > 0 && now - last_access >= server.conn_expire_time;
}
public boolean isConnected() {
return connected;
}
public boolean isConnectionPending() {
return false;
}
public boolean isOpen() {
return sock != null && !sock.isClosed();
}
public void close() throws IOException {
Util.close(sock);
send_lock.lock();
try {
if(receiver != null) {
receiver.stop();
receiver=null;
}
Util.close(out,in);
}
finally {
connected=false;
send_lock.unlock();
}
}
}
|
package org.openhab.binding.zwave.internal.config;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import org.openhab.binding.zwave.internal.ZWaveNetworkMonitor;
import org.openhab.binding.zwave.internal.protocol.ConfigurationParameter;
import org.openhab.binding.zwave.internal.protocol.ZWaveController;
import org.openhab.binding.zwave.internal.protocol.ZWaveDeviceClass;
import org.openhab.binding.zwave.internal.protocol.ZWaveDeviceType;
import org.openhab.binding.zwave.internal.protocol.ZWaveEventListener;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.openhab.binding.zwave.internal.protocol.SerialMessage;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveAssociationCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveAssociationCommandClass.ZWaveAssociationEvent;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveBatteryCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveConfigurationCommandClass.ZWaveConfigurationParameterEvent;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveConfigurationCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveSwitchAllCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveVersionCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveWakeUpCommandClass;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveInclusionEvent;
import org.openhab.binding.zwave.internal.protocol.initialization.ZWaveNodeInitStage;
import org.openhab.binding.zwave.internal.protocol.initialization.ZWaveNodeSerializer;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Z Wave configuration class Interfaces between the REST services using the
* OpenHABConfigurationService interface. It uses the ZWave product database to
* configure zwave devices.
*
* @author Chris Jackson
* @since 1.4.0
*
*/
public class ZWaveConfiguration implements OpenHABConfigurationService, ZWaveEventListener {
private static final Logger logger = LoggerFactory.getLogger(ZWaveConfiguration.class);
private ZWaveController zController = null;
private ZWaveNetworkMonitor networkMonitor = null;
private boolean inclusion = false;
private boolean exclusion = false;
private DateFormat df;
private Timer timer = new Timer();
private TimerTask timerTask = null;
private final String MAX_VERSION = "255.255";
private PendingConfiguration PendingCfg = new PendingConfiguration();
/**
* Constructor for the configuration class. Sets the zwave controller
* which is required in order to allow the class to retrieve the configuration.
* @param controller The zWave controller
*/
public ZWaveConfiguration(ZWaveController controller, ZWaveNetworkMonitor monitor) {
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
this.zController = controller;
this.networkMonitor = monitor;
// Register the service
FrameworkUtil.getBundle(getClass()).getBundleContext()
.registerService(OpenHABConfigurationService.class.getName(), this, null);
}
@Override
public String getBundleName() {
return "zwave";
}
@Override
public String getVersion() {
return FrameworkUtil.getBundle(getClass()).getBundleContext().getBundle().getVersion().toString();
}
@Override
public List<OpenHABConfigurationRecord> getConfiguration(String domain) {
// We only deal with top level domains here!
if (domain.endsWith("/") == false) {
logger.error("Malformed domain request in getConfiguration '{}'", domain);
return null;
}
List<OpenHABConfigurationRecord> records = new ArrayList<OpenHABConfigurationRecord>();
OpenHABConfigurationRecord record;
if (domain.equals("status/")) {
// Return the z-wave status information
return null;
}
if (domain.startsWith("products/")) {
ZWaveProductDatabase database = new ZWaveProductDatabase();
String[] splitDomain = domain.split("/");
switch (splitDomain.length) {
case 1:
// Just list the manufacturers
for (ZWaveDbManufacturer manufacturer : database.GetManufacturers()) {
record = new OpenHABConfigurationRecord(domain + manufacturer.Id.toString() + "/", manufacturer.Name);
records.add(record);
}
break;
case 2:
// Get products list
if (database.FindManufacturer(Integer.parseInt(splitDomain[1])) == false) {
break;
}
record = new OpenHABConfigurationRecord(domain, "ManufacturerID", "Manufacturer ID", true);
record.value = Integer.toHexString(database.getManufacturerId());
records.add(record);
for (ZWaveDbProduct product : database.GetProducts()) {
record = new OpenHABConfigurationRecord(domain + product.Reference.get(0).Type + "/" + product.Reference.get(0).Id + "/", product.Model);
record.value = database.getLabel(product.Label);
records.add(record);
}
break;
case 4:
// Get product
if (database.FindProduct(Integer.parseInt(splitDomain[1]), Integer.parseInt(splitDomain[2]), Integer.parseInt(splitDomain[3]), MAX_VERSION) == false) {
break;
}
if(database.doesProductImplementCommandClass(ZWaveCommandClass.CommandClass.CONFIGURATION.getKey()) == true) {
record = new OpenHABConfigurationRecord(domain + "parameters/", "Configuration Parameters");
records.add(record);
}
if(database.doesProductImplementCommandClass(ZWaveCommandClass.CommandClass.ASSOCIATION.getKey()) == true) {
record = new OpenHABConfigurationRecord(domain + "associations/", "Association Groups");
records.add(record);
}
record = new OpenHABConfigurationRecord(domain + "classes/", "Command Classes");
records.add(record);
break;
case 5:
// Get product
if (database.FindProduct(Integer.parseInt(splitDomain[1]), Integer.parseInt(splitDomain[2]), Integer.parseInt(splitDomain[3]), MAX_VERSION) == false) {
break;
}
if (splitDomain[4].equals("parameters")) {
List<ZWaveDbConfigurationParameter> configList = database.getProductConfigParameters();
// Loop through the parameters and add to the records...
for (ZWaveDbConfigurationParameter parameter : configList) {
record = new OpenHABConfigurationRecord(domain, "configuration" + parameter.Index,
database.getLabel(parameter.Label), true);
if (parameter != null)
record.value = parameter.Default;
// Add the data type
try {
record.type = OpenHABConfigurationRecord.TYPE.valueOf(parameter.Type.toUpperCase());
} catch(IllegalArgumentException e) {
logger.error("Error with parameter type for {} - Set {} - assuming LONG", parameter.Label.toString(), parameter.Type);
record.type = OpenHABConfigurationRecord.TYPE.LONG;
}
if(parameter.Item != null) {
for (ZWaveDbConfigurationListItem item : parameter.Item) {
record.addValue(Integer.toString(item.Value), database.getLabel(item.Label));
}
}
// Add the description
record.description = database.getLabel(parameter.Help);
records.add(record);
}
}
if (splitDomain[4].equals("associations")) {
List<ZWaveDbAssociationGroup> groupList = database.getProductAssociationGroups();
if (groupList != null) {
// Loop through the associations and add to the
// records...
for (ZWaveDbAssociationGroup group : groupList) {
record = new OpenHABConfigurationRecord(domain, "association" + group.Index,
database.getLabel(group.Label), true);
// Add the description
record.description = database.getLabel(group.Help);
records.add(record);
}
}
}
if (splitDomain[4].equals("classes")) {
List<ZWaveDbCommandClass> classList = database.getProductCommandClasses();
if (classList != null) {
// Loop through the command classes and add to the
// records...
for (ZWaveDbCommandClass iClass : classList) {
// Make sure the command class exists!
if(ZWaveCommandClass.CommandClass.getCommandClass(iClass.Id) == null) {
continue;
}
record = new OpenHABConfigurationRecord(domain, "class" + iClass.Id,
ZWaveCommandClass.CommandClass.getCommandClass(iClass.Id).getLabel(), true);
if(ZWaveCommandClass.CommandClass.getCommandClass(iClass.Id).getCommandClassClass() == null) {
record.state = OpenHABConfigurationRecord.STATE.WARNING;
}
records.add(record);
}
}
}
break;
}
return records;
}
// All domains after here must have an initialised ZWave network
if (zController == null) {
logger.error("Controller not initialised in call to getConfiguration");
return null;
}
if (domain.equals("nodes/")) {
ZWaveProductDatabase database = new ZWaveProductDatabase();
// Return the list of nodes
for(ZWaveNode node : zController.getNodes()) {
if (node.getName() == null || node.getName().isEmpty()) {
record = new OpenHABConfigurationRecord("nodes/" + "node" + node.getNodeId() + "/", "Node " + node.getNodeId());
}
else {
record = new OpenHABConfigurationRecord("nodes/" + "node" + node.getNodeId() + "/", node.getNodeId() + ": " + node.getName());
}
// If we can't find the product, then try and find just the manufacturer
if (node.getManufacturer() == Integer.MAX_VALUE) {
// The device isn't know, print nothing!
}
else if(database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == false) {
if (database.FindManufacturer(node.getManufacturer()) == false) {
record.value = "Manufacturer:" + node.getManufacturer() + " [ID:"
+ Integer.toHexString(node.getDeviceId()) + ",Type:"
+ Integer.toHexString(node.getDeviceType()) + "]";
} else {
record.value = database.getManufacturerName() + " [ID:"
+ Integer.toHexString(node.getDeviceId()) + ",Type:"
+ Integer.toHexString(node.getDeviceType()) + "]";
}
logger.debug("NODE {}: No database entry: {}", node.getNodeId(), record.value);
} else {
if (node.getLocation() == null || node.getLocation().isEmpty()) {
record.value = database.getProductName();
}
else {
record.value = database.getProductName() + ": " + node.getLocation();
}
}
// Set the state
boolean canDelete = false;
switch(node.getNodeState()) {
case DEAD:
record.state = OpenHABConfigurationRecord.STATE.ERROR;
break;
case FAILED:
record.state = OpenHABConfigurationRecord.STATE.ERROR;
canDelete = true;
break;
case ALIVE:
Date lastDead = node.getDeadTime();
Long timeSinceLastDead = Long.MAX_VALUE;
if(lastDead != null) {
timeSinceLastDead = System.currentTimeMillis() - lastDead.getTime();
}
if(node.getNodeInitializationStage() != ZWaveNodeInitStage.DONE) {
record.state = OpenHABConfigurationRecord.STATE.INITIALIZING;
}
else if(node.getDeadCount() > 0 && timeSinceLastDead < 86400000) {
record.state = OpenHABConfigurationRecord.STATE.WARNING;
}
else if(node.getSendCount() > 20 && (node.getRetryCount() * 100 / node.getSendCount()) > 5) {
record.state = OpenHABConfigurationRecord.STATE.WARNING;
}
else {
record.state = OpenHABConfigurationRecord.STATE.OK;
}
break;
}
// Add the action buttons
record.addAction("Heal", "Heal Node");
record.addAction("Initialise", "Reinitialise Node");
// Add the delete button if the node is not "operational"
if(canDelete) {
record.addAction("Delete", "Delete Node");
}
records.add(record);
}
return records;
}
if (domain.startsWith("nodes/node")) {
String nodeNumber = domain.substring(10);
int next = nodeNumber.indexOf('/');
String arg = null;
if (next != -1) {
arg = nodeNumber.substring(next + 1);
nodeNumber = nodeNumber.substring(0, next);
}
int nodeId = Integer.parseInt(nodeNumber);
// Return the detailed configuration for this node
ZWaveNode node = zController.getNode(nodeId);
if (node == null) {
return null;
}
// Open the product database
ZWaveProductDatabase database = new ZWaveProductDatabase();
// Process the request
if (arg.equals("")) {
record = new OpenHABConfigurationRecord(domain, "Name", "Name", false);
record.value = node.getName();
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Location", "Location", false);
record.value = node.getLocation();
records.add(record);
ZWaveSwitchAllCommandClass switchAllCommandClass = (ZWaveSwitchAllCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.SWITCH_ALL);
if (switchAllCommandClass != null) {
record = new OpenHABConfigurationRecord(domain, "Switch All", "Switch All", false);
record.type = OpenHABConfigurationRecord.TYPE.LIST;
record.addValue("0", "Exclude from All On and All Off groups");
record.addValue("1", "Include in All On group");
record.addValue("2", "Include in All Off group");
record.addValue("255", "Include in All On and All Off groups");
record.value = String.valueOf(switchAllCommandClass.getMode());
records.add(record);
}
if(node.getManufacturer() != Integer.MAX_VALUE) {
if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == true) {
// Add links to configuration if the node supports the various command classes
if(database.doesProductImplementCommandClass(ZWaveCommandClass.CommandClass.CONFIGURATION.getKey()) == true) {
record = new OpenHABConfigurationRecord(domain + "parameters/", "Configuration Parameters");
record.addAction("Refresh", "Refresh");
records.add(record);
}
if(database.doesProductImplementCommandClass(ZWaveCommandClass.CommandClass.ASSOCIATION.getKey()) == true) {
record = new OpenHABConfigurationRecord(domain + "associations/", "Association Groups");
record.addAction("Refresh", "Refresh");
records.add(record);
}
if(database.doesProductImplementCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP.getKey()) == true) {
record = new OpenHABConfigurationRecord(domain + "wakeup/", "Wakeup Period");
record.addAction("Refresh", "Refresh");
records.add(record);
}
}
}
// Is this a controller
if(nodeId == zController.getOwnNodeId()) {
record = new OpenHABConfigurationRecord(domain + "controller/", "Controller");
records.add(record);
}
record = new OpenHABConfigurationRecord(domain + "neighbors/", "Neighbors");
record.addAction("Refresh", "Refresh");
records.add(record);
record = new OpenHABConfigurationRecord(domain + "status/", "Status");
records.add(record);
record = new OpenHABConfigurationRecord(domain + "info/", "Information");
records.add(record);
} else if (arg.equals("switch_all/")) {
/*ZWaveSwitchAllCommandClass switchAllCommandClass = (ZWaveSwitchAllCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.SWITCH_ALL);
if (switchAllCommandClass != null) {
logger.debug("NODE {}: Supports Switch All Command Class Adding Switch All Configuration ", (Object)nodeId);
record = new OpenHABConfigurationRecord(domain, "Mode", "Mode", true);
record.type = OpenHABConfigurationRecord.TYPE.LIST;
record.addValue("0x00", "Exclude from All On and All Off groups");
record.addValue("0x01", "Include in All On group");
record.addValue("0x02", "Include in All Off group");
record.addValue("0xFF", "Include in All On and All Off groups");
records.add(record);
}*/
} else if (arg.equals("info/")) {
record = new OpenHABConfigurationRecord(domain, "NodeID", "Node ID", true);
record.value = Integer.toString(node.getNodeId());
records.add(record);
if (node.getManufacturer() != Integer.MAX_VALUE) {
if (database.FindManufacturer(node.getManufacturer()) == true) {
record = new OpenHABConfigurationRecord(domain, "Manufacturer", "Manufacturer", true);
record.value = database.getManufacturerName();
records.add(record);
}
if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == true) {
record = new OpenHABConfigurationRecord(domain, "Product", "Product", true);
record.value = database.getProductName();
records.add(record);
}
}
record = new OpenHABConfigurationRecord(domain, "ManufacturerID", "Manufacturer ID", true);
if(node.getDeviceId() == Integer.MAX_VALUE) {
record.value = "UNKNOWN";
}
else {
record.value = Integer.toHexString(node.getManufacturer());
}
records.add(record);
record = new OpenHABConfigurationRecord(domain, "DeviceID", "Device ID", true);
if(node.getDeviceId() == Integer.MAX_VALUE) {
record.value = "UNKNOWN";
}
else {
record.value = Integer.toHexString(node.getDeviceId());
}
records.add(record);
record = new OpenHABConfigurationRecord(domain, "DeviceType", "Device Type", true);
if(node.getDeviceId() == Integer.MAX_VALUE) {
record.value = "UNKNOWN";
}
else {
record.value = Integer.toHexString(node.getDeviceType());
}
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Version", "Version", true);
record.value = Integer.toString(node.getVersion());
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Listening", "Listening", true);
record.value = Boolean.toString(node.isListening());
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Routing", "Routing", true);
record.value = Boolean.toString(node.isRouting());
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Power", "Power", true);
ZWaveBatteryCommandClass batteryCommandClass = (ZWaveBatteryCommandClass) node
.getCommandClass(CommandClass.BATTERY);
if (batteryCommandClass != null) {
if(batteryCommandClass.getBatteryLevel() == null) {
record.value = "BATTERY " + "UNKNOWN";
}
else {
record.value = "BATTERY " + batteryCommandClass.getBatteryLevel() + "%";
}
// If the node is reporting low battery, mark it up...
if(batteryCommandClass.getBatteryLow() == true) {
record.value += " LOW";
}
}
else if(node.getNodeInitializationStage().getStage() <= ZWaveNodeInitStage.DETAILS.getStage()) {
// If we haven't passed the DETAILS stage, then we don't know the source
record.value = "UNKNOWN";
}
else {
record.value = "MAINS";
}
records.add(record);
ZWaveVersionCommandClass versionCommandClass = (ZWaveVersionCommandClass) node
.getCommandClass(CommandClass.VERSION);
if (versionCommandClass != null) {
record = new OpenHABConfigurationRecord(domain, "LibType", "Library Type", true);
if (versionCommandClass.getLibraryType() == null) {
record.value = "Unknown";
}
else {
record.value = versionCommandClass.getLibraryType().getLabel();
}
records.add(record);
record = new OpenHABConfigurationRecord(domain, "ProtocolVersion", "Protocol Version", true);
if (versionCommandClass.getProtocolVersion() == null) {
record.value = "Unknown";
}
else {
record.value = versionCommandClass.getProtocolVersion();
}
records.add(record);
record = new OpenHABConfigurationRecord(domain, "AppVersion", "Application Version", true);
if (versionCommandClass.getApplicationVersion() == null) {
record.value = "Unknown";
}
else {
record.value = versionCommandClass.getApplicationVersion();
}
records.add(record);
}
ZWaveDeviceClass devClass = node.getDeviceClass();
if (devClass != null) {
record = new OpenHABConfigurationRecord(domain, "BasicClass", "Basic Device Class", true);
record.value = devClass.getBasicDeviceClass().toString();
records.add(record);
record = new OpenHABConfigurationRecord(domain, "GenericClass", "Generic Device Class", true);
record.value = devClass.getGenericDeviceClass().toString();
records.add(record);
record = new OpenHABConfigurationRecord(domain, "SpecificClass", "Specific Device Class", true);
record.value = devClass.getSpecificDeviceClass().toString();
records.add(record);
}
} else if (arg.equals("status/")) {
record = new OpenHABConfigurationRecord(domain, "LastSent", "Last Packet Sent", true);
if(node.getLastSent() == null) {
record.value = "NEVER";
}
else {
record.value = df.format(node.getLastSent());
}
records.add(record);
record = new OpenHABConfigurationRecord(domain, "LastReceived", "Last Packet Received", true);
if(node.getLastReceived() == null) {
record.value = "NEVER";
}
else {
record.value = df.format(node.getLastReceived());
}
records.add(record);
if(networkMonitor != null) {
record = new OpenHABConfigurationRecord(domain, "LastHeal", "Heal Status", true);
if (node.getHealState() == null) {
record.value = networkMonitor.getNodeState(nodeId);
}
else {
record.value = node.getHealState();
}
records.add(record);
}
record = new OpenHABConfigurationRecord(domain, "NodeStage", "Node Stage", true);
record.value = node.getNodeState() + " " + node.getNodeInitializationStage() + " " + df.format(node.getQueryStageTimeStamp());
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Packets", "Packet Statistics", true);
record.value = node.getRetryCount() + " / " + node.getSendCount();
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Dead", "Dead", true);
if(node.getDeadCount() == 0) {
record.value = Boolean.toString(node.isDead());
}
else {
record.value = Boolean.toString(node.isDead()) + " [" + node.getDeadCount() + " previous - last @ " + df.format(node.getDeadTime()) + "]";
}
records.add(record);
} else if (arg.equals("parameters/")) {
if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) != false) {
List<ZWaveDbConfigurationParameter> configList = database.getProductConfigParameters();
if(configList == null) {
return records;
}
// Get the configuration command class for this node if it's supported
ZWaveConfigurationCommandClass configurationCommandClass = (ZWaveConfigurationCommandClass) node
.getCommandClass(CommandClass.CONFIGURATION);
if (configurationCommandClass == null) {
return null;
}
// Loop through the parameters and add to the records...
for (ZWaveDbConfigurationParameter parameter : configList) {
record = new OpenHABConfigurationRecord(domain, "configuration" + parameter.Index,
parameter.Index + ": " + database.getLabel(parameter.Label), false);
ConfigurationParameter configurationParameter = configurationCommandClass
.getParameter(parameter.Index);
// Only provide a value if it's stored in the node and is not WriteOnly
// This is the only way we can be sure of its real value
if (configurationParameter != null && configurationParameter.getWriteOnly() == false) {
record.value = Integer.toString(configurationParameter.getValue());
}
// If the value is in our PENDING list, then use that instead
Integer pendingValue = PendingCfg.Get(ZWaveCommandClass.CommandClass.CONFIGURATION.getKey(), nodeId, parameter.Index);
if(pendingValue != null) {
record.value = Integer.toString(pendingValue);
record.state = OpenHABConfigurationRecord.STATE.PENDING;
}
try {
record.type = OpenHABConfigurationRecord.TYPE.valueOf(parameter.Type.toUpperCase());
} catch(IllegalArgumentException e) {
record.type = OpenHABConfigurationRecord.TYPE.LONG;
}
if(parameter.Item != null) {
for (ZWaveDbConfigurationListItem item : parameter.Item)
record.addValue(Integer.toString(item.Value), database.getLabel(item.Label));
}
// Add any limits
record.minimum = parameter.Minimum;
record.maximum = parameter.Maximum;
// Add the description
record.description = database.getLabel(parameter.Help);
records.add(record);
}
}
} else if (arg.equals("associations/")) {
if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) != false) {
List<ZWaveDbAssociationGroup> groupList = database.getProductAssociationGroups();
if (groupList == null) {
return records;
}
// Get the association command class for this node if it's supported
ZWaveAssociationCommandClass associationCommandClass = (ZWaveAssociationCommandClass) node
.getCommandClass(CommandClass.ASSOCIATION);
if (associationCommandClass == null) {
return null;
}
// Loop through the associations and add all groups to the
// records...
for (ZWaveDbAssociationGroup group : groupList) {
record = new OpenHABConfigurationRecord(domain, "association" + group.Index + "/",
database.getLabel(group.Label), true);
// Add the description
record.description = database.getLabel(group.Help);
// For the 'value', describe how many devices are set and the maximum allowed
int memberCnt = 0;
List<Integer> members = associationCommandClass.getGroupMembers(group.Index);
if(members != null) {
memberCnt = members.size();
}
record.value = memberCnt + " of " + group.Maximum + " group members";
// Add the action for refresh
record.addAction("Refresh", "Refresh");
records.add(record);
}
}
} else if (arg.startsWith("associations/association")) {
if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) != false) {
String groupString = arg.substring(24);
int nextDelimiter = groupString.indexOf('/');
// String arg = null;
if (nextDelimiter != -1) {
// arg = nodeNumber.substring(nextDelimiter + 1);
groupString = groupString.substring(0, nextDelimiter);
}
int groupId = Integer.parseInt(groupString);
// Get the requested group so we have access to the
// attributes
List<ZWaveDbAssociationGroup> groupList = database.getProductAssociationGroups();
if (groupList == null) {
return null;
}
ZWaveDbAssociationGroup group = null;
for (int cnt = 0; cnt < groupList.size(); cnt++) {
if (groupList.get(cnt).Index == groupId) {
group = groupList.get(cnt);
break;
}
}
// Return if the group wasn't found
if (group == null) {
return null;
}
// Get the group members
ZWaveAssociationCommandClass associationCommandClass = (ZWaveAssociationCommandClass) node
.getCommandClass(CommandClass.ASSOCIATION);
// First we build a list of all nodes, starting with the group members
// This ensures that old nodes included in a group, but not now part
// of the network will still be listed, and can be removed.
List<Integer> nodes = new ArrayList<Integer>();
nodes.addAll(associationCommandClass.getGroupMembers(groupId));
for(ZWaveNode nodeList : zController.getNodes()) {
// Don't allow an association with itself
if(nodeList.getNodeId() == node.getNodeId()) {
continue;
}
if(!nodes.contains(nodeList.getNodeId())) {
nodes.add(nodeList.getNodeId());
}
}
// Let's sort them!
Collections.sort(nodes);
// Now we loop through the node list and create an entry for each node.
List<Integer> members = associationCommandClass.getGroupMembers(groupId);
for(int i = 0; i < nodes.size(); i++) {
int nodeNum = nodes.get(i);
ZWaveNode nodeList = zController.getNode(nodeNum);
// Add the member
if (nodeList == null || nodeList.getName() == null || nodeList.getName().isEmpty()) {
record = new OpenHABConfigurationRecord(domain, "node" + nodeNum, "Node " + nodeNum, false);
} else {
record = new OpenHABConfigurationRecord(domain, "node" + nodeNum, nodeList.getName(), false);
}
record.type = OpenHABConfigurationRecord.TYPE.LIST;
record.addValue("true", "Member");
record.addValue("false", "Non-Member");
if (members != null && members.contains(nodeNum)) {
record.value = "true";
} else {
record.value = "false";
}
// If the value is in our PENDING list, then use that instead
Integer pendingValue = PendingCfg.Get(ZWaveCommandClass.CommandClass.ASSOCIATION.getKey(), nodeId, groupId, nodeNum);
if(pendingValue != null) {
if(pendingValue == 1) {
record.value = "true";
} else {
record.value = "false";
}
record.state = OpenHABConfigurationRecord.STATE.PENDING;
}
records.add(record);
}
}
} else if (arg.equals("wakeup/")) {
ZWaveWakeUpCommandClass wakeupCommandClass = (ZWaveWakeUpCommandClass) node
.getCommandClass(CommandClass.WAKE_UP);
if(wakeupCommandClass == null) {
logger.debug("NODE {}: wakeupCommandClass not supported", nodeId);
return null;
}
// Display the wakeup parameters.
// Note that only the interval is writable.
record = new OpenHABConfigurationRecord(domain, "Interval", "Wakeup Interval", false);
record.minimum = wakeupCommandClass.getMinInterval();
record.maximum = wakeupCommandClass.getMaxInterval();
record.value = Integer.toString(wakeupCommandClass.getInterval());
// If the value is in our PENDING list, then use that instead
Integer pendingValue = PendingCfg.Get(ZWaveCommandClass.CommandClass.WAKE_UP.getKey(), nodeId);
if(pendingValue != null) {
record.value = Integer.toString(pendingValue);
record.state = OpenHABConfigurationRecord.STATE.PENDING;
}
records.add(record);
record = new OpenHABConfigurationRecord(domain, "LastWake", "Last Wakeup", true);
if(wakeupCommandClass.getLastWakeup() == null) {
record.value = "NEVER";
}
else {
record.value = df.format(wakeupCommandClass.getLastWakeup());
}
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Target", "Target Node", true);
record.value = Integer.toString(wakeupCommandClass.getTargetNodeId());
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Minimum", "Minimum Interval", true);
record.value = Integer.toString(wakeupCommandClass.getMinInterval());
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Maximum", "Maximum Interval", true);
record.value = Integer.toString(wakeupCommandClass.getMaxInterval());
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Default", "Default Interval", true);
record.value = Integer.toString(wakeupCommandClass.getDefaultInterval());
records.add(record);
record = new OpenHABConfigurationRecord(domain, "Step", "Interval Step", true);
record.value = Integer.toString(wakeupCommandClass.getIntervalStep());
records.add(record);
} else if (arg.equals("neighbors/")) {
// Check that we have the neighbor list for this node
if(node.getNeighbors() == null) {
return null;
}
for (Integer neighbor : node.getNeighbors()) {
ZWaveNode nodeNeighbor = zController.getNode(neighbor);
String neighborName;
if (nodeNeighbor == null) {
neighborName = "Node " + neighbor + " (UNKNOWN)";
}
else if (nodeNeighbor.getName() == null || nodeNeighbor.getName().isEmpty()) {
neighborName = "Node " + neighbor;
}
else {
neighborName = nodeNeighbor.getName();
}
// Create the record
record = new OpenHABConfigurationRecord(domain, "node" + neighbor, neighborName, false);
record.readonly = true;
// If this node isn't known, mark it as an error
if(nodeNeighbor == null) {
record.state = OpenHABConfigurationRecord.STATE.ERROR;
}
records.add(record);
}
} else if (arg.equals("controller/")) {
// Create the record
record = new OpenHABConfigurationRecord(domain, "Type", "Controller Type", true);
record.type = OpenHABConfigurationRecord.TYPE.LIST;
record.value = zController.getControllerType().getLabel();
record.addValue(ZWaveDeviceType.PRIMARY.toString(), ZWaveDeviceType.PRIMARY.getLabel());
record.addValue(ZWaveDeviceType.SECONDARY.toString(), ZWaveDeviceType.SECONDARY.getLabel());
record.addValue(ZWaveDeviceType.SUC.toString(), ZWaveDeviceType.SUC.getLabel());
// Set the read-only if this isn't a controller!
switch(zController.getControllerType()) {
case SUC:
case PRIMARY:
case SECONDARY:
record.readonly = true;
break;
default:
record.readonly = true;
break;
}
records.add(record);
record = new OpenHABConfigurationRecord(domain, "APIVersion", "API Version", true);
record.value = zController.getSerialAPIVersion();
records.add(record);
record = new OpenHABConfigurationRecord(domain, "ZWaveVersion", "ZWave Version", true);
record.value = zController.getZWaveVersion();
records.add(record);
}
return records;
}
return null;
}
@Override
public void setConfiguration(String domain, List<OpenHABConfigurationRecord> records) {
}
@Override
public String getCommonName() {
return "ZWave";
}
@Override
public String getDescription() {
return "Provides interface to Z-Wave network";
}
@Override
public void doAction(String domain, String action) {
logger.trace("doAction domain '{}' to '{}'", domain, action);
String[] splitDomain = domain.split("/");
// There must be at least 2 components to the domain
if (splitDomain.length < 2) {
logger.error("Error malformed domain in doAction '{}'", domain);
return;
}
// Process Controller Reset requests even if the controller isn't initialised
if (splitDomain[0].equals("binding") && splitDomain[1].equals("network")) {
if(action.equals("SoftReset")) {
zController.requestSoftReset();
}
else if(action.equals("HardReset")) {
zController.requestHardReset();
}
}
// If the controller isn't ready, then ignore any further requests
if (zController.isConnected() == false) {
logger.debug("Controller not ready - Ignoring request to '{}'", domain);
return;
}
if (splitDomain[0].equals("binding")) {
if (splitDomain[1].equals("network")) {
if (action.equals("Heal")) {
if (networkMonitor != null) {
networkMonitor.rescheduleHeal();
}
}
if (action.equals("Include") || action.equals("Exclude")) {
// Only do include/exclude if it's not already in progress
if(inclusion == false && exclusion == false) {
if (action.equals("Include")) {
inclusion = true;
zController.requestAddNodesStart();
setInclusionTimer();
}
if (action.equals("Exclude")) {
exclusion = true;
zController.requestRemoveNodesStart();
setInclusionTimer();
}
}
else {
logger.debug("Exclusion/Inclusion already in progress.");
}
}
}
}
if (splitDomain[0].equals("nodes")) {
int nodeId = Integer.parseInt(splitDomain[1].substring(4));
// Get the node - if it exists
ZWaveNode node = zController.getNode(nodeId);
if (node == null) {
logger.error("NODE {}: Error finding node in doAction", nodeId);
return;
}
if (splitDomain.length == 2) {
if (action.equals("Heal")) {
logger.debug("NODE {}: Heal node", nodeId);
if (networkMonitor != null) {
networkMonitor.startNodeHeal(nodeId);
}
}
if (action.equals("Save")) {
logger.debug("NODE {}: Saving node", nodeId);
// Write the node to disk
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.SerializeNode(node);
}
if (action.equals("Initialise")) {
logger.debug("NODE {}: re-initialising node", nodeId);
// Delete the saved XML
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.DeleteNode(nodeId);
this.zController.reinitialiseNode(nodeId);
}
if (action.equals("Delete")) {
logger.debug("NODE {}: Delete node", nodeId);
this.zController.requestRemoveFailedNode(nodeId);
}
// Return here as afterwards we assume there are more elements
// in the domain array
return;
}
if (splitDomain[2].equals("parameters")) {
ZWaveConfigurationCommandClass configurationCommandClass = (ZWaveConfigurationCommandClass) node
.getCommandClass(CommandClass.CONFIGURATION);
if (configurationCommandClass == null) {
return;
}
if (action.equals("Refresh")) {
logger.debug("NODE {}: Refresh parameters", nodeId);
ZWaveProductDatabase database = new ZWaveProductDatabase();
if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == false) {
return;
}
List<ZWaveDbConfigurationParameter> configList = database.getProductConfigParameters();
// Request all parameters for this node
for (ZWaveDbConfigurationParameter parameter : configList) {
this.zController.sendData(configurationCommandClass.getConfigMessage(parameter.Index));
}
}
}
if (splitDomain[2].equals("wakeup")) {
if (action.equals("Refresh")) {
// Only update if we support the wakeup class
ZWaveWakeUpCommandClass wakeupCommandClass = (ZWaveWakeUpCommandClass) node
.getCommandClass(CommandClass.WAKE_UP);
if (wakeupCommandClass == null) {
return;
}
logger.debug("NODE {}: Refresh wakeup capabilities", nodeId);
// Request the wakeup interval for this node
this.zController.sendData(wakeupCommandClass.getIntervalMessage());
// Request the wakeup parameters for this node
this.zController.sendData(wakeupCommandClass.getIntervalCapabilitiesMessage());
}
}
if (splitDomain[2].equals("neighbors")) {
if (action.equals("Refresh")) {
// this.zController.requestNodeNeighborUpdate(nodeId);
this.zController.requestNodeRoutingInfo(nodeId);// .requestNodeNeighborUpdate(nodeId);
}
}
if (splitDomain[2].equals("associations")) {
if (action.equals("Refresh")) {
// Make sure the association class is supported
ZWaveAssociationCommandClass associationCommandClass = (ZWaveAssociationCommandClass) node
.getCommandClass(CommandClass.ASSOCIATION);
if (associationCommandClass == null) {
return;
}
logger.debug("NODE {}: Refresh associations", nodeId);
ZWaveProductDatabase database = new ZWaveProductDatabase();
if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == false) {
logger.error("NODE {}: Error in doAction - no database found", nodeId);
return;
}
if (splitDomain.length == 3) {
// Request all groups for this node
associationCommandClass.getAllAssociations();
} else if (splitDomain.length == 4) {
// Request a single group
int nodeArg = Integer.parseInt(splitDomain[3].substring(11));
this.zController.sendData(associationCommandClass.getAssociationMessage(nodeArg));
}
}
}
}
}
@Override
public void doSet(String domain, String value) {
logger.debug("doSet domain '{}' to '{}'", domain, value);
String[] splitDomain = domain.split("/");
// If the controller isn't ready, then ignore any requests
if(zController.isConnected() == false) {
logger.debug("Controller not ready - Ignoring request to '{}'", domain);
return;
}
// There must be at least 2 components to the domain
if (splitDomain.length < 2) {
logger.error("Error malformed domain in doSet '{}'", domain);
return;
}
if (splitDomain[0].equals("nodes")) {
int nodeId = Integer.parseInt(splitDomain[1].substring(4));
ZWaveNode node = zController.getNode(nodeId);
if (node == null) {
logger.error("Error finding node in doSet '{}'", domain);
return;
}
// TODO: Should we check that the node is finished initializing
ZWaveProductDatabase database = new ZWaveProductDatabase();
if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == false) {
logger.error("NODE {}: Error in doSet - no database found", nodeId);
return;
}
if (splitDomain.length == 3) {
if (splitDomain[2].equals("Name")) {
node.setName(value);
}
if (splitDomain[2].equals("Location")) {
node.setLocation(value);
}
if (splitDomain[2].equals("Switch All")) {
ZWaveSwitchAllCommandClass switchAllCommandClass = (ZWaveSwitchAllCommandClass) node
.getCommandClass(CommandClass.SWITCH_ALL);
if (switchAllCommandClass == null) {
logger.error("NODE {}: Error getting switchAllCommandClass in doSet", nodeId);
return;
}
// Set the switch all mode
int mode = Integer.parseInt(value);
PendingCfg.Add(ZWaveSwitchAllCommandClass.CommandClass.SWITCH_ALL.getKey(), node.getNodeId(), 0, mode);
SerialMessage msg = switchAllCommandClass.setValueMessage(mode);
this.zController.sendData(msg);
// And request a read-back
this.zController.sendData(switchAllCommandClass.getValueMessage());
}
// Write the node to disk
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.SerializeNode(node);
} else if (splitDomain.length == 4) {
if (splitDomain[2].equals("parameters")) {
ZWaveConfigurationCommandClass configurationCommandClass = (ZWaveConfigurationCommandClass) node
.getCommandClass(CommandClass.CONFIGURATION);
if (configurationCommandClass == null) {
logger.error("NODE {}: Error getting configurationCommandClass in doSet", nodeId);
return;
}
int paramIndex = Integer.parseInt(splitDomain[3].substring(13));
List<ZWaveDbConfigurationParameter> configList = database.getProductConfigParameters();
// Get the size
int size = 1;
for (ZWaveDbConfigurationParameter parameter : configList) {
if (parameter.Index == paramIndex) {
size = parameter.Size;
break;
}
}
logger.debug("Set parameter index '{}' to '{}'", paramIndex, value);
PendingCfg.Add(ZWaveCommandClass.CommandClass.CONFIGURATION.getKey(), nodeId, paramIndex, Integer.valueOf(value));
ConfigurationParameter configurationParameter = new ConfigurationParameter(paramIndex,
Integer.valueOf(value), size);
// Set the parameter
this.zController.sendData(configurationCommandClass.setConfigMessage(configurationParameter));
// And request a read-back
this.zController.sendData(configurationCommandClass.getConfigMessage(paramIndex));
}
if (splitDomain[2].equals("wakeup")) {
ZWaveWakeUpCommandClass wakeupCommandClass = (ZWaveWakeUpCommandClass) node
.getCommandClass(CommandClass.WAKE_UP);
if (wakeupCommandClass == null) {
logger.error("NODE {}: Error getting wakeupCommandClass in doSet", nodeId);
return;
}
logger.debug("NODE {}: Set wakeup interval to '{}'", nodeId, value);
// Add this as a pending transaction
PendingCfg.Add(ZWaveCommandClass.CommandClass.WAKE_UP.getKey(), node.getNodeId(), Integer.parseInt(value));
// Set the wake-up interval
this.zController.sendData(wakeupCommandClass.setInterval(Integer.parseInt(value)));
// And request a read-back
this.zController.sendData(wakeupCommandClass.getIntervalMessage());
}
if (splitDomain[2].equals("controller")) {
if(splitDomain[3].equals("Type")) {
ZWaveDeviceType type = ZWaveDeviceType.fromString(value);
logger.error("NODE {}: Setting controller type to {}", nodeId, type.toString());
// ZW_EnableSUC and ZW_SetSUCNodeID
}
}
} else if (splitDomain.length == 5) {
if (splitDomain[2].equals("associations")) {
ZWaveAssociationCommandClass associationCommandClass = (ZWaveAssociationCommandClass) node
.getCommandClass(CommandClass.ASSOCIATION);
if (associationCommandClass == null) {
logger.error("NODE {}: Error getting associationCommandClass in doSet", nodeId);
return;
}
int assocId = Integer.parseInt(splitDomain[3].substring(11));
int assocArg = Integer.parseInt(splitDomain[4].substring(4));
if (value.equalsIgnoreCase("true")) {
PendingCfg.Add(ZWaveCommandClass.CommandClass.ASSOCIATION.getKey(), nodeId, assocId, assocArg, 1);
logger.debug("Add association index '{}' to '{}'", assocId, assocArg);
this.zController.sendData(associationCommandClass.setAssociationMessage(assocId, assocArg));
} else {
PendingCfg.Add(ZWaveCommandClass.CommandClass.ASSOCIATION.getKey(), nodeId, assocId, assocArg, 0);
logger.debug("Remove association index '{}' to '{}'", assocId, assocArg);
this.zController.sendData(associationCommandClass.removeAssociationMessage(assocId, assocArg));
}
// Request an update to the group
this.zController.sendData(associationCommandClass.getAssociationMessage(assocId));
// When associations change, we should ensure routes are configured
// So, let's start a network heal - just for this node right now
if(networkMonitor != null) {
networkMonitor.startNodeHeal(nodeId);
}
}
}
}
}
/**
* Handle the inclusion/exclusion event. This just notifies the GUI.
* @param event
*/
void handleInclusionEvent(ZWaveInclusionEvent event) {
boolean endInclusion = false;
switch(event.getEvent()) {
case IncludeStart:
break;
case IncludeSlaveFound:
break;
case IncludeControllerFound:
break;
case IncludeFail:
endInclusion = true;
break;
case IncludeDone:
endInclusion = true;
break;
case ExcludeStart:
break;
case ExcludeSlaveFound:
break;
case ExcludeControllerFound:
break;
case ExcludeFail:
endInclusion = true;
break;
case ExcludeDone:
endInclusion = true;
break;
}
if(endInclusion) {
stopInclusionTimer();
}
}
/**
* Event handler method for incoming Z-Wave events.
*
* @param event
* the incoming Z-Wave event.
*/
@Override
public void ZWaveIncomingEvent(ZWaveEvent event) {
if (event instanceof ZWaveConfigurationParameterEvent) {
// Write the node to disk
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.SerializeNode(zController.getNode(event.getNodeId()));
// We've received an updated configuration parameter
// See if this is something in our 'pending' list and remove it
PendingCfg.Remove(ZWaveCommandClass.CommandClass.CONFIGURATION.getKey(), event.getNodeId(), ((ZWaveConfigurationParameterEvent) event).getParameter().getIndex());
return;
}
if (event instanceof ZWaveAssociationEvent) {
// Write the node to disk
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.SerializeNode(zController.getNode(event.getNodeId()));
// We've received an updated association group
// See if this is something in our 'pending' list and remove it
for(ZWaveNode node : zController.getNodes()) {
PendingCfg.Remove(ZWaveCommandClass.CommandClass.ASSOCIATION.getKey(), event.getNodeId(), ((ZWaveAssociationEvent) event).getGroup(), node.getNodeId());
}
return;
}
if (event instanceof ZWaveWakeUpCommandClass.ZWaveWakeUpEvent) {
// We only care about the wake-up report
if(((ZWaveWakeUpCommandClass.ZWaveWakeUpEvent) event).getEvent() != ZWaveWakeUpCommandClass.WAKE_UP_INTERVAL_REPORT)
return;
// Write the node to disk
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.SerializeNode(zController.getNode(event.getNodeId()));
// Remove this node from the pending list
PendingCfg.Remove(ZWaveCommandClass.CommandClass.WAKE_UP.getKey(), event.getNodeId());
return;
}
if (event instanceof ZWaveSwitchAllCommandClass.ZWaveSwitchAllModeEvent) {
ZWaveSwitchAllCommandClass.ZWaveSwitchAllModeEvent e = (ZWaveSwitchAllCommandClass.ZWaveSwitchAllModeEvent) event;
// Write the node to disk
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.SerializeNode(zController.getNode(event.getNodeId()));
// Remove this node from the pending list
PendingCfg.Remove(ZWaveCommandClass.CommandClass.SWITCH_ALL.getKey(), e.getNodeId());
return;
}
if (event instanceof ZWaveInclusionEvent) {
handleInclusionEvent((ZWaveInclusionEvent)event);
}
}
// The following timer class implements a re-triggerable timer to stop the inclusion
// mode after 30 seconds.
private class InclusionTimerTask extends TimerTask {
@Override
public void run() {
logger.debug("Ending inclusion mode.");
stopInclusionTimer();
}
}
public synchronized void setInclusionTimer() {
// Stop any existing timer
if(timerTask != null) {
timerTask.cancel();
}
// Create the timer task
timerTask = new InclusionTimerTask();
// Start the timer for 30 seconds
timer.schedule(timerTask, 30000);
}
/**
* Stops any pending inclusion/exclusion.
* Resets flags, and signals to controller.
*/
public synchronized void stopInclusionTimer() {
logger.debug("Stopping inclusion timer.");
if(inclusion) {
zController.requestAddNodesStop();
}
else if(exclusion) {
zController.requestRemoveNodesStop();
}
else {
logger.error("Neither inclusion nor exclusion was active!");
}
inclusion = false;
exclusion = false;
// Stop the timer
if(timerTask != null) {
timerTask.cancel();
timerTask = null;
}
}
/**
* The PendingConfiguration class holds information on outstanding requests
* When the binding sends a configuration request to a device, we hold a copy
* of the new value here so that any requests for the current value can take account
* of the pending request.
* When the information is updated, we remove the request from the pending list.
* @author Chris Jackson
*
*/
public class PendingConfiguration {
public class Cfg {
int key;
int node;
int parameter;
int argument;
int value;
}
List<Cfg> CfgList = new ArrayList<Cfg>();
void Add(int key, int node, int value) {
Add(key, node, 0, 0, value);
}
void Add(int key, int node, int parameter, int value) {
Add(key, node, parameter, 0, value);
}
void Add(int key, int node, int parameter, int argument, int value) {
for(Cfg i : CfgList) {
if(i.key == key && i.node == node && i.argument == argument && i.parameter == parameter) {
i.value = value;
return;
}
}
Cfg n = new Cfg();
n.key = key;
n.node = node;
n.parameter = parameter;
n.argument = argument;
n.value = value;
CfgList.add(n);
}
void Remove(int key, int node) {
Remove(key, node, 0, 0);
}
void Remove(int key, int node, int parameter) {
Remove(key, node, parameter, 0);
}
void Remove(int key, int node, int parameter, int argument) {
for(Cfg i : CfgList) {
if(i.key == key && i.node == node && i.argument == argument && i.parameter == parameter) {
CfgList.remove(i);
return;
}
}
}
Integer Get(int key, int node) {
return Get(key, node, 0, 0);
}
Integer Get(int key, int node, int parameter) {
return Get(key, node, parameter, 0);
}
Integer Get(int key, int node, int parameter, int argument) {
for(Cfg i : CfgList) {
if(i.key == key && i.node == node && i.argument == argument && i.parameter == parameter) {
return i.value;
}
}
return null;
}
}
}
|
// $Id: Digest.java,v 1.17 2005/10/03 13:25:26 belaban Exp $
package org.jgroups.protocols.pbcast;
import EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.Address;
import org.jgroups.Global;
import org.jgroups.util.Streamable;
import org.jgroups.util.Util;
import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* A message digest, which is used by the PBCAST layer for gossiping (also used by NAKACK for
* keeping track of current seqnos for all members). It contains pairs of senders and a range of seqnos
* (low and high), where each sender is associated with its highest and lowest seqnos seen so far. That
* is, the lowest seqno which was not yet garbage-collected and the highest that was seen so far and is
* deliverable (or was already delivered) to the application. A range of [0 - 0] means no messages have
* been received yet.
* <p> April 3 2001 (bela): Added high_seqnos_seen member. It is used to disseminate
* information about the last (highest) message M received from a sender P. Since we might be using a
* negative acknowledgment message numbering scheme, we would never know if the last message was
* lost. Therefore we periodically gossip and include the last message seqno. Members who haven't seen
* it (e.g. because msg was dropped) will request a retransmission. See DESIGN for details.
* @author Bela Ban
*/
public class Digest implements Externalizable, Streamable {
/** Map<Address, Entry> */
Map senders=null;
protected static final Log log=LogFactory.getLog(Digest.class);
static final boolean warn=log.isWarnEnabled();
public Digest() {
} // used for externalization
public Digest(int size) {
senders=createSenders(size);
}
public boolean equals(Object obj) {
if(obj == null)
return false;
Digest other=(Digest)obj;
if(senders == null && other.senders == null)
return true;
return senders.equals(other.senders);
}
public void add(Address sender, long low_seqno, long high_seqno) {
add(sender, low_seqno, high_seqno, -1);
}
public void add(Address sender, long low_seqno, long high_seqno, long high_seqno_seen) {
add(sender, new Entry(low_seqno, high_seqno, high_seqno_seen));
}
private void add(Address sender, Entry entry) {
if(sender == null || entry == null) {
if(log.isErrorEnabled())
log.error("sender (" + sender + ") or entry (" + entry + ")is null, will not add entry");
return;
}
Object retval=senders.put(sender, entry);
if(retval != null && warn)
log.warn("entry for " + sender + " was overwritten with " + entry);
}
public void add(Digest d) {
if(d != null) {
Map.Entry entry;
Address key;
Entry val;
for(Iterator it=d.senders.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=(Address)entry.getKey();
val=(Entry)entry.getValue();
add(key, val.low_seqno, val.high_seqno, val.high_seqno_seen);
}
}
}
public void replace(Digest d) {
if(d != null) {
Map.Entry entry;
Address key;
Entry val;
clear();
for(Iterator it=d.senders.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=(Address)entry.getKey();
val=(Entry)entry.getValue();
add(key, val.low_seqno, val.high_seqno, val.high_seqno_seen);
}
}
}
public Entry get(Address sender) {
return (Entry)senders.get(sender);
}
public boolean set(Address sender, long low_seqno, long high_seqno, long high_seqno_seen) {
Entry entry=(Entry)senders.get(sender);
if(entry == null)
return false;
entry.low_seqno=low_seqno;
entry.high_seqno=high_seqno;
entry.high_seqno_seen=high_seqno_seen;
return true;
}
/**
* Adds a digest to this digest. This digest must have enough space to add the other digest; otherwise an error
* message will be written. For each sender in the other digest, the merge() method will be called.
*/
public void merge(Digest d) {
if(d == null) {
if(log.isErrorEnabled()) log.error("digest to be merged with is null");
return;
}
Map.Entry entry;
Address sender;
Entry val;
for(Iterator it=d.senders.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
sender=(Address)entry.getKey();
val=(Entry)entry.getValue();
if(val != null) {
merge(sender, val.low_seqno, val.high_seqno, val.high_seqno_seen);
}
}
}
/**
* Similar to add(), but if the sender already exists, its seqnos will be modified (no new entry) as follows:
* <ol>
* <li>this.low_seqno=min(this.low_seqno, low_seqno)
* <li>this.high_seqno=max(this.high_seqno, high_seqno)
* <li>this.high_seqno_seen=max(this.high_seqno_seen, high_seqno_seen)
* </ol>
* If the sender doesn not exist, a new entry will be added (provided there is enough space)
*/
public void merge(Address sender, long low_seqno, long high_seqno, long high_seqno_seen) {
if(sender == null) {
if(log.isErrorEnabled()) log.error("sender == null");
return;
}
Entry entry=(Entry)senders.get(sender);
if(entry == null) {
add(sender, low_seqno, high_seqno, high_seqno_seen);
}
else {
if(low_seqno < entry.low_seqno)
entry.low_seqno=low_seqno;
if(high_seqno > entry.high_seqno)
entry.high_seqno=high_seqno;
if(high_seqno_seen > entry.high_seqno_seen)
entry.high_seqno_seen=high_seqno_seen;
}
}
public boolean contains(Address sender) {
return senders.containsKey(sender);
}
/**
* Compares two digests and returns true if the senders are the same, otherwise false.
* @param other
* @return True if senders are the same, otherwise false.
*/
public boolean sameSenders(Digest other) {
if(other == null) return false;
if(this.senders == null || other.senders == null) return false;
if(this.senders.size() != other.senders.size()) return false;
Set my_senders=senders.keySet(), other_senders=other.senders.keySet();
return my_senders.equals(other_senders);
}
/**
* Increments the sender's high_seqno by 1.
*/
public void incrementHighSeqno(Address sender) {
Entry entry=(Entry)senders.get(sender);
if(entry == null)
return;
entry.high_seqno++;
}
public int size() {
return senders.size();
}
/**
* Resets the seqnos for the sender at 'index' to 0. This happens when a member has left the group,
* but it is still in the digest. Resetting its seqnos ensures that no-one will request a message
* retransmission from the dead member.
*/
public void resetAt(Address sender) {
Entry entry=(Entry)senders.get(sender);
if(entry != null)
entry.reset();
}
public void clear() {
senders.clear();
}
public long lowSeqnoAt(Address sender) {
Entry entry=(Entry)senders.get(sender);
if(entry == null)
return -1;
else
return entry.low_seqno;
}
public long highSeqnoAt(Address sender) {
Entry entry=(Entry)senders.get(sender);
if(entry == null)
return -1;
else
return entry.high_seqno;
}
public long highSeqnoSeenAt(Address sender) {
Entry entry=(Entry)senders.get(sender);
if(entry == null)
return -1;
else
return entry.high_seqno_seen;
}
public void setHighSeqnoAt(Address sender, long high_seqno) {
Entry entry=(Entry)senders.get(sender);
if(entry != null)
entry.high_seqno=high_seqno;
}
public void setHighSeqnoSeenAt(Address sender, long high_seqno_seen) {
Entry entry=(Entry)senders.get(sender);
if(entry != null)
entry.high_seqno_seen=high_seqno_seen;
}
public void setHighestDeliveredAndSeenSeqnos(Address sender, long high_seqno, long high_seqno_seen) {
Entry entry=(Entry)senders.get(sender);
if(entry != null) {
entry.high_seqno=high_seqno;
entry.high_seqno_seen=high_seqno_seen;
}
}
public Digest copy() {
Digest ret=new Digest(senders.size());
Map.Entry entry;
Entry tmp;
for(Iterator it=senders.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
tmp=(Entry)entry.getValue();
ret.add((Address)entry.getKey(), tmp.low_seqno, tmp.high_seqno, tmp.high_seqno_seen);
}
return ret;
}
public String toString() {
StringBuffer sb=new StringBuffer();
boolean first=true;
if(senders == null) return "[]";
Map.Entry entry;
Address key;
Entry val;
for(Iterator it=senders.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=(Address)entry.getKey();
val=(Entry)entry.getValue();
if(!first) {
sb.append(", ");
}
else {
first=false;
}
sb.append(key).append(": ").append('[').append(val.low_seqno).append(" : ");
sb.append(val.high_seqno);
if(val.high_seqno_seen >= 0)
sb.append(" (").append(val.high_seqno_seen).append(")");
sb.append("]");
}
return sb.toString();
}
public String printHighSeqnos() {
StringBuffer sb=new StringBuffer();
boolean first=true;
Map.Entry entry;
Address key;
Entry val;
for(Iterator it=senders.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=(Address)entry.getKey();
val=(Entry)entry.getValue();
if(!first) {
sb.append(", ");
}
else {
sb.append('[');
first=false;
}
sb.append(key).append("#").append(val.high_seqno);
}
sb.append(']');
return sb.toString();
}
public String printHighSeqnosSeen() {
StringBuffer sb=new StringBuffer();
boolean first=true;
Map.Entry entry;
Address key;
Entry val;
for(Iterator it=senders.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=(Address)entry.getKey();
val=(Entry)entry.getValue();
if(!first) {
sb.append(", ");
}
else {
sb.append('[');
first=false;
}
sb.append(key).append("#").append(val.high_seqno_seen);
}
sb.append(']');
return sb.toString();
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(senders);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
senders=(Map)in.readObject();
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeShort(senders.size());
Map.Entry entry;
Address key;
Entry val;
for(Iterator it=senders.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=(Address)entry.getKey();
val=(Entry)entry.getValue();
Util.writeAddress(key, out);
out.writeLong(val.low_seqno);
out.writeLong(val.high_seqno);
out.writeLong(val.high_seqno_seen);
}
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
short size=in.readShort();
senders=createSenders(size);
Address key;
for(int i=0; i < size; i++) {
key=Util.readAddress(in);
add(key, in.readLong(), in.readLong(), in.readLong());
}
}
public long serializedSize() {
long retval=Global.SHORT_SIZE; // number of elements in 'senders'
if(senders.size() > 0) {
Address addr=(Address)senders.keySet().iterator().next();
int len=addr.size() +
2 * Global.BYTE_SIZE; // presence byte, IpAddress vs other address
len+=3 * Global.LONG_SIZE; // 3 longs in one Entry
retval+=len * senders.size();
}
return retval;
}
private Map createSenders(int size) {
return new ConcurrentReaderHashMap(size);
}
/**
* Class keeping track of the lowest and highest sequence numbers delivered, and the highest
* sequence numbers received, per member
*/
public static class Entry {
public long low_seqno, high_seqno, high_seqno_seen=-1;
public Entry(long low_seqno, long high_seqno, long high_seqno_seen) {
this.low_seqno=low_seqno;
this.high_seqno=high_seqno;
this.high_seqno_seen=high_seqno_seen;
}
public Entry(long low_seqno, long high_seqno) {
this.low_seqno=low_seqno;
this.high_seqno=high_seqno;
}
public Entry(Entry other) {
if(other != null) {
low_seqno=other.low_seqno;
high_seqno=other.high_seqno;
high_seqno_seen=other.high_seqno_seen;
}
}
public boolean equals(Object obj) {
Entry other=(Entry)obj;
return low_seqno == other.low_seqno && high_seqno == other.high_seqno && high_seqno_seen == other.high_seqno_seen;
}
public String toString() {
return new StringBuffer("low=").append(low_seqno).append(", high=").append(high_seqno).
append(", highest seen=").append(high_seqno_seen).toString();
}
public void reset() {
low_seqno=high_seqno=0;
high_seqno_seen=-1;
}
}
}
|
package org.eclipse.smarthome.core.thing.setup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.core.items.ActiveItem;
import org.eclipse.smarthome.core.items.GenericItem;
import org.eclipse.smarthome.core.items.GroupItem;
import org.eclipse.smarthome.core.items.Item;
import org.eclipse.smarthome.core.items.ItemFactory;
import org.eclipse.smarthome.core.items.ItemRegistry;
import org.eclipse.smarthome.core.thing.Channel;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingRegistry;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.core.thing.UID;
import org.eclipse.smarthome.core.thing.binding.ThingHandlerFactory;
import org.eclipse.smarthome.core.thing.internal.ThingManager;
import org.eclipse.smarthome.core.thing.link.AbstractLink;
import org.eclipse.smarthome.core.thing.link.ItemChannelLink;
import org.eclipse.smarthome.core.thing.link.ItemChannelLinkRegistry;
import org.eclipse.smarthome.core.thing.link.ItemThingLink;
import org.eclipse.smarthome.core.thing.link.ItemThingLinkRegistry;
import org.eclipse.smarthome.core.thing.type.ChannelGroupDefinition;
import org.eclipse.smarthome.core.thing.type.ChannelType;
import org.eclipse.smarthome.core.thing.type.ThingType;
import org.eclipse.smarthome.core.thing.type.ThingTypeRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link ThingSetupManager} provides various method to manage things. In
* contrast to the {@link ThingRegistry}, the {@link ThingManager} also creates
* Items and Links automatically and removes it, when the according thing is
* removed.
*
* @author Dennis Nobel - Initial contribution
* @author Alex Tugarev - addThing operation returns created Thing instance
*/
public class ThingSetupManager {
public static final String TAG_CHANNEL_GROUP = "channel-group";
public static final String TAG_HOME_GROUP = "home-group";
public static final String TAG_THING = "thing";
private ItemChannelLinkRegistry itemChannelLinkRegistry;
private List<ItemFactory> itemFactories = new CopyOnWriteArrayList<>();
private ItemRegistry itemRegistry;
private ItemThingLinkRegistry itemThingLinkRegistry;
private final Logger logger = LoggerFactory.getLogger(ThingSetupManager.class);
private List<ThingHandlerFactory> thingHandlerFactories = new CopyOnWriteArrayList<>();
private ThingRegistry thingRegistry;
private ThingTypeRegistry thingTypeRegistry;
/**
* Adds a group to the system with the a 'home-group' tag.
*
* @param itemName
* name of group to be added
* @param label
* label of the group to be added
* @return created {@link GroupItem} instance
*/
public GroupItem addHomeGroup(String itemName, String label) {
GroupItem groupItem = new GroupItem(itemName);
groupItem.setLabel(label);
groupItem.addTag(TAG_HOME_GROUP);
itemRegistry.add(groupItem);
return groupItem;
}
/**
* Adds a thing without a label, without group names, but enables all
* channels.
*
* See {@link ThingSetupManager#addThing(ThingUID, Configuration, ThingUID, String, List, boolean)}
*
* @return created {@link Thing} instance (can be null)
*/
public Thing addThing(ThingUID thingUID, Configuration configuration, ThingUID bridgeUID) {
return addThing(thingUID, configuration, bridgeUID, null);
}
/**
* Adds a thing without group names, but enables all channels.
*
* See {@link ThingSetupManager#addThing(ThingUID, Configuration, ThingUID, String, List, boolean)}
*
* @return created {@link Thing} instance (can be null)
*/
public Thing addThing(ThingUID thingUID, Configuration configuration, ThingUID bridgeUID, String label) {
return addThing(thingUID, configuration, bridgeUID, label, new ArrayList<String>());
}
/**
* Adds a thing and enables all channels.
*
* See {@link ThingSetupManager#addThing(ThingUID, Configuration, ThingUID, String, List, boolean)}
*
* @return created {@link Thing} instance (can be null)
*/
public Thing addThing(ThingUID thingUID, Configuration configuration, ThingUID bridgeUID, String label,
List<String> groupNames) {
return addThing(thingUID, configuration, bridgeUID, label, groupNames, true);
}
/**
* Adds a new thing to the system and creates the according items and links.
*
* @param thingUID
* UID of the thing (must not be null)
* @param configuration
* configuration (must not be null)
* @param bridgeUID
* bridge UID (can be null)
* @param label
* label (can be null)
* @param groupNames
* list of group names, in which the thing should be added as
* member (must not be null)
* @param enableChannels
* defines if all not 'advanced' channels should be enabled
* directly
* @return created {@link Thing} instance (can be null)
*/
public Thing addThing(ThingUID thingUID, Configuration configuration, ThingUID bridgeUID, String label,
List<String> groupNames, boolean enableChannels) {
ThingTypeUID thingTypeUID = thingUID.getThingTypeUID();
Thing thing = createThing(thingUID, configuration, bridgeUID, thingTypeUID);
if (thing == null) {
logger.warn("Cannot create thing. No binding found that supports creating a thing" + " of type {}.",
thingTypeUID);
return null;
}
String itemName = toItemName(thing.getUID());
GroupItem groupItem = new GroupItem(itemName);
groupItem.addTag(TAG_THING);
groupItem.setLabel(label);
groupItem.addGroupNames(groupNames);
thingRegistry.add(thing);
itemRegistry.add(groupItem);
itemThingLinkRegistry.add(new ItemThingLink(itemName, thing.getUID()));
ThingType thingType = thingTypeRegistry.getThingType(thingTypeUID);
if (thingType != null) {
List<ChannelGroupDefinition> channelGroupDefinitions = thingType.getChannelGroupDefinitions();
for (ChannelGroupDefinition channelGroupDefinition : channelGroupDefinitions) {
GroupItem channelGroupItem = new GroupItem(getChannelGroupItemName(itemName,
channelGroupDefinition.getId()));
channelGroupItem.addTag(TAG_CHANNEL_GROUP);
channelGroupItem.addGroupName(itemName);
itemRegistry.add(channelGroupItem);
}
}
if (enableChannels) {
List<Channel> channels = thing.getChannels();
for (Channel channel : channels) {
ChannelType channelType = this.thingTypeRegistry.getChannelType(channel.getUID());
if (channelType != null && !channelType.isAdvanced()) {
enableChannel(channel.getUID());
} else {
logger.warn("Could not enable channel '{}', because no channel type was found.", channel.getUID());
}
}
}
return thing;
}
/**
* Adds the given item to the given group.
*
* @param itemName
* item name (must not be null)
* @param groupItemName
* group item name (must not be null)
*/
public void addToHomeGroup(String itemName, String groupItemName) {
ActiveItem item = (ActiveItem) this.itemRegistry.get(itemName);
if (item != null) {
item.addGroupName(groupItemName);
this.itemRegistry.update(item);
} else {
logger.warn("Could not add item '{}' to group '{}', because thing is not linked.", itemName, groupItemName);
}
}
/**
* Adds a thing identified by the given thing UID to the given group.
*
* @param thingUID
* thing UID (must not be null)
* @param groupItemName
* group item name (must not be null)
*/
public void addToHomeGroup(ThingUID thingUID, String groupItemName) {
String linkedItem = getFirstLinkedItem(thingUID);
if (linkedItem != null) {
addToHomeGroup(linkedItem, groupItemName);
} else {
logger.warn("Could not add thing '{}' to group '{}', because thing is not linked.", thingUID, groupItemName);
}
}
/**
* Disables the channel with the given UID (removes the linked item).
*
* @param channelUID
* channel UID (must not be null)
*/
public void disableChannel(ChannelUID channelUID) {
Collection<ItemChannelLink> itemChannelLinks = this.itemChannelLinkRegistry.getAll();
for (ItemChannelLink itemChannelLink : itemChannelLinks) {
if (itemChannelLink.getUID().equals(channelUID)) {
String itemName = itemChannelLink.getItemName();
itemRegistry.remove(itemName);
itemChannelLinkRegistry.remove(itemChannelLink.getID());
}
}
}
/**
* Enables the channel with the given UID (adds a linked item).
*
* @param channelUID
* channel UID (must not be null)
*/
public void enableChannel(ChannelUID channelUID) {
ChannelType channelType = thingTypeRegistry.getChannelType(channelUID);
if (channelType != null) {
String itemType = channelType.getItemType();
ItemFactory itemFactory = getItemFactoryForItemType(itemType);
if (itemFactory != null) {
String itemName = toItemName(channelUID);
GenericItem item = itemFactory.createItem(itemType, itemName);
if (item != null) {
String thingGroupItemName = getThingGroupItemName(channelUID);
if (thingGroupItemName != null) {
if (!channelUID.isInGroup()) {
item.addGroupName(thingGroupItemName);
} else {
item.addGroupName(getChannelGroupItemName(thingGroupItemName, channelUID.getGroupId()));
}
}
item.addTags(channelType.getTags());
item.setCategory(channelType.getCategory());
this.itemRegistry.add(item);
this.itemChannelLinkRegistry.add(new ItemChannelLink(itemName, channelUID));
}
}
} else {
logger.warn("Could not enable channel '{}', because no channel type was found.", channelUID);
}
}
/**
* Returns a list of all group items (items with tag 'home-group').
*
* @return list of all group items (can not be null)
*/
public Collection<GroupItem> getHomeGroups() {
List<GroupItem> homeGroupItems = new ArrayList<>();
for (Item item : this.itemRegistry.getAll()) {
if (item instanceof GroupItem && ((GroupItem) item).hasTag(TAG_HOME_GROUP)) {
homeGroupItems.add((GroupItem) item);
}
}
return homeGroupItems;
}
/**
* Returns a thing for a given UID.
*
* @return thing or null, if thing with UID does not exists
*/
public Thing getThing(ThingUID thingUID) {
return this.thingRegistry.get(thingUID);
}
/**
* Returns all things.
*
* @return things
*/
public Collection<Thing> getThings() {
return thingRegistry.getAll();
}
/**
* Removes the given item from the given group.
*
* @param itemName
* item name (must not be null)
* @param groupItemName
* group item name (must not be null)
*/
public void removeFromHomeGroup(String itemName, String groupItemName) {
ActiveItem item = (ActiveItem) this.itemRegistry.get(itemName);
item.removeGroupName(groupItemName);
this.itemRegistry.update(item);
}
/**
* Removes the thing identified by the given thing UID from the given group.
*
* @param thingUID
* thing UID (must not be null)
* @param groupItemName
* group item name (must not be null)
*/
public void removeFromHomeGroup(ThingUID thingUID, String groupItemName) {
String linkedItem = getFirstLinkedItem(thingUID);
if (linkedItem != null) {
removeFromHomeGroup(linkedItem, groupItemName);
}
}
/**
* Removes the home group identified by the given itemName from the system.
*
* @param itemName
* name of group to be added
* @param label
* label of the group to be added
*/
public void removeHomeGroup(String itemName) {
itemRegistry.remove(itemName);
}
public void removeThing(ThingUID thingUID) {
String itemName = toItemName(thingUID);
thingRegistry.remove(thingUID);
itemRegistry.remove(itemName, true);
itemThingLinkRegistry.remove(AbstractLink.getIDFor(itemName, thingUID));
itemChannelLinkRegistry.removeLinksForThing(thingUID);
}
/**
* Sets the label for a given thing UID.
*
* @param thingUID
* thing UID (must not be null)
* @param label
* label (can be null)
*/
public void setLabel(ThingUID thingUID, String label) {
Thing thing = thingRegistry.get(thingUID);
GroupItem groupItem = thing.getLinkedItem();
if (groupItem != null) {
if (label != null && label.equals(groupItem.getLabel())) {
return;
}
groupItem.setLabel(label);
itemRegistry.update(groupItem);
} else {
throw new IllegalArgumentException("No item is linked with thing '" + thingUID.toString() + "'.");
}
}
/**
* Sets the given label for the home group identified by the given item name.
*
* @param itemName the name of the home group
* @param label the new label for the home group
*/
public void setHomeGroupLabel(String itemName, String label) {
GroupItem groupItem = (GroupItem) itemRegistry.get(itemName);
if (groupItem == null) {
throw new IllegalArgumentException("No group item found with item name " + itemName);
}
groupItem.setLabel(label);
itemRegistry.update(groupItem);
}
/**
* Updates an item.
*
* @param item
* item (must not be null)
*/
public void updateItem(Item item) {
itemRegistry.update(item);
}
/**
* Updates a thing.
*
* @param thing
* thing (must not be null)
*/
public void updateThing(Thing thing) {
this.thingRegistry.update(thing);
}
protected void addItemFactory(ItemFactory itemFactory) {
this.itemFactories.add(itemFactory);
}
protected void addThingHandlerFactory(ThingHandlerFactory thingHandlerFactory) {
this.thingHandlerFactories.add(thingHandlerFactory);
}
protected void removeItemFactory(ItemFactory itemFactory) {
this.itemFactories.remove(itemFactory);
}
protected void removeThingHandlerFactory(ThingHandlerFactory thingHandlerFactory) {
this.thingHandlerFactories.remove(thingHandlerFactory);
}
protected void setItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) {
this.itemChannelLinkRegistry = itemChannelLinkRegistry;
}
protected void setItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = itemRegistry;
}
protected void setItemThingLinkRegistry(ItemThingLinkRegistry itemThingLinkRegistry) {
this.itemThingLinkRegistry = itemThingLinkRegistry;
}
protected void setThingRegistry(ThingRegistry thingRegistry) {
this.thingRegistry = thingRegistry;
}
protected void setThingTypeRegistry(ThingTypeRegistry thingTypeRegistry) {
this.thingTypeRegistry = thingTypeRegistry;
}
protected void unsetItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) {
this.itemChannelLinkRegistry = null;
}
protected void unsetItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = null;
}
protected void unsetItemThingLinkRegistry(ItemThingLinkRegistry itemThingLinkRegistry) {
this.itemThingLinkRegistry = null;
}
protected void unsetThingRegistry(ThingRegistry thingRegistry) {
this.thingRegistry = null;
}
protected void unsetThingTypeRegistry(ThingTypeRegistry thingTypeRegistry) {
this.thingTypeRegistry = null;
}
private Thing createThing(ThingUID thingUID, Configuration configuration, ThingUID bridgeUID,
ThingTypeUID thingTypeUID) {
for (ThingHandlerFactory thingHandlerFactory : this.thingHandlerFactories) {
if (thingHandlerFactory.supportsThingType(thingTypeUID)) {
Thing thing = thingHandlerFactory.createThing(thingTypeUID, configuration, thingUID, bridgeUID);
return thing;
}
}
return null;
}
private String getChannelGroupItemName(String itemName, String channelGroupId) {
return itemName + "_" + channelGroupId;
}
private ItemFactory getItemFactoryForItemType(String itemType) {
for (ItemFactory itemFactory : this.itemFactories) {
String[] supportedItemTypes = itemFactory.getSupportedItemTypes();
for (int i = 0; i < supportedItemTypes.length; i++) {
String supportedItemType = supportedItemTypes[i];
if (supportedItemType.equals(itemType)) {
return itemFactory;
}
}
}
return null;
}
private String getThingGroupItemName(ChannelUID channelUID) {
Collection<ItemThingLink> links = this.itemThingLinkRegistry.getAll();
for (ItemThingLink link : links) {
if (link.getUID().equals(channelUID.getThingUID())) {
return link.getItemName();
}
}
return null;
}
private String toItemName(UID uid) {
String itemName = uid.getAsString().replaceAll("[^a-zA-Z0-9_]", "_");
return itemName;
}
private String getFirstLinkedItem(UID uid) {
for (ItemThingLink link : itemThingLinkRegistry.getAll()) {
if (link.getUID().equals(uid)) {
return link.getItemName();
}
}
return null;
}
}
|
package gov.nih.nci.cagrid.data.creation;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.data.DataServiceConstants;
import gov.nih.nci.cagrid.introduce.IntroduceConstants;
import gov.nih.nci.cagrid.introduce.beans.ServiceDescription;
import gov.nih.nci.cagrid.introduce.beans.method.MethodType;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeExceptions;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeExceptionsException;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeInputs;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeInputsInput;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeOutput;
import gov.nih.nci.cagrid.introduce.beans.method.MethodsType;
import gov.nih.nci.cagrid.introduce.beans.namespace.NamespaceType;
import gov.nih.nci.cagrid.introduce.beans.namespace.NamespacesType;
import gov.nih.nci.cagrid.introduce.beans.property.ServiceProperties;
import gov.nih.nci.cagrid.introduce.beans.property.ServicePropertiesProperty;
import gov.nih.nci.cagrid.introduce.beans.resource.ResourcePropertiesListType;
import gov.nih.nci.cagrid.introduce.beans.resource.ResourcePropertyType;
import gov.nih.nci.cagrid.introduce.beans.service.ServiceType;
import gov.nih.nci.cagrid.introduce.common.CommonTools;
import gov.nih.nci.cagrid.introduce.extension.CreationExtensionException;
import gov.nih.nci.cagrid.introduce.extension.CreationExtensionPostProcessor;
import gov.nih.nci.cagrid.introduce.extension.ExtensionsLoader;
import gov.nih.nci.cagrid.introduce.extension.utils.ExtensionUtilities;
import gov.nih.nci.cagrid.metadata.ServiceMetadata;
import gov.nih.nci.cagrid.metadata.ServiceMetadataServiceDescription;
import gov.nih.nci.cagrid.metadata.service.Service;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.xml.namespace.QName;
import org.projectmobius.tools.common.viewer.XSDFileFilter;
/**
* DataServiceCreationPostProcessor
* Creation post-processor for data services
*
* @author <A HREF="MAILTO:ervin@bmi.osu.edu">David W. Ervin</A>
* @created Mar 29, 2006
* @version $Id$
*/
public class DataServiceCreationPostProcessor implements CreationExtensionPostProcessor {
public void postCreate(ServiceDescription serviceDescription, Properties serviceProperties)
throws CreationExtensionException {
// apply data service requirements to it
try {
System.out.println("Adding data service components to template");
makeDataService(serviceDescription, serviceProperties);
} catch (Exception ex) {
ex.printStackTrace();
throw new CreationExtensionException("Error adding data service components to template! " + ex.getMessage(), ex);
}
// add the proper deployment properties
try {
System.out.println("Adding deploy property for query processor class");
modifyServiceProperties(serviceDescription);
} catch (Exception ex) {
ex.printStackTrace();
throw new CreationExtensionException("Error adding query processor parameter to service! " + ex.getMessage(), ex);
}
}
private void makeDataService(ServiceDescription description, Properties props) throws Exception {
// get the data service itself
String serviceName = props.getProperty(IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME);
ServiceType dataService = CommonTools.getService(description.getServices(), serviceName);
// grab cql query and result set schemas and move them into the service's directory
String schemaDir = getServiceSchemaDir(props);
System.out.println("Copying schemas to " + schemaDir);
File extensionSchemaDir = new File(ExtensionsLoader.EXTENSIONS_DIRECTORY + File.separator
+ "data" + File.separator + "schema");
List schemaFiles = Utils.recursiveListFiles(extensionSchemaDir, new XSDFileFilter());
for (int i = 0; i < schemaFiles.size(); i++) {
File schemaFile = (File) schemaFiles.get(i);
String subname = schemaFile.getCanonicalPath().substring(
extensionSchemaDir.getCanonicalPath().length() + File.separator.length());
copySchema(subname, schemaDir);
}
// copy libraries for data services into the new DS's lib directory
copyLibraries(props);
// namespaces
System.out.println("Modifying namespace definitions");
NamespacesType namespaces = description.getNamespaces();
if (namespaces == null) {
namespaces = new NamespacesType();
}
// add some namespaces to the service
List dsNamespaces = new ArrayList(Arrays.asList(namespaces.getNamespace()));
// query namespace
NamespaceType queryNamespace = CommonTools.createNamespaceType(schemaDir + File.separator
+ DataServiceConstants.CQL_QUERY_SCHEMA);
queryNamespace.setLocation("." + File.separator + DataServiceConstants.CQL_QUERY_SCHEMA);
// query result namespace
NamespaceType resultNamespace = CommonTools.createNamespaceType(schemaDir + File.separator
+ DataServiceConstants.CQL_RESULT_SET_SCHEMA);
resultNamespace.setLocation("." + File.separator + DataServiceConstants.CQL_RESULT_SET_SCHEMA);
// ds metadata namespace
NamespaceType dsMetadataNamespace = CommonTools.createNamespaceType(schemaDir + File.separator
+ DataServiceConstants.DATA_METADATA_SCHEMA);
dsMetadataNamespace.setLocation("." + File.separator + DataServiceConstants.DATA_METADATA_SCHEMA);
// caGrid metadata namespace
NamespaceType cagridMdNamespace = CommonTools.createNamespaceType(schemaDir + File.separator
+ DataServiceConstants.CAGRID_METADATA_SCHEMA);
cagridMdNamespace.setLocation("." + File.separator + DataServiceConstants.CAGRID_METADATA_SCHEMA);
// prevent metadata beans from being built
cagridMdNamespace.setGenerateStubs(Boolean.FALSE);
// add those new namespaces to the list of namespace types
dsNamespaces.add(queryNamespace);
dsNamespaces.add(resultNamespace);
dsNamespaces.add(dsMetadataNamespace);
dsNamespaces.add(cagridMdNamespace);
NamespaceType[] nsArray = new NamespaceType[dsNamespaces.size()];
dsNamespaces.toArray(nsArray);
namespaces.setNamespace(nsArray);
description.setNamespaces(namespaces);
// query method
System.out.println("Building query method");
MethodsType methods = dataService.getMethods();
if (methods == null) {
methods = new MethodsType();
}
MethodType queryMethod = new MethodType();
queryMethod.setName(DataServiceConstants.QUERY_METHOD_NAME);
// method input parameters
MethodTypeInputs inputs = new MethodTypeInputs();
MethodTypeInputsInput queryInput = new MethodTypeInputsInput();
queryInput.setName(DataServiceConstants.QUERY_METHOD_PARAMETER_NAME);
queryInput.setIsArray(false);
QName queryQname = new QName(queryNamespace.getNamespace(), queryNamespace.getSchemaElement(0).getType());
queryInput.setQName(queryQname);
inputs.setInput(new MethodTypeInputsInput[]{queryInput});
queryMethod.setInputs(inputs);
// method output
MethodTypeOutput output = new MethodTypeOutput();
output.setIsArray(false);
QName resultSetQName = new QName(resultNamespace.getNamespace(), resultNamespace.getSchemaElement(0).getType());
output.setQName(resultSetQName);
queryMethod.setOutput(output);
// exceptions on query method
MethodTypeExceptions queryExceptions = new MethodTypeExceptions();
MethodTypeExceptionsException[] exceptions = {
new MethodTypeExceptionsException(DataServiceConstants.QUERY_METHOD_EXCEPTIONS[0]),
new MethodTypeExceptionsException(DataServiceConstants.QUERY_METHOD_EXCEPTIONS[1])};
queryExceptions.setException(exceptions);
queryMethod.setExceptions(queryExceptions);
// add query method to methods array
MethodType[] dsMethods = null;
if (methods.getMethod() != null) {
dsMethods = new MethodType[methods.getMethod().length + 1];
System.arraycopy(methods.getMethod(), 0, dsMethods, 0, methods.getMethod().length);
} else {
dsMethods = new MethodType[1];
}
dsMethods[dsMethods.length - 1] = queryMethod;
methods.setMethod(dsMethods);
dataService.setMethods(methods);
// add the service metadata
addServiceMetadata(description);
}
private void addServiceMetadata(ServiceDescription desc) {
ResourcePropertyType serviceMetadata = new ResourcePropertyType();
serviceMetadata.setPopulateFromFile(false); // no metadata file yet...
serviceMetadata.setRegister(true);
serviceMetadata.setQName(DataServiceConstants.SERVICE_METADATA_QNAME);
ServiceMetadata smd = new ServiceMetadata();
ServiceMetadataServiceDescription des = new ServiceMetadataServiceDescription();
Service service = new Service();
des.setService(service);
smd.setServiceDescription(des);
ResourcePropertiesListType propsList = desc.getServices().getService()[0].getResourcePropertiesList();
if (propsList == null) {
propsList = new ResourcePropertiesListType();
desc.getServices().getService()[0].setResourcePropertiesList(propsList);
}
ResourcePropertyType[] metadataArray = propsList.getResourceProperty();
if (metadataArray == null || metadataArray.length == 0) {
metadataArray = new ResourcePropertyType[]{serviceMetadata};
} else {
ResourcePropertyType[] tmpArray = new ResourcePropertyType[metadataArray.length + 1];
System.arraycopy(metadataArray, 0, tmpArray, 0, metadataArray.length);
tmpArray[metadataArray.length] = serviceMetadata;
metadataArray = tmpArray;
}
propsList.setResourceProperty(metadataArray);
}
private String getServiceSchemaDir(Properties props) {
return props.getProperty(IntroduceConstants.INTRODUCE_SKELETON_DESTINATION_DIR) + File.separator + "schema"
+ File.separator + props.getProperty(IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME);
}
private String getServiceLibDir(Properties props) {
return props.getProperty(IntroduceConstants.INTRODUCE_SKELETON_DESTINATION_DIR) + File.separator + "lib";
}
private void copySchema(String schemaName, String outputDir) throws Exception {
File schemaFile = new File(ExtensionsLoader.EXTENSIONS_DIRECTORY + File.separator + "data" + File.separator
+ "schema" + File.separator + schemaName);
System.out.println("Copying schema from " + schemaFile.getAbsolutePath());
File outputFile = new File(outputDir + File.separator + schemaName);
System.out.println("Saving schema to " + outputFile.getAbsolutePath());
Utils.copyFile(schemaFile, outputFile);
}
private void copyLibraries(Properties props) throws Exception {
String toDir = getServiceLibDir(props);
File directory = new File(toDir);
if (!directory.exists()) {
directory.mkdirs();
}
// from the lib directory
File libDir = new File(ExtensionsLoader.EXTENSIONS_DIRECTORY + File.separator + "lib");
File[] libs = libDir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
String name = pathname.getName();
return (name.endsWith(".jar") && (name.startsWith("caGrid-data-1.0") || name.startsWith("castor")
|| name.startsWith("client") || name.startsWith("caGrid-caDSR")
|| name.startsWith("caGrid-metadata") || name.startsWith("caGrid-core")));
}
});
File[] copiedLibs = new File[libs.length];
if (libs != null) {
for (int i = 0; i < libs.length; i++) {
File outFile = new File(toDir + File.separator + libs[i].getName());
copiedLibs[i] = outFile;
Utils.copyFile(libs[i], outFile);
}
}
modifyClasspathFile(copiedLibs, props);
}
private void modifyClasspathFile(File[] libs, Properties props) throws Exception {
File classpathFile = new File(props.getProperty(IntroduceConstants.INTRODUCE_SKELETON_DESTINATION_DIR)
+ File.separator + ".classpath");
ExtensionUtilities.syncEclipseClasspath(classpathFile, libs);
}
private void modifyServiceProperties(ServiceDescription desc) throws Exception {
ServicePropertiesProperty prop = new ServicePropertiesProperty();
prop.setKey(DataServiceConstants.QUERY_PROCESSOR_CLASS_PROPERTY);
prop.setValue(""); // empty value to be populated later
ServiceProperties serviceProperties = desc.getServiceProperties();
if (serviceProperties == null) {
serviceProperties = new ServiceProperties();
}
ServicePropertiesProperty[] allProps = serviceProperties.getProperty();
if (allProps != null) {
ServicePropertiesProperty[] tmpProps = new ServicePropertiesProperty[allProps.length + 1];
System.arraycopy(allProps, 0, tmpProps, 0, allProps.length);
tmpProps[tmpProps.length - 1] = prop;
} else {
allProps = new ServicePropertiesProperty[] {prop};
}
serviceProperties.setProperty(allProps);
desc.setServiceProperties(serviceProperties);
}
}
|
package org.opencms.db.generic;
import org.opencms.db.CmsAdjacencyTree;
import org.opencms.db.CmsDriverManager;
import org.opencms.db.I_CmsVfsDriver;
import com.opencms.boot.I_CmsLogChannels;
import com.opencms.core.A_OpenCms;
import com.opencms.core.CmsException;
import com.opencms.core.I_CmsConstants;
import com.opencms.file.CmsFile;
import com.opencms.file.CmsFolder;
import com.opencms.file.CmsProject;
import com.opencms.file.CmsPropertydefinition;
import com.opencms.file.CmsResource;
import com.opencms.file.CmsUser;
import com.opencms.file.I_CmsResourceType;
import com.opencms.flex.util.CmsUUID;
import com.opencms.linkmanagement.CmsPageLinks;
import com.opencms.report.I_CmsReport;
import com.opencms.util.SqlHelper;
import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
import source.org.apache.java.util.Configurations;
public class CmsVfsDriver extends Object implements I_CmsVfsDriver {
protected CmsDriverManager m_driverManager;
protected org.opencms.db.generic.CmsSqlManager m_sqlManager;
/**
* Changes the project-id of a resource to the new project
* for publishing the resource directly
*
* @param newProjectId The new project-id
* @param resourcename The name of the resource to change
* @throws CmsException if an error occurs
*/
public void changeLockedInProject(int newProjectId, CmsUUID resourceId) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_UPDATE_PROJECTID");
stmt.setInt(1, newProjectId);
stmt.setString(2, resourceId.toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Copies a file.
*
* @param project The project in which the resource will be used.
* @param userId The id of the user who wants to copy the file.
* @param source the source file to copy
* @param parentId The parentId of the resource.
* @param destination The complete path of the destinationfile.
*
* @throws CmsException Throws CmsException if operation was not succesful
* @return the file copy
*/
// public CmsFile copyFile(CmsProject project, CmsUUID userId, CmsUUID parentId, String source, String destination) throws CmsException {
// CmsFile file = this.readFile(project.getId(),false, resourceId);
// return createFile(project, file, userId, parentId, destination);
/**
* Counts the locked resources in this project.
*
* @param project The project to be unlocked.
* @return the amount of locked resources in this project.
*
* @throws CmsException Throws CmsException if something goes wrong.
*/
public int countLockedResources(CmsProject project) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet res = null;
int retValue;
try {
// create the statement
conn = m_sqlManager.getConnection(project);
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_COUNTLOCKED");
stmt.setString(1, CmsUUID.getNullUUID().toString());
stmt.setInt(2, project.getId());
res = stmt.executeQuery();
if (res.next()) {
retValue = res.getInt(1);
} else {
retValue = 0;
}
} catch (Exception exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
// close all db-resources
m_sqlManager.closeAll(conn, stmt, res);
}
return retValue;
}
/**
* Returns the amount of properties for a propertydefinition.
*
* @param metadef The propertydefinition to test.
*
* @return the amount of properties for a propertydefinition.
*
* @throws CmsException Throws CmsException if something goes wrong.
*/
protected int countProperties(CmsPropertydefinition metadef) throws CmsException {
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
int returnValue;
try {
// create statement
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTIES_READALL_COUNT");
stmt.setInt(1, metadef.getId());
res = stmt.executeQuery();
if (res.next()) {
returnValue = res.getInt(1);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + metadef.getName(), CmsException.C_UNKNOWN_EXCEPTION);
}
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
// close all db-resources
m_sqlManager.closeAll(conn, stmt, res);
}
return returnValue;
}
public CmsFile createCmsFileFromResultSet(ResultSet res, int projectId, boolean hasProjectIdInResultSet, boolean hasFileContentInResultSet) throws SQLException, CmsException {
byte[] content = null;
int resProjectId = I_CmsConstants.C_UNKNOWN_ID;
CmsUUID structureId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_STRUCTURE_ID")));
CmsUUID resourceId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_ID")));
CmsUUID parentId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_PARENT_ID")));
String resourceName = res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_NAME"));
int resourceType = res.getInt(m_sqlManager.get("C_RESOURCES_RESOURCE_TYPE"));
int resourceFlags = res.getInt(m_sqlManager.get("C_RESOURCES_RESOURCE_FLAGS"));
CmsUUID fileId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_FILE_ID")));
int state = res.getInt(m_sqlManager.get("C_RESOURCES_STATE"));
CmsUUID lockedBy = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_LOCKED_BY")));
int launcherType = res.getInt(m_sqlManager.get("C_RESOURCES_LAUNCHER_TYPE"));
String launcherClass = res.getString(m_sqlManager.get("C_RESOURCES_LAUNCHER_CLASSNAME"));
long dateCreated = SqlHelper.getTimestamp(res, m_sqlManager.get("C_RESOURCES_DATE_CREATED")).getTime();
long dateLastModified = SqlHelper.getTimestamp(res, m_sqlManager.get("C_RESOURCES_DATE_LASTMODIFIED")).getTime();
int resourceSize = res.getInt(m_sqlManager.get("C_RESOURCES_SIZE"));
CmsUUID userCreated = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_USER_CREATED")));
CmsUUID userLastModified = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_USER_LASTMODIFIED")));
int lockedInProject = res.getInt("LOCKED_IN_PROJECT");
//resProjectId = res.getInt(m_sqlManager.get("C_RESOURCES_PROJECT_ID"));
if (hasFileContentInResultSet) {
content = m_sqlManager.getBytes(res, m_sqlManager.get("C_RESOURCES_FILE_CONTENT"));
} else {
content = new byte[0];
}
if (!lockedBy.equals(CmsUUID.getNullUUID())) {
// resource is locked
resProjectId = lockedInProject;
} else {
// resource is not locked
resProjectId = lockedInProject = projectId;
}
if (org.opencms.db.generic.CmsProjectDriver.C_USE_TARGET_DATE && resourceType == org.opencms.db.generic.CmsProjectDriver.C_RESTYPE_LINK_ID && resourceFlags > 0) {
dateLastModified = fetchDateFromResource(projectId, resourceFlags, dateLastModified);
}
return new CmsFile(structureId, resourceId, parentId, fileId, resourceName, resourceType, resourceFlags, userCreated, CmsUUID.getNullUUID(), resProjectId, 0, state, lockedBy, launcherType, launcherClass, dateCreated, dateLastModified, userLastModified, content, resourceSize, lockedInProject);
}
/**
* @see org.opencms.db.I_CmsVfsDriver#createCmsFileFromResultSet(java.sql.ResultSet, int)
*/
public CmsFile createCmsFileFromResultSet(ResultSet res, int projectId) throws SQLException, CmsException {
CmsUUID structureId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_STRUCTURE_ID")));
CmsUUID resourceId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_ID")));
CmsUUID parentId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_PARENT_ID")));
int resourceType = res.getInt(m_sqlManager.get("C_RESOURCES_RESOURCE_TYPE"));
String resourceName = res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_NAME"));
int resourceFlags = res.getInt(m_sqlManager.get("C_RESOURCES_RESOURCE_FLAGS"));
CmsUUID fileId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_FILE_ID")));
int state = res.getInt(m_sqlManager.get("C_RESOURCES_STATE"));
CmsUUID lockedBy = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_LOCKED_BY")));
int launcherType = res.getInt(m_sqlManager.get("C_RESOURCES_LAUNCHER_TYPE"));
String launcherClass = res.getString(m_sqlManager.get("C_RESOURCES_LAUNCHER_CLASSNAME"));
long dateCreated = SqlHelper.getTimestamp(res, m_sqlManager.get("C_RESOURCES_DATE_CREATED")).getTime();
long dateLastModified = SqlHelper.getTimestamp(res, m_sqlManager.get("C_RESOURCES_DATE_LASTMODIFIED")).getTime();
int resourceSize = res.getInt(m_sqlManager.get("C_RESOURCES_SIZE"));
CmsUUID userCreated = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_USER_CREATED")));
CmsUUID userLastModified = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_USER_LASTMODIFIED")));
int lockedInProject = res.getInt("LOCKED_IN_PROJECT");
int resProjectId = res.getInt(m_sqlManager.get("C_RESOURCES_PROJECT_ID"));
byte[] content = m_sqlManager.getBytes(res, m_sqlManager.get("C_RESOURCES_FILE_CONTENT"));
if (org.opencms.db.generic.CmsProjectDriver.C_USE_TARGET_DATE && resourceType == org.opencms.db.generic.CmsProjectDriver.C_RESTYPE_LINK_ID && resourceFlags > 0) {
dateLastModified = fetchDateFromResource(projectId, resourceFlags, dateLastModified);
}
if (!lockedBy.equals(CmsUUID.getNullUUID())) {
// resource is locked
} else {
// resource is not locked
resProjectId = lockedInProject = projectId;
}
return new CmsFile(structureId, resourceId, parentId, fileId, resourceName, resourceType, resourceFlags, userCreated, CmsUUID.getNullUUID(), resProjectId, 0, state, lockedBy, launcherType, launcherClass, dateCreated, dateLastModified, userLastModified, content, resourceSize, lockedInProject);
}
/**
* @see org.opencms.db.I_CmsVfsDriver#createCmsFolderFromResultSet(java.sql.ResultSet, int, boolean)
*/
public CmsFolder createCmsFolderFromResultSet(ResultSet res, int projectId, boolean hasProjectIdInResultSet) throws SQLException {
int resProjectId = I_CmsConstants.C_UNKNOWN_ID;
CmsUUID structureId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_STRUCTURE_ID")));
CmsUUID resourceId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_ID")));
CmsUUID parentId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_PARENT_ID")));
String resourceName = res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_NAME"));
int resourceType = res.getInt(m_sqlManager.get("C_RESOURCES_RESOURCE_TYPE"));
int resourceFlags = res.getInt(m_sqlManager.get("C_RESOURCES_RESOURCE_FLAGS"));
CmsUUID fileId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_FILE_ID")));
int state = res.getInt(m_sqlManager.get("C_RESOURCES_STATE"));
CmsUUID lockedBy = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_LOCKED_BY")));
long dateCreated = SqlHelper.getTimestamp(res, m_sqlManager.get("C_RESOURCES_DATE_CREATED")).getTime();
long dateLastModified = SqlHelper.getTimestamp(res, m_sqlManager.get("C_RESOURCES_DATE_LASTMODIFIED")).getTime();
CmsUUID userCreated = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_USER_CREATED")));
CmsUUID userLastModified = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_USER_LASTMODIFIED")));
int lockedInProject = res.getInt("LOCKED_IN_PROJECT");
if (!lockedBy.equals(CmsUUID.getNullUUID())) {
// resource is locked
resProjectId = lockedInProject;
} else {
// resource is not locked
resProjectId = lockedInProject = projectId;
}
return new CmsFolder(structureId, resourceId, parentId, fileId, resourceName, resourceType, resourceFlags, userCreated, CmsUUID.getNullUUID(), resProjectId, 0, state, lockedBy, dateCreated, dateLastModified, userLastModified, lockedInProject);
}
/**
* @see org.opencms.db.I_CmsVfsDriver#createCmsResourceFromResultSet(java.sql.ResultSet, int)
*/
public CmsResource createCmsResourceFromResultSet(ResultSet res, int projectId) throws SQLException, CmsException {
CmsUUID structureId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_STRUCTURE_ID")));
CmsUUID resourceId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_ID")));
CmsUUID parentId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_PARENT_ID")));
String resourceName = res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_NAME"));
int resourceType = res.getInt(m_sqlManager.get("C_RESOURCES_RESOURCE_TYPE"));
int resourceFlags = res.getInt(m_sqlManager.get("C_RESOURCES_RESOURCE_FLAGS"));
int resourceProjectId = res.getInt(m_sqlManager.get("C_RESOURCES_PROJECT_ID"));
CmsUUID fileId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_FILE_ID")));
int state = res.getInt(m_sqlManager.get("C_RESOURCES_STATE"));
CmsUUID lockedBy = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_LOCKED_BY")));
int launcherType = res.getInt(m_sqlManager.get("C_RESOURCES_LAUNCHER_TYPE"));
String launcherClass = res.getString(m_sqlManager.get("C_RESOURCES_LAUNCHER_CLASSNAME"));
long dateCreated = SqlHelper.getTimestamp(res, m_sqlManager.get("C_RESOURCES_DATE_CREATED")).getTime();
long dateLastModified = SqlHelper.getTimestamp(res, m_sqlManager.get("C_RESOURCES_DATE_LASTMODIFIED")).getTime();
int resSize = res.getInt(m_sqlManager.get("C_RESOURCES_SIZE"));
CmsUUID userCreated = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_USER_CREATED")));
CmsUUID userLastModified = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_USER_LASTMODIFIED")));
int lockedInProject = res.getInt("LOCKED_IN_PROJECT");
if (org.opencms.db.generic.CmsProjectDriver.C_USE_TARGET_DATE && resourceType == org.opencms.db.generic.CmsProjectDriver.C_RESTYPE_LINK_ID && resourceFlags > 0) {
dateLastModified = fetchDateFromResource(projectId, resourceFlags, dateLastModified);
}
if (!lockedBy.equals(CmsUUID.getNullUUID())) {
// resource is locked
} else {
// resource is not locked
resourceProjectId = lockedInProject = projectId;
}
return new CmsResource(structureId, resourceId, parentId, fileId, resourceName, resourceType, resourceFlags, userCreated, CmsUUID.getNullUUID(), resourceProjectId, 0, state, lockedBy, launcherType, launcherClass, dateCreated, dateLastModified, userLastModified, resSize, lockedInProject);
}
/**
* Creates a new file from an given CmsFile object and a new filename.
*
* @param project The project in which the resource will be used.
* @param file The file to be written to the Cms.
* @param userId The Id of the user who changed the resourse.
* @param parentId The parentId of the resource.
* @param filename The complete new name of the file (including pathinformation).
*
* @return file The created file.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public CmsFile createFile(CmsProject project, CmsFile file, CmsUUID userId, CmsUUID parentId, String filename) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
if (filename.length() > I_CmsConstants.C_MAX_LENGTH_RESOURCE_NAME) {
throw new CmsException("The resource name '" + filename + "' is too long! (max. allowed length must be <= " + I_CmsConstants.C_MAX_LENGTH_RESOURCE_NAME + " chars.!)", CmsException.C_BAD_NAME);
}
int state = 0;
CmsUUID modifiedByUserId = userId;
long dateModified = System.currentTimeMillis();
if (project.getId() == I_CmsConstants.C_PROJECT_ONLINE_ID) {
state = file.getState();
modifiedByUserId = file.getResourceLastModifiedBy();
dateModified = file.getDateLastModified();
} else {
state = I_CmsConstants.C_STATE_NEW;
}
// Test if the file is already there and marked as deleted.
// If so, delete it.
// If the file exists already and is not marked as deleted then throw exception
try {
readFileHeader(project.getId(), parentId, filename, false);
throw new CmsException("[" + this.getClass().getName() + "] ", CmsException.C_FILE_EXISTS);
} catch (CmsException e) {
// if the file is marked as deleted remove it!
if (e.getType() == CmsException.C_RESOURCE_DELETED) {
removeFile(project, parentId, filename);
state = I_CmsConstants.C_STATE_CHANGED;
}
if (e.getType() == CmsException.C_FILE_EXISTS) {
throw e;
}
}
try {
conn = m_sqlManager.getConnection(project);
// write the content
try {
createFileContent(file.getFileId(), file.getContents(), 0, project.getId(), false);
} catch (CmsException se) {
if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + "] " + se.getMessage());
}
}
// write the resource
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_WRITE");
stmt.setString(1, file.getResourceId().toString());
stmt.setInt(2, file.getType());
stmt.setInt(3, file.getFlags());
stmt.setString(4, file.getFileId().toString());
stmt.setInt(5, file.getLauncherType());
stmt.setString(6, file.getLauncherClassname());
stmt.setTimestamp(7, new Timestamp(file.getDateCreated()));
stmt.setTimestamp(8, new Timestamp(dateModified));
stmt.setInt(9, file.getLength());
stmt.executeUpdate();
m_sqlManager.closeAll(null, stmt, null);
// write the structure
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_STRUCTURE_WRITE");
stmt.setString(1, file.getId().toString());
stmt.setString(2, parentId.toString());
stmt.setString(3, file.getResourceId().toString());
stmt.setInt(4, project.getId());
stmt.setString(5, filename);
stmt.setInt(6, 0);
stmt.setInt(7, state);
stmt.setString(8, file.isLockedBy().toString());
stmt.setString(9, modifiedByUserId.toString());
stmt.setString(10, userId.toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
return readFile(project.getId(), false, file.getId());
}
/**
* Creates a new file with the given content and resourcetype.
*
* @param user The user who wants to create the file.
* @param project The project in which the resource will be used.
* @param filename The complete name of the new file (including pathinformation).
* @param flags The flags of this resource.
* @param parentId The parentId of the resource.
* @param contents The contents of the new file.
* @param resourceType The resourceType of the new file.
*
* @return file The created file.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public CmsFile createFile(CmsUser user, CmsProject project, String filename, int flags, CmsUUID parentId, byte[] contents, I_CmsResourceType resourceType) throws CmsException {
CmsFile newFile = new CmsFile(
new CmsUUID(),
new CmsUUID(),
parentId,
new CmsUUID(),
filename,
resourceType.getResourceType(),
flags,
user.getId(),
user.getDefaultGroupId(),
project.getId(),
com.opencms.core.I_CmsConstants.C_ACCESS_DEFAULT_FLAGS,
com.opencms.core.I_CmsConstants.C_STATE_NEW,
CmsUUID.getNullUUID(),
resourceType.getLauncherType(),
resourceType.getLauncherClass(),
0,
0,
user.getId(),
contents,
contents.length,
project.getId());
return createFile(project, newFile, user.getId(), parentId, filename);
}
/**
* Creates the content entry for a file
*
* @param fileId The ID of the new file
* @param fileContent The content of the new file
* @param versionId For the content of a backup file you need to insert the versionId of the backup
* @throws CmsException if an error occurs
*/
public void createFileContent(CmsUUID fileId, byte[] fileContent, int versionId, int projectId, boolean writeBackup) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
if (writeBackup) {
conn = m_sqlManager.getConnectionForBackup();
stmt = m_sqlManager.getPreparedStatement(conn, "C_FILES_WRITE_BACKUP");
}
else {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_FILES_WRITE");
}
stmt.setString(1, fileId.toString());
if (fileContent.length < 2000) {
stmt.setBytes(2, fileContent);
} else {
stmt.setBinaryStream(2, new ByteArrayInputStream(fileContent), fileContent.length);
}
if (writeBackup) {
stmt.setInt(3, versionId);
stmt.setString(4, new CmsUUID().toString());
}
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Creates a new folder from an existing folder object.
*
* @param user The user who wants to create the folder.
* @param project The project in which the resource will be used.
* @param folder The folder to be written to the Cms.
* @param parentId The parentId of the resource.
*
* @param foldername The complete path of the new name of this folder.
*
* @return The created folder.
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder createFolder(CmsUser user, CmsProject project, CmsFolder folder, CmsUUID parentId, String foldername) throws CmsException {
if (foldername.length() > I_CmsConstants.C_MAX_LENGTH_RESOURCE_NAME) {
throw new CmsException("The resource name '" + foldername + "' is too long! (max. allowed length must be <= " + I_CmsConstants.C_MAX_LENGTH_RESOURCE_NAME + " chars.!)", CmsException.C_BAD_NAME);
}
CmsFolder oldFolder = null;
int state = 0;
CmsUUID modifiedByUserId = user.getId();
long dateModified = System.currentTimeMillis();
if (project.getId() == I_CmsConstants.C_PROJECT_ONLINE_ID) {
state = folder.getState();
modifiedByUserId = folder.getResourceLastModifiedBy();
dateModified = folder.getDateLastModified();
} else {
state = I_CmsConstants.C_STATE_NEW;
}
// Test if the file is already there and marked as deleted.
// If so, delete it
// No, dont delete it, throw exception (h.riege, 04.01.01)
try {
oldFolder = readFolder(project.getId(), parentId, foldername);
if (oldFolder.getState() == I_CmsConstants.C_STATE_DELETED) {
throw new CmsException("[" + this.getClass().getName() + "] ", CmsException.C_FILE_EXISTS);
} else {
if (oldFolder != null) {
throw new CmsException("[" + this.getClass().getName() + "] ", CmsException.C_FILE_EXISTS);
}
}
} catch (CmsException e) {
if (e.getType() == CmsException.C_FILE_EXISTS) {
throw e;
}
}
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = m_sqlManager.getConnection(project);
// write the resource
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_WRITE");
stmt.setString(1, folder.getResourceId().toString());
stmt.setInt(2, folder.getType());
stmt.setInt(3, folder.getFlags());
stmt.setString(4, CmsUUID.getNullUUID().toString());
stmt.setInt(5, folder.getLauncherType());
stmt.setString(6, folder.getLauncherClassname());
stmt.setTimestamp(7, new Timestamp(folder.getDateCreated()));
stmt.setTimestamp(8, new Timestamp(dateModified));
stmt.setInt(9, folder.getLength());
stmt.executeUpdate();
m_sqlManager.closeAll(null, stmt, null);
// write the structure
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_STRUCTURE_WRITE");
stmt.setString(1, folder.getId().toString());
stmt.setString(2, parentId.toString());
stmt.setString(3, folder.getResourceId().toString());
stmt.setInt(4, project.getId());
stmt.setString(5, foldername);
stmt.setInt(6, 0);
stmt.setInt(7, state);
stmt.setString(8, folder.isLockedBy().toString());
stmt.setString(9, modifiedByUserId.toString());
stmt.setString(10, user.getId().toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
// if this is the rootfolder or if the parentfolder is the rootfolder
// try to create the projectresource
String parentFolderName = "/";
if (!folder.getResourceName().equals(I_CmsConstants.C_ROOT)) {
parentFolderName = folder.getResourceName().substring(0, folder.getResourceName().length() - 1);
parentFolderName = parentFolderName.substring(0, parentFolderName.lastIndexOf("/") + 1);
}
if (parentId.isNullUUID() || parentFolderName.equals(I_CmsConstants.C_ROOT)) {
try {
String rootFolder = null;
try {
rootFolder = readProjectResource(project.getId(), I_CmsConstants.C_ROOT);
} catch (CmsException exc) {
// NOOP
}
if (rootFolder == null) {
createProjectResource(project.getId(), foldername);
}
//createProjectResource(project.getId(), foldername);
} catch (CmsException e) {
if (e.getType() != CmsException.C_FILE_EXISTS) {
throw e;
}
}
}
return readFolder(project.getId(), folder.getId());
}
/**
* Creates a new folder
*
* @param user The user who wants to create the folder.
* @param project The project in which the resource will be used.
* @param parentId The parentId of the folder.
* @param fileId The fileId of the folder.
* @param foldername The complete path to the folder in which the new folder will be created.
* @param flags The flags of this resource.
*
* @return The created folder.
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder createFolder(CmsUser user, CmsProject project, CmsUUID parentId, CmsUUID fileId, String folderName, int flags) throws CmsException {
CmsFolder newFolder = new CmsFolder(
new CmsUUID(),
new CmsUUID(),
parentId,
CmsUUID.getNullUUID(),
folderName,
com.opencms.core.I_CmsConstants.C_TYPE_FOLDER,
flags,
user.getId(),
user.getDefaultGroupId(),
project.getId(),
com.opencms.core.I_CmsConstants.C_ACCESS_DEFAULT_FLAGS,
com.opencms.core.I_CmsConstants.C_STATE_NEW,
CmsUUID.getNullUUID(),
0,
0,
user.getId(),
project.getId());
return createFolder(user, project, newFolder, parentId, folderName);
}
/**
* Creates a new projectResource from a given CmsResource object.
*
* @param project The project in which the resource will be used.
* @param resource The resource to be written to the Cms.
*
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void createProjectResource(int projectId, String resourceName) throws CmsException {
// do not create entries for online-project
PreparedStatement stmt = null;
Connection conn = null;
try {
readProjectResource(projectId, resourceName);
throw new CmsException("[" + this.getClass().getName() + "] ", CmsException.C_FILE_EXISTS);
} catch (CmsException e) {
if (e.getType() == CmsException.C_FILE_EXISTS) {
throw e;
}
}
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_CREATE");
// write new resource to the database
stmt.setInt(1, projectId);
stmt.setString(2, resourceName);
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Creates the propertydefinitions for the resource type.<BR/>
*
* Only the admin can do this.
*
* @param name The name of the propertydefinitions to overwrite.
* @param resourcetype The resource-type for the propertydefinitions.
*
* @throws CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition createPropertydefinition(String name, int projectId, int resourcetype) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
for (int i=0; i<3; i++) {
// create the offline property definition
if (i == 0) {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, Integer.MAX_VALUE, "C_PROPERTYDEF_CREATE");
stmt.setInt(1, m_sqlManager.nextId(m_sqlManager.get("C_TABLE_PROPERTYDEF")));
}
// create the online property definition
else if (i == 1) {
conn = m_sqlManager.getConnection(I_CmsConstants.C_PROJECT_ONLINE_ID);
stmt = m_sqlManager.getPreparedStatement(conn, I_CmsConstants.C_PROJECT_ONLINE_ID, "C_PROPERTYDEF_CREATE");
stmt.setInt(1, m_sqlManager.nextId(m_sqlManager.get("C_TABLE_PROPERTYDEF_ONLINE")));
}
// create the backup property definition
else {
conn = m_sqlManager.getConnectionForBackup();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTYDEF_CREATE_BACKUP");
stmt.setInt(1, m_sqlManager.nextId(m_sqlManager.get("C_TABLE_PROPERTYDEF_BACKUP")));
}
stmt.setString(2, name);
stmt.setInt(3, resourcetype);
stmt.executeUpdate();
m_sqlManager.closeAll(conn, stmt, null);
}
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
return readPropertydefinition(name, projectId, resourcetype);
}
/**
* Creates a new resource from an given CmsResource object.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param newResource The resource to be written to the Cms.
* @param filecontent The filecontent if the resource is a file
* @param userId The ID of the current user.
* @param parentId The parentId of the resource.
*
* @return resource The created resource.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public CmsResource importResource(CmsProject project, CmsUUID parentId, CmsResource newResource, byte[] filecontent, CmsUUID userId, boolean isFolder) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
if (newResource.getResourceName().length() > I_CmsConstants.C_MAX_LENGTH_RESOURCE_NAME) {
throw new CmsException("The resource name '" + newResource.getResourceName() + "' is too long! (max. allowed length must be <= " + I_CmsConstants.C_MAX_LENGTH_RESOURCE_NAME + " chars.!)", CmsException.C_BAD_NAME);
}
int state = 0;
CmsUUID modifiedByUserId = userId;
//long dateModified = newResource.isTouched() ? newResource.getDateLastModified() : System.currentTimeMillis();
if (project.getId() == I_CmsConstants.C_PROJECT_ONLINE_ID) {
state = newResource.getState();
modifiedByUserId = newResource.getResourceLastModifiedBy();
//dateModified = newResource.getDateLastModified();
} else {
state = I_CmsConstants.C_STATE_NEW;
}
// Test if the file is already there and marked as deleted.
// If so, delete it.
// If the file exists already and is not marked as deleted then throw exception
try {
readResource(project, parentId, newResource.getResourceName());
throw new CmsException("[" + this.getClass().getName() + "] ", CmsException.C_FILE_EXISTS);
} catch (CmsException e) {
// if the resource is marked as deleted remove it!
if (e.getType() == CmsException.C_RESOURCE_DELETED) {
if (isFolder) {
removeFolder(project.getId(), (CmsFolder) newResource);
} else {
removeFile(project, parentId, newResource.getResourceName());
}
state = I_CmsConstants.C_STATE_CHANGED;
//throw new CmsException("["+this.getClass().getName()+"] ",CmsException.C_FILE_EXISTS);
}
if (e.getType() == CmsException.C_FILE_EXISTS) {
throw e;
}
}
CmsUUID newFileId = CmsUUID.getNullUUID();
CmsUUID resourceId = new CmsUUID();
CmsUUID structureId = new CmsUUID();
// now write the resource
try {
conn = m_sqlManager.getConnection(project);
// write the content
if (!isFolder) {
newFileId = new CmsUUID();
try {
createFileContent(newFileId, filecontent, 0, project.getId(), false);
} catch (CmsException se) {
if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + "] " + se.getMessage());
}
}
}
// write the resource
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_WRITE");
stmt.setString(1, resourceId.toString());
stmt.setInt(2, newResource.getType());
stmt.setInt(3, newResource.getFlags());
stmt.setString(4, newFileId.toString());
stmt.setInt(5, newResource.getLauncherType());
stmt.setString(6, newResource.getLauncherClassname());
stmt.setTimestamp(7, new Timestamp(newResource.getDateCreated()));
stmt.setTimestamp(8, new Timestamp(newResource.getDateLastModified()));
stmt.setInt(9, newResource.getLength());
stmt.executeUpdate();
m_sqlManager.closeAll(null, stmt, null);
// write the structure
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_STRUCTURE_WRITE");
stmt.setString(1, structureId.toString());
stmt.setString(2, parentId.toString());
stmt.setString(3, resourceId.toString());
stmt.setInt(4, project.getId());
stmt.setString(5, newResource.getResourceName());
stmt.setInt(6, 0);
stmt.setInt(7, state);
stmt.setString(8, newResource.isLockedBy().toString());
stmt.setString(9, modifiedByUserId.toString());
stmt.setString(10, userId.toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
return readResource(project, parentId, newResource.getResourceName());
}
/**
* delete all projectResource from an given CmsProject object.
*
* @param project The project in which the resource is used.
*
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void deleteAllProjectResources(int projectId) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_DELETEALL");
stmt.setInt(1, projectId);
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Deletes all properties for a file or folder.
*
* @param resourceId The id of the resource.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void deleteAllProperties(int projectId, CmsResource resource) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_PROPERTIES_DELETEALL");
stmt.setString(1, resource.getId().toString());
stmt.executeUpdate();
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Deletes all properties for a file or folder.
*
* @param resourceId The id of the resource.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void deleteAllProperties(int projectId, CmsUUID resourceId) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
// create statement
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_PROPERTIES_DELETEALL");
stmt.setString(1, resourceId.toString());
stmt.executeUpdate();
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Deletes the file.
*
* @param project The project in which the resource will be used.
* @param filename The complete path of the file.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void deleteFile(CmsProject project, CmsUUID resourceId) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = m_sqlManager.getConnection(project);
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_REMOVE");
stmt.setInt(1, com.opencms.core.I_CmsConstants.C_STATE_DELETED);
stmt.setString(2, CmsUUID.getNullUUID().toString());
stmt.setString(3, resourceId.toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Deletes the folder.
*
* Only empty folders can be deleted yet.
*
* @param project The project in which the resource will be used.
* @param orgFolder The folder that will be deleted.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void deleteFolder(int projectId, CmsFolder orgFolder) throws CmsException {
// the current implementation only deletes empty folders
// check if the folder has any files in it
Vector files = getFilesInFolder(projectId, orgFolder);
files = getUndeletedResources(files);
if (files.size() == 0) {
// check if the folder has any folders in it
Vector folders = getSubFolders(projectId, orgFolder);
folders = getUndeletedResources(folders);
if (folders.size() == 0) {
//this folder is empty, delete it
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_REMOVE");
// mark the folder as deleted
stmt.setInt(1, com.opencms.core.I_CmsConstants.C_STATE_DELETED);
stmt.setString(2, CmsUUID.getNullUUID().toString());
stmt.setString(3, orgFolder.getId().toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + orgFolder.getResourceName(), CmsException.C_NOT_EMPTY);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + orgFolder.getResourceName(), CmsException.C_NOT_EMPTY);
}
}
/**
* delete a projectResource from an given CmsResource object.
*
* @param project The project in which the resource is used.
* @param resource The resource to be deleted from the Cms.
*
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void deleteProjectResource(int projectId, String resourceName) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_DELETE");
// delete resource from the database
stmt.setInt(1, projectId);
stmt.setString(2, resourceName);
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Deletes a specified project
*
* @param project The project to be deleted.
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void deleteProjectResources(CmsProject project) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_DELETE_PROJECT");
// delete all project-resources.
stmt.setInt(1, project.getId());
stmt.executeQuery();
// delete all project-files.
//clearFilesTable();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Deletes a property for a file or folder.
*
* @param meta The property-name of which the property has to be read.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void deleteProperty(String meta, int projectId, CmsResource resource, int resourceType) throws CmsException {
CmsPropertydefinition propdef = readPropertydefinition(meta, 0, resourceType);
if (propdef == null) {
// there is no propdefinition with the overgiven name for the resource
throw new CmsException("[" + this.getClass().getName() + ".deleteProperty] " + meta, CmsException.C_NOT_FOUND);
} else {
// delete the metainfo in the db
Connection conn = null;
PreparedStatement stmt = null;
try {
// create statement
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_PROPERTIES_DELETE");
stmt.setInt(1, propdef.getId());
stmt.setString(2, resource.getId().toString());
stmt.executeUpdate();
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
}
/**
* Delete the propertydefinitions for the resource type.<BR/>
*
* Only the admin can do this.
*
* @param metadef The propertydefinitions to be deleted.
*
* @throws CmsException Throws CmsException if something goes wrong.
*/
public void deletePropertydefinition(CmsPropertydefinition metadef) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
if (countProperties(metadef) != 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + metadef.getName(), CmsException.C_UNKNOWN_EXCEPTION);
}
for (int i = 0; i < 3; i++) {
// delete the propertydef from offline db
if (i == 0) {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTYDEF_DELETE");
}
// delete the propertydef from online db
else if (i == 1) {
conn = m_sqlManager.getConnection(I_CmsConstants.C_PROJECT_ONLINE_ID);
stmt = m_sqlManager.getPreparedStatement(conn, I_CmsConstants.C_PROJECT_ONLINE_ID, "C_PROPERTYDEF_DELETE");
}
// delete the propertydef from backup db
else {
conn = m_sqlManager.getConnectionForBackup();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTYDEF_DELETE_BACKUP");
}
stmt.setInt(1, metadef.getId());
stmt.executeUpdate();
m_sqlManager.closeAll(conn, stmt, null);
}
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Private helper method to delete a resource.
*
* @param id the id of the resource to delete.
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void deleteResource(CmsResource resource) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
// delete resource data from database
conn = m_sqlManager.getConnection(resource.getProjectId());
//stmt = m_sqlManager.getPreparedStatement(conn, resource.getProjectId(), "C_RESOURCES_DELETEBYID");
stmt = m_sqlManager.getPreparedStatement(conn, resource.getProjectId(), "C_RESOURCES_ID_DELETE");
stmt.setString(1, resource.getId().toString());
stmt.executeUpdate();
m_sqlManager.closeAll(null, stmt, null);
// delete the file content
stmt = m_sqlManager.getPreparedStatement(conn, resource.getProjectId(), "C_FILE_CONTENT_DELETE");
stmt.setString(1, resource.getFileId().toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* @see org.opencms.db.I_CmsVfsDriver#destroy()
*/
public void destroy() throws Throwable {
finalize();
if (I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[" + this.getClass().getName() + "] destroyed!");
}
}
/**
* Fetch all VFS links pointing to other VFS resources.
*
* @param theProject the resources in this project are updated
* @param theResourceIDs reference to an ArrayList where the ID's of the fetched links are stored
* @param theLinkContents reference to an ArrayList where the contents of the fetched links (= VFS resource names of the targets) are stored
* @param theResourceTypeLinkID the ID of the link resource type
* @return the count of affected rows
*/
public int fetchAllVfsLinks(CmsProject theProject, ArrayList theResourceIDs, ArrayList theLinkContents, ArrayList theLinkResources, int theResourceTypeLinkID) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
int rowCount = 0;
ResultSet res = null;
try {
// execute the query
conn = m_sqlManager.getConnection(theProject);
stmt = m_sqlManager.getPreparedStatement(conn, theProject, "C_SELECT_VFS_LINK_RESOURCES");
stmt.setInt(1, theResourceTypeLinkID);
res = stmt.executeQuery();
while (res.next()) {
theResourceIDs.add((String) res.getString(1));
theLinkContents.add((String) new String(m_sqlManager.getBytes(res, m_sqlManager.get("C_FILE_CONTENT"))));
theLinkResources.add((String) res.getString(3));
rowCount++;
}
} catch (SQLException e) {
rowCount = 0;
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return rowCount;
}
public long fetchDateFromResource(int theProjectId, int theResourceId, long theDefaultDate) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
ResultSet res = null;
long date_lastModified = theDefaultDate;
try {
// execute the query
conn = m_sqlManager.getConnection(theProjectId);
stmt = m_sqlManager.getPreparedStatement(conn, theProjectId, "C_SELECT_RESOURCE_DATE_LASTMODIFIED");
stmt.setInt(1, theResourceId);
res = stmt.executeQuery();
if (res.next()) {
date_lastModified = SqlHelper.getTimestamp(res, m_sqlManager.get("C_RESOURCES_DATE_LASTMODIFIED")).getTime();
} else {
date_lastModified = theDefaultDate;
}
} catch (SQLException e) {
//System.err.println( "\n[" + this.getClass().getName() + ".fetchDateFromResource()] " + e.toString() );
date_lastModified = theDefaultDate;
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return date_lastModified;
}
/**
* Fetches the RESOURCE_FLAGS attribute for a given resource name.
* This method is slighty more efficient that calling readFileHeader().
*
* @param theProject the current project to choose the right SQL query
* @param theResourceName the name of the resource of which the resource flags are fetched
* @return the value of the resource flag attribute.
* @throws CmsException
*/
public int fetchResourceFlags(CmsProject theProject, String theResourceName) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
int resourceFlags = 0;
ResultSet res = null;
try {
// execute the query
conn = m_sqlManager.getConnection(theProject);
stmt = m_sqlManager.getPreparedStatement(conn, theProject, "C_SELECT_RESOURCE_FLAGS");
stmt.setString(1, theResourceName);
res = stmt.executeQuery();
if (res.next()) {
resourceFlags = res.getInt(1);
} else {
resourceFlags = 0;
}
} catch (SQLException e) {
resourceFlags = 0;
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return resourceFlags;
}
/**
* Fetch the ID for a given VFS link target.
*
* @param theProject the CmsProject where the resource is fetched
* @param theResourceName the name of the resource for which we fetch it's ID
* @param skipResourceTypeID targets of this resource type are ignored
* @return the ID of the resource, or -1
*/
public int fetchResourceID(CmsProject theProject, String theResourceName, int skipResourceTypeID) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
int resourceID = 0;
ResultSet res = null;
try {
// execute the query
conn = m_sqlManager.getConnection(theProject);
stmt = m_sqlManager.getPreparedStatement(conn, theProject, "C_SELECT_RESOURCE_ID");
stmt.setString(1, theResourceName);
res = stmt.executeQuery();
if (res.next()) {
int resourceTypeID = res.getInt(2);
if (resourceTypeID != skipResourceTypeID) {
resourceID = res.getInt(1);
} else {
resourceID = -1;
}
} else {
resourceID = 0;
}
} catch (SQLException e) {
resourceID = 0;
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return resourceID;
}
/**
* Fetches all VFS links pointing to a given resource ID.
*
* @param theProject the current project
* @param theResourceID the ID of the resource of which the VFS links are fetched
* @param theResourceTypeLinkID the resource type ID of VFS links
* @return an ArrayList with the resource names of the fetched VFS links
* @throws CmsException
*/
public ArrayList fetchVfsLinksForResourceID(CmsProject theProject, int theResourceID, int theResourceTypeLinkID) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
ResultSet res = null;
ArrayList vfsLinks = new ArrayList();
try {
// execute the query
conn = m_sqlManager.getConnection(theProject);
stmt = m_sqlManager.getPreparedStatement(conn, theProject, "C_SELECT_VFS_LINKS");
stmt.setInt(1, theResourceID);
stmt.setInt(2, theResourceTypeLinkID);
stmt.setInt(3, com.opencms.core.I_CmsConstants.C_STATE_DELETED);
res = stmt.executeQuery();
while (res.next()) {
CmsResource resource = null;
//this.readFileHeader(theProject.getId(), parentId, res.getString(1), false);
if (resource != null) {
vfsLinks.add(resource);
}
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return vfsLinks;
}
protected void finalize() throws Throwable {
if (m_sqlManager!=null) {
m_sqlManager.finalize();
}
m_sqlManager = null;
m_driverManager = null;
}
/**
* helper method for getBrokenLinks.
*/
protected Vector getAllOnlineReferencesForLink(String link, Vector exceptions) throws CmsException {
Vector resources = new Vector();
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(I_CmsConstants.C_PROJECT_ONLINE_ID);
stmt = m_sqlManager.getPreparedStatement(conn, "C_LM_GET_ONLINE_REFERENCES");
stmt.setString(1, link);
res = stmt.executeQuery();
while (res.next()) {
String resName = res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_NAME"));
if (!exceptions.contains(resName)) {
CmsPageLinks pl = new CmsPageLinks(new CmsUUID(res.getString(m_sqlManager.get("C_LM_PAGE_ID"))));
pl.setOnline(true);
pl.addLinkTarget(link);
pl.setResourceName(resName);
resources.add(pl);
}
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false);
} finally {
// close all db-resources
m_sqlManager.closeAll(conn, stmt, res);
}
return resources;
}
/**
* checks a project for broken links that would appear if the project is published.
*
* @param report A cmsReport object for logging while the method is still running.
* @param changed A vecor (of CmsResources) with the changed resources in the project.
* @param deleted A vecor (of CmsResources) with the deleted resources in the project.
* @param newRes A vecor (of CmsResources) with the new resources in the project.
*/
public void getBrokenLinks(I_CmsReport report, Vector changed, Vector deleted, Vector newRes) throws CmsException {
// first create some Vectors for performance increase
Vector deletedByName = new Vector(deleted.size());
for (int i = 0; i < deleted.size(); i++) {
deletedByName.add(((CmsResource) deleted.elementAt(i)).getResourceName());
}
Vector newByName = new Vector(newRes.size());
for (int i = 0; i < newRes.size(); i++) {
newByName.add(((CmsResource) newRes.elementAt(i)).getResourceName());
}
Vector changedByName = new Vector(changed.size());
for (int i = 0; i < changed.size(); i++) {
changedByName.add(((CmsResource) changed.elementAt(i)).getResourceName());
}
Vector onlineResNames = getOnlineResourceNames();
// now check the new and the changed resources
for (int i = 0; i < changed.size(); i++) {
CmsUUID resId = ((CmsResource) changed.elementAt(i)).getResourceId();
Vector currentLinks = m_driverManager.getProjectDriver().readLinkEntrys(resId);
CmsPageLinks aktualBrokenList = new CmsPageLinks(resId);
for (int index = 0; index < currentLinks.size(); index++) {
String curElement = (String) currentLinks.elementAt(index);
if (!((onlineResNames.contains(curElement) && !deletedByName.contains(curElement)) || (newByName.contains(curElement)))) {
// this is a broken link
aktualBrokenList.addLinkTarget(curElement);
}
}
if (aktualBrokenList.getLinkTargets().size() != 0) {
aktualBrokenList.setResourceName(((CmsResource) changed.elementAt(i)).getResourceName());
report.println(aktualBrokenList);
}
}
for (int i = 0; i < newRes.size(); i++) {
CmsUUID resId = ((CmsResource) newRes.elementAt(i)).getResourceId();
Vector currentLinks = m_driverManager.getProjectDriver().readLinkEntrys(resId);
CmsPageLinks aktualBrokenList = new CmsPageLinks(resId);
for (int index = 0; index < currentLinks.size(); index++) {
String curElement = (String) currentLinks.elementAt(index);
if (!((onlineResNames.contains(curElement) && !deletedByName.contains(curElement)) || (newByName.contains(curElement)))) {
// this is a broken link
aktualBrokenList.addLinkTarget(curElement);
}
}
if (aktualBrokenList.getLinkTargets().size() != 0) {
aktualBrokenList.setResourceName(((CmsResource) newRes.elementAt(i)).getResourceName());
report.println(aktualBrokenList);
}
}
// now we have to check if the deleted resources make any problems
Hashtable onlineResults = new Hashtable();
changedByName.addAll(deletedByName);
for (int i = 0; i < deleted.size(); i++) {
Vector refs = getAllOnlineReferencesForLink(((CmsResource) deleted.elementAt(i)).getResourceName(), changedByName);
for (int index = 0; index < refs.size(); index++) {
CmsPageLinks pl = (CmsPageLinks) refs.elementAt(index);
CmsUUID key = pl.getResourceId();
CmsPageLinks old = (CmsPageLinks) onlineResults.get(key);
if (old == null) {
onlineResults.put(key, pl);
} else {
old.addLinkTarget((String) (pl.getLinkTargets().firstElement()));
}
}
}
// now lets put the results in the report (behind a seperator)
Enumeration enu = onlineResults.elements();
while (enu.hasMoreElements()) {
report.println((CmsPageLinks) enu.nextElement());
}
}
/**
* Returns a Vector with all file headers of a folder.<BR/>
*
* @param parentFolder The folder to be searched.
*
* @return subfiles A Vector with all file headers of the folder.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public Vector getFilesInFolder(int projectId, CmsFolder parentFolder) throws CmsException {
Vector files = new Vector();
ResultSet res = null;
Connection conn = null;
PreparedStatement stmt = null;
try {
// get all files in folder
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_GET_FILESINFOLDER");
stmt.setString(1, parentFolder.getId().toString());
res = stmt.executeQuery();
// create new file objects
while (res.next()) {
files.addElement(createCmsFileFromResultSet(res, projectId, false, false));
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return files;
}
/**
* Returns a Vector with all resource-names that have set the given property to the given value.
*
* @param projectid, the id of the project to test.
* @param propertydef, the name of the propertydefinition to check.
* @param property, the value of the property for the resource.
*
* @return Vector with all names of resources.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public Vector getFilesWithProperty(int projectId, String propertyDefinition, String propertyValue) throws CmsException {
Vector names = new Vector();
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_GET_FILES_WITH_PROPERTY");
stmt.setInt(1, projectId);
stmt.setString(2, propertyValue);
stmt.setString(3, propertyDefinition);
res = stmt.executeQuery();
// store the result into the vector
while (res.next()) {
String result = res.getString(1);
names.addElement(result);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception exc) {
throw m_sqlManager.getCmsException(this, "getFilesWithProperty(int, String, String)", CmsException.C_UNKNOWN_EXCEPTION, exc, false);
} finally {
// close all db-resources
m_sqlManager.closeAll(conn, stmt, res);
}
return names;
}
/**
* @see org.opencms.db.I_CmsVfsDriver#getFolderTree(com.opencms.file.CmsProject, com.opencms.file.CmsResource)
*/
public List getFolderTree(CmsProject currentProject, CmsResource parentResource) throws CmsException {
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
CmsFolder currentFolder = null;
CmsAdjacencyTree tree = new CmsAdjacencyTree();
/*
* possible other SQL queries to select a tree view:
* SELECT PARENT.RESOURCE_NAME, CHILD.RESOURCE_NAME FROM CMS_OFFLINE_STRUCTURE PARENT, CMS_OFFLINE_STRUCTURE CHILD WHERE PARENT.STRUCTURE_ID=CHILD.PARENT_ID;
* SELECT PARENT.RESOURCE_NAME,CHILD.RESOURCE_NAME FROM CMS_OFFLINE_STRUCTURE PARENT LEFT JOIN CMS_OFFLINE_STRUCTURE CHILD ON PARENT.STRUCTURE_ID=CHILD.PARENT_ID;
*/
try {
conn = m_sqlManager.getConnection(currentProject);
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_RESOURCES_GET_FOLDERTREE");
res = stmt.executeQuery();
while (res.next()) {
currentFolder = createCmsFolderFromResultSet(res, currentProject.getId(), true);
tree.addResource(currentFolder);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return tree.toList(parentResource);
}
/**
* This method reads all resource names from the table CmsOnlineResources
*
* @return A Vector (of Strings) with the resource names (like from getAbsolutePath())
*/
public Vector getOnlineResourceNames() throws CmsException {
Vector resources = new Vector();
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(I_CmsConstants.C_PROJECT_ONLINE_ID);
stmt = m_sqlManager.getPreparedStatement(conn, "C_LM_GET_ALL_ONLINE_RES_NAMES");
res = stmt.executeQuery();
// create new resource
while (res.next()) {
String resName = res.getString(m_sqlManager.get("C_RESOURCES_RESOURCE_NAME"));
resources.add(resName);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, "getOnlineResourceNames()", CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw m_sqlManager.getCmsException(this, "getOnlineResourceNames()", CmsException.C_UNKNOWN_EXCEPTION, ex, false);
} finally {
// close all db-resources
m_sqlManager.closeAll(conn, stmt, res);
}
return resources;
}
/**
* Reads all resources (including the folders) residing in a folder<BR>
*
* @param onlineResource the parent resource id of the online resoure.
* @param offlineResource the parent resource id of the offline resoure.
*
* @return A Vecor of resources.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public Vector getResourcesInFolder(int projectId, CmsFolder offlineResource) throws CmsException {
Vector resources = new Vector();
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
CmsResource currentResource = null;
CmsFolder currentFolder = null;
// first get the folderst
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_GET_FOLDERS_IN_FOLDER");
stmt.setString(1, offlineResource.getId().toString());
//stmt.setInt(2, projectId);
res = stmt.executeQuery();
while (res.next()) {
currentFolder = createCmsFolderFromResultSet(res, projectId, true);
resources.addElement(currentFolder);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw new CmsException("[" + this.getClass().getName() + "]", ex);
} finally {
m_sqlManager.closeAll(null, stmt, res);
}
// then get the resources
try {
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_GET_RESOURCES_IN_FOLDER");
stmt.setString(1, offlineResource.getId().toString());
//stmt.setInt(2, projectId);
res = stmt.executeQuery();
while (res.next()) {
currentResource = createCmsResourceFromResultSet(res, projectId);
resources.addElement(currentResource);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw new CmsException("[" + this.getClass().getName() + "]", ex);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return resources;
}
/**
* Returns a Vector with all resources of the given type
* that have set the given property. For the start it is
* only used by the static export so it reads the online project only.
*
* @param projectid, the id of the project to test.
* @param propertyDefinition, the name of the propertydefinition to check.
*
* @return Vector with all resources.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public Vector getResourcesWithProperty(int projectId, String propertyDefName) throws CmsException {
Vector resources = new Vector();
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_GET_RESOURCE_WITH_PROPERTYDEF");
stmt.setString(1, propertyDefName);
res = stmt.executeQuery();
while (res.next()) {
CmsResource resource = createCmsResourceFromResultSet(res, projectId);
resources.addElement(resource);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return resources;
}
/**
* Returns a Vector with all resources of the given type
* that have set the given property to the given value.
*
* @param projectid, the id of the project to test.
* @param propertyDefinition, the name of the propertydefinition to check.
* @param propertyValue, the value of the property for the resource.
* @param resourceType, the value of the resourcetype.
*
* @return Vector with all resources.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public Vector getResourcesWithProperty(int projectId, String propertyDefinition, String propertyValue, int resourceType) throws CmsException {
Vector resources = new Vector();
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_GET_RESOURCE_WITH_PROPERTY");
stmt.setInt(1, projectId);
stmt.setString(2, propertyValue);
stmt.setString(3, propertyDefinition);
stmt.setInt(4, resourceType);
res = stmt.executeQuery();
String lastResourcename = "";
while (res.next()) {
CmsResource resource = createCmsResourceFromResultSet(res, projectId);
if (!resource.getName().equalsIgnoreCase(lastResourcename)) {
resources.addElement(resource);
}
lastResourcename = resource.getName();
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception exc) {
throw new CmsException("getResourcesWithProperty" + exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return resources;
}
/**
* Returns a Vector with all subfolders.<BR/>
*
* @param parentFolder The folder to be searched.
*
* @return Vector with all subfolders for the given folder.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public Vector getSubFolders(int projectId, CmsFolder parentFolder) throws CmsException {
Vector folders = new Vector();
CmsFolder folder = null;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
// get all subfolders
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_GET_SUBFOLDER");
stmt.setString(1, parentFolder.getId().toString());
res = stmt.executeQuery();
// create new folder objects
while (res.next()) {
folder = createCmsFolderFromResultSet(res, projectId, false);
folders.addElement(folder);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception exc) {
throw new CmsException("getSubFolders " + exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return folders;
}
/**
* Gets all resources that are marked as undeleted.
* @param resources Vector of resources
* @return Returns all resources that are markes as deleted
*/
public Vector getUndeletedResources(Vector resources) {
Vector undeletedResources = new Vector();
for (int i = 0; i < resources.size(); i++) {
CmsResource res = (CmsResource) resources.elementAt(i);
if (res.getState() != I_CmsConstants.C_STATE_DELETED) {
undeletedResources.addElement(res);
}
}
return undeletedResources;
}
public void init(Configurations config, String dbPoolUrl, CmsDriverManager driverManager) {
m_sqlManager = this.initQueries(dbPoolUrl);
m_driverManager = driverManager;
if (I_CmsLogChannels.C_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, ". VFS driver init : ok");
}
}
/**
* @see org.opencms.db.I_CmsVfsDriver#initQueries(java.lang.String)
*/
public org.opencms.db.generic.CmsSqlManager initQueries(String dbPoolUrl) {
return new org.opencms.db.generic.CmsSqlManager(dbPoolUrl);
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @throws CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(int projectId, I_CmsResourceType resourcetype) throws CmsException {
return (readAllPropertydefinitions(projectId, resourcetype.getResourceType()));
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @throws CmsException Throws CmsException if something goes wrong.
*/
// TODO: check if propertydefs have online and offline tables
public Vector readAllPropertydefinitions(int projectId, int resourcetype) throws CmsException {
Vector metadefs = new Vector();
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_PROPERTYDEF_READALL");
// create statement
stmt.setInt(1, resourcetype);
res = stmt.executeQuery();
while (res.next()) {
metadefs.addElement(new CmsPropertydefinition(res.getInt(m_sqlManager.get("C_PROPERTYDEF_ID")), res.getString(m_sqlManager.get("C_PROPERTYDEF_NAME")), res.getInt(m_sqlManager.get("C_PROPERTYDEF_RESOURCE_TYPE"))));
}
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return (metadefs);
}
/**
* select a projectResource from an given project and resourcename
*
* @param project The project in which the resource is used.
* @param resource The resource to be read from the Cms.
*
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public Vector readBackupProjectResources(int versionId) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
ResultSet res = null;
Vector projectResources = new Vector();
try {
conn = m_sqlManager.getConnectionForBackup();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_READ_BACKUP");
// select resource from the database
stmt.setInt(1, versionId);
res = stmt.executeQuery();
while (res.next()) {
projectResources.addElement(res.getString("RESOURCE_NAME"));
}
res.close();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return projectResources;
}
/**
* Reads a file from the Cms.<BR/>
*
* @param projectId The Id of the project in which the resource will be used.
* @param onlineProjectId The online projectId of the OpenCms.
* @param filename The complete name of the new file (including pathinformation).
*
* @return file The read file.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFile(int projectId, boolean includeDeleted, CmsUUID structureId) throws CmsException {
CmsFile file = null;
PreparedStatement stmt = null;
ResultSet res = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_FILES_READ");
stmt.setString(1, structureId.toString());
//stmt.setInt(2, projectId);
res = stmt.executeQuery();
if (res.next()) {
file = createCmsFileFromResultSet(res, projectId);
while (res.next()) {
// do nothing only move through all rows because of mssql odbc driver
}
// check if this resource is marked as deleted
if (file.getState() == com.opencms.core.I_CmsConstants.C_STATE_DELETED && !includeDeleted) {
throw new CmsException("[" + this.getClass().getName() + ".readFile] " + file.getResourceName(), CmsException.C_RESOURCE_DELETED);
}
} else {
throw new CmsException("[" + this.getClass().getName() + ".readFile] " + structureId.toString(), CmsException.C_NOT_FOUND);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (CmsException ex) {
throw ex;
} catch (Exception exc) {
throw new CmsException("readFile " + exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return file;
}
/**
* Private helper method to read the fileContent for publishProject(export).
*
* @param fileId the fileId.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
// public byte[] readFileContent(int projectId, int fileId) throws CmsException {
// PreparedStatement stmt = null;
// ResultSet res = null;
// Connection conn = null;
// byte[] returnValue = null;
// try {
// conn = m_sqlManager.getConnection(projectId);
// stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_FILE_READ");
// // read fileContent from database
// stmt.setInt(1, fileId);
// res = stmt.executeQuery();
// if (res.next()) {
// returnValue = res.getBytes(m_sqlManager.get("C_FILE_CONTENT"));
// } else {
// throw new CmsException("[" + this.getClass().getName() + "]" + fileId, CmsException.C_NOT_FOUND);
// } catch (SQLException e) {
// throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
// } finally {
// m_sqlManager.closeAll(conn, stmt, res);
// return returnValue;
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent.
*
* @param projectId The Id of the project
* @param resourceId The Id of the resource.
*
* @return file The read file.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFileHeader(int projectId, CmsResource resource) throws CmsException {
CmsFile file = null;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READBYID");
// read file data from database
stmt.setString(1, resource.getId().toString());
res = stmt.executeQuery();
// create new file
if (res.next()) {
file = createCmsFileFromResultSet(res, projectId, true, false);
while (res.next()) {
// do nothing only move through all rows because of mssql odbc driver
}
// check if this resource is marked as deleted
if (file.getState() == com.opencms.core.I_CmsConstants.C_STATE_DELETED) {
throw new CmsException("[" + this.getClass().getName() + ".readFileHeader/1] " + file.getResourceName(), CmsException.C_RESOURCE_DELETED);
}
} else {
throw new CmsException("[" + this.getClass().getName() + ".readFileHeader/1] " + resource.getResourceName(), CmsException.C_NOT_FOUND);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (CmsException ex) {
throw ex;
} catch (Exception exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return file;
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent.
*
* @param projectId The Id of the project
* @param resourceId The Id of the resource.
*
* @return file The read file.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFileHeader(int projectId, CmsUUID resourceId, boolean includeDeleted) throws CmsException {
CmsFile file = null;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READBYID");
// read file data from database
stmt.setString(1, resourceId.toString());
res = stmt.executeQuery();
// create new file
if (res.next()) {
file = createCmsFileFromResultSet(res, projectId, true, false);
while (res.next()) {
// do nothing only move through all rows because of mssql odbc driver
}
// check if this resource is marked as deleted
if ((file.getState() == com.opencms.core.I_CmsConstants.C_STATE_DELETED) && !includeDeleted) {
throw new CmsException("[" + this.getClass().getName() + ".readFileHeader/2] " + file.getResourceName(), CmsException.C_RESOURCE_DELETED);
}
} else {
throw new CmsException("[" + this.getClass().getName() + ".readFileHeader/2] " + resourceId, CmsException.C_NOT_FOUND);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (CmsException ex) {
throw ex;
} catch (Exception exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return file;
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent.
*
* @param projectId The Id of the project in which the resource will be used.
* @param filename The complete name of the new file (including pathinformation).
*
* @return file The read file.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFileHeader(int projectId, CmsUUID parentId, String filename, boolean includeDeleted) throws CmsException {
CmsFile file = null;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READ");
stmt.setString(1, filename);
stmt.setString(2, parentId.toString());
//stmt.setInt(3, projectId);
res = stmt.executeQuery();
if (res.next()) {
file = createCmsFileFromResultSet(res, projectId, true, false);
while (res.next()) {
// do nothing only move through all rows because of mssql odbc driver
}
// check if this resource is marked as deleted
if ((file.getState() == com.opencms.core.I_CmsConstants.C_STATE_DELETED) && !includeDeleted) {
throw new CmsException("[" + this.getClass().getName() + ".readFileHeader/3] " + file.getResourceName(), CmsException.C_RESOURCE_DELETED);
}
} else {
throw new CmsException("[" + this.getClass().getName() + ".readFileHeader/3] " + filename, CmsException.C_NOT_FOUND);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (CmsException ex) {
throw ex;
} catch (Exception exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return file;
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent.
*
* @param projectId The Id of the project in which the resource will be used.
* @param filename The complete name of the new file (including pathinformation).
*
* @return file The read file.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
// public CmsFile readFileHeaderInProject(int projectId, String filename) throws CmsException {
// CmsFile file = null;
// ResultSet res = null;
// PreparedStatement stmt = null;
// Connection conn = null;
// try {
// conn = m_sqlManager.getConnection(projectId);
// stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READINPROJECT");
// stmt.setString(1, filename);
// stmt.setInt(2, projectId);
// res = stmt.executeQuery();
// if (res.next()) {
// file = createCmsFileFromResultSet(res, true, false);
// while (res.next()) {
// // do nothing only move through all rows because of mssql odbc driver
// // check if this resource is marked as deleted
// if (file.getState() == com.opencms.core.I_CmsConstants.C_STATE_DELETED) {
// throw new CmsException("[" + this.getClass().getName() + "] " + cms.readPath(file), CmsException.C_RESOURCE_DELETED);
// } else {
// throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NOT_FOUND);
// } catch (SQLException e) {
// throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
// } catch (CmsException ex) {
// throw ex;
// } catch (Exception exc) {
// throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false);
// } finally {
// m_sqlManager.closeAll(conn, stmt, res);
// return file;
/**
* Reads a file in the project from the Cms.<BR/>
*
* @param projectId The Id of the project in which the resource will be used.
* @param onlineProjectId The online projectId of the OpenCms.
* @param filename The complete name of the new file (including pathinformation).
*
* @return file The read file.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
// public CmsFile readFileInProject(int projectId, int onlineProjectId, String filename) throws CmsException {
// CmsFile file = null;
// PreparedStatement stmt = null;
// ResultSet res = null;
// Connection conn = null;
// try {
// conn = m_sqlManager.getConnection(projectId);
// stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_FILES_READINPROJECT");
// stmt.setString(1, filename);
// stmt.setInt(2, projectId);
// res = stmt.executeQuery();
// if (res.next()) {
// file = createCmsFileFromResultSet(res, projectId);
// while (res.next()) {
// // do nothing only move through all rows because of mssql odbc driver
// } else {
// throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NOT_FOUND);
// } catch (SQLException e) {
// throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
// } catch (CmsException ex) {
// throw ex;
// } catch (Exception exc) {
// throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false);
// } finally {
// m_sqlManager.closeAll(conn, stmt, res);
// return file;
/**
* Reads all files from the Cms, that are in one project.<BR/>
*
* @param project The project in which the files are.
*
* @return A Vecor of files.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public List readFiles(int projectId, boolean includeUnchanged, boolean onlyProject) throws CmsException {
List files = (List) new ArrayList();
CmsFile currentFile;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
String changedClause = null;
String projectClause = null;
String orderClause = " ORDER BY CMS_T_STRUCTURE.STRUCTURE_ID ASC";
String query = null;
if (projectId != I_CmsConstants.C_PROJECT_ONLINE_ID && onlyProject) {
projectClause = " AND CMS_T_STRUCTURE.PROJECT_ID=" + projectId;
} else {
projectClause = "";
}
if (!includeUnchanged) {
// TODO: dangerous - move this to query.properties
changedClause = " AND CMS_T_STRUCTURE.RESOURCE_STATE!=" + com.opencms.core.I_CmsConstants.C_STATE_UNCHANGED;
} else {
changedClause = "";
}
try {
conn = m_sqlManager.getConnection(projectId);
query = m_sqlManager.get(projectId, "C_RESOURCES_READ_FILES_BY_PROJECT") + m_sqlManager.replaceTableKey(projectId, projectClause + changedClause + orderClause);
stmt = m_sqlManager.getPreparedStatementForSql(conn, query);
//stmt.setInt(1, projectId);
res = stmt.executeQuery();
while (res.next()) {
currentFile = createCmsFileFromResultSet(res, projectId, true, true);
files.add(currentFile);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return files;
}
/**
* Reads all files from the Cms, that are of the given type.<BR/>
*
* @param projectId A project id for reading online or offline resources
* @param resourcetype The type of the files.
*
* @return A Vector of files.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public Vector readFilesByType(int projectId, int resourcetype) throws CmsException {
Vector files = new Vector();
CmsFile file;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READ_FILESBYTYPE");
// read file data from database
stmt.setInt(1, resourcetype);
res = stmt.executeQuery();
// create new file
while (res.next()) {
file = createCmsFileFromResultSet(res, projectId, true, true);
files.addElement(file);
}
} catch (SQLException e) {
e.printStackTrace();
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return files;
}
/**
* Reads a folder from the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param folderid The id of the folder to be read.
*
* @return The read folder.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder readFolder(int projectId, CmsUUID folderId) throws CmsException {
CmsFolder folder = null;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READBYID");
stmt.setString(1, folderId.toString());
res = stmt.executeQuery();
if (res.next()) {
folder = createCmsFolderFromResultSet(res, projectId, true);
while (res.next()) {
// do nothing only move through all rows because of mssql odbc driver
}
} else {
throw new CmsException("[" + this.getClass().getName() + ".readFolder/1] " + folderId, CmsException.C_NOT_FOUND);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (CmsException exc) {
throw exc;
} catch (Exception exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return folder;
}
/**
* Reads a folder from the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param foldername The name of the folder to be read.
*
* @return The read folder.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder readFolder(int projectId, CmsUUID parentId, String foldername) throws CmsException {
CmsFolder folder = null;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READ");
stmt.setString(1, foldername);
stmt.setString(2, parentId.toString());
res = stmt.executeQuery();
if (res.next()) {
folder = createCmsFolderFromResultSet(res, projectId, true);
while (res.next()) {
// do nothing only move through all rows because of mssql odbc driver
}
} else {
throw new CmsException("[" + this.getClass().getName() + ".readFolder/2] " + foldername, CmsException.C_NOT_FOUND);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (CmsException exc) {
throw exc;
} catch (Exception exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return folder;
}
/**
* Reads a folder from the Cms that exists in the project.<BR/>
*
* @param project The project in which the resource will be used.
* @param foldername The name of the folder to be read.
*
* @return The read folder.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
// public CmsFolder readFolderInProject(int projectId, String foldername) throws CmsException {
// CmsFolder folder = null;
// ResultSet res = null;
// PreparedStatement stmt = null;
// Connection conn = null;
// try {
// conn = m_sqlManager.getConnection(projectId);
// stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READINPROJECT");
// stmt.setString(1, foldername);
// stmt.setInt(2, projectId);
// res = stmt.executeQuery();
// if (res.next()) {
// folder = createCmsFolderFromResultSet(res, true);
// while (res.next()) {
// // do nothing only move through all rows because of mssql odbc driver
// } else {
// throw new CmsException("[" + this.getClass().getName() + "] " + foldername, CmsException.C_NOT_FOUND);
// } catch (SQLException e) {
// throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
// } catch (CmsException exc) {
// // just throw this exception
// throw exc;
// } catch (Exception exc) {
// throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false);
// } finally {
// m_sqlManager.closeAll(conn, stmt, res);
// return folder;
/**
* Reads all folders from the Cms, that are in one project.<BR/>
*
* @param project The project in which the folders are.
*
* @return A Vecor of folders.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
/**
* Reads all folders from the Cms, that are in one project.<BR/>
*
* @param project The project in which the folders are.
*
* @return A Vecor of folders.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public List readFolders(CmsProject currentProject, boolean includeUnchanged, boolean onlyProject) throws CmsException {
List folders = (List) new ArrayList();
CmsFolder currentFolder;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
String changedClause = null;
String projectClause = null;
String orderClause = " ORDER BY CMS_T_STRUCTURE.STRUCTURE_ID ASC";
String query = null;
int projectId = currentProject.getId();
if (projectId != I_CmsConstants.C_PROJECT_ONLINE_ID && onlyProject) {
projectClause = " AND CMS_T_STRUCTURE.PROJECT_ID=" + projectId;
} else {
projectClause = "";
}
if (!includeUnchanged) {
// TODO: dangerous - move this to query.properties
changedClause = " AND CMS_T_STRUCTURE.RESOURCE_STATE!=" + I_CmsConstants.C_STATE_UNCHANGED;
} else {
projectClause = "";
}
try {
conn = m_sqlManager.getConnection(projectId);
query = m_sqlManager.get(projectId, "C_RESOURCES_READ_FOLDERS_BY_PROJECT") + m_sqlManager.replaceTableKey(projectId, projectClause + changedClause + orderClause);
stmt = m_sqlManager.getPreparedStatementForSql(conn, query);
//stmt.setInt(1, projectId);
res = stmt.executeQuery();
while (res.next()) {
currentFolder = createCmsFolderFromResultSet(res, projectId, true);
folders.add(currentFolder);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return folders;
}
/**
* @see org.opencms.db.I_CmsVfsDriver#readProjectResource(int, java.lang.String)
*/
public String readProjectResource(int projectId, String resourcename) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
ResultSet res = null;
String resName = null;
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_READ");
// select resource from the database
stmt.setInt(1, projectId);
stmt.setString(2, resourcename);
res = stmt.executeQuery();
if (res.next()) {
resName = res.getString("RESOURCE_NAME");
} else {
throw new CmsException("[" + this.getClass().getName() + ".readProjectResource] " + resourcename, CmsException.C_NOT_FOUND);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return resName;
}
/**
* @see org.opencms.db.I_CmsVfsDriver#readProjectResource(com.opencms.file.CmsProject)
*/
public String readProjectResource(CmsProject project) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
ResultSet res = null;
String resName = null;
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_READ_BY_ID");
stmt.setInt(1, project.getId());
stmt.setString(2, "%" + I_CmsConstants.C_FOLDER_SEPARATOR + I_CmsConstants.C_ROOTNAME_VFS + I_CmsConstants.C_FOLDER_SEPARATOR + "%");
stmt.setInt(3, project.getId());
stmt.setString(4, I_CmsConstants.C_ROOT);
res = stmt.executeQuery();
if (res.next()) {
resName = res.getString("RESOURCE_NAME");
} else {
throw new CmsException("[" + this.getClass().getName() + ".readProjectResource] no project resource for ID: " + project.getId(), CmsException.C_NOT_FOUND);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return resName;
}
/**
* Returns a list of all properties of a file or folder.<p>
*
* @param resourceId the id of the resource
* @param resource the resource to read the properties from
* @param resourceType the type of the resource
*
* @return a Map of Strings representing the properties of the resource
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public HashMap readProperties(int projectId, CmsResource resource, int resourceType) throws CmsException {
HashMap returnValue = new HashMap();
ResultSet result = null;
PreparedStatement stmt = null;
Connection conn = null;
CmsUUID resourceId = resource.getId();
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_PROPERTIES_READALL");
stmt.setString(1, resourceId.toString());
stmt.setInt(2, resourceType);
result = stmt.executeQuery();
while (result.next()) {
returnValue.put(result.getString(m_sqlManager.get("C_PROPERTYDEF_NAME")), result.getString(m_sqlManager.get("C_PROPERTY_VALUE")));
}
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, result);
}
return (returnValue);
}
/**
* Returns a property of a file or folder.
*
* @param meta The property-name of which the property has to be read.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @return property The property as string or null if the property not exists.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public String readProperty(String meta, int projectId, CmsResource resource, int resourceType) throws CmsException {
ResultSet result = null;
PreparedStatement stmt = null;
Connection conn = null;
String returnValue = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_PROPERTIES_READ");
String structureId = resource.getId().toString();
stmt.setString(1, structureId);
stmt.setString(2, meta);
stmt.setInt(3, resourceType);
result = stmt.executeQuery();
if (result.next()) {
returnValue = result.getString(m_sqlManager.get("C_PROPERTY_VALUE"));
}
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, result);
}
return returnValue;
}
/**
* Reads a propertydefinition for the given resource type.
*
* @param name The name of the propertydefinition to read.
* @param type The resource type for which the propertydefinition is valid.
*
* @return propertydefinition The propertydefinition that corresponds to the overgiven
* arguments - or null if there is no valid propertydefinition.
*
* @throws CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition readPropertydefinition(String name, int projectId, I_CmsResourceType type) throws CmsException {
return (readPropertydefinition(name, projectId, type.getResourceType()));
}
/**
* Reads a propertydefinition for the given resource type.
*
* @param name The name of the propertydefinition to read.
* @param type The resource type for which the propertydefinition is valid.
*
* @return propertydefinition The propertydefinition that corresponds to the overgiven
* arguments - or null if there is no valid propertydefinition.
*
* @throws CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition readPropertydefinition(String name, int projectId, int type) throws CmsException {
CmsPropertydefinition propDef = null;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_PROPERTYDEF_READ");
stmt.setString(1, name);
stmt.setInt(2, type);
res = stmt.executeQuery();
// if resultset exists - return it
if (res.next()) {
propDef = new CmsPropertydefinition(res.getInt(m_sqlManager.get("C_PROPERTYDEF_ID")), res.getString(m_sqlManager.get("C_PROPERTYDEF_NAME")), res.getInt(m_sqlManager.get("C_PROPERTYDEF_RESOURCE_TYPE")));
} else {
res.close();
res = null;
// not found!
throw new CmsException("[" + this.getClass().getName() + ".readPropertydefinition] " + name, CmsException.C_NOT_FOUND);
}
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return propDef;
}
/**
* Reads a resource from the Cms.<BR/>
* A resource is either a file header or a folder.
*
* @param project The project in which the resource will be used.
* @param filename The complete name of the new file (including pathinformation).
*
* @return The resource read.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public CmsResource readResource(CmsProject project, CmsUUID parentId, String filename) throws CmsException {
CmsResource file = null;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(project);
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_READ");
stmt.setString(1, filename);
stmt.setString(2, parentId.toString());
res = stmt.executeQuery();
if (res.next()) {
file = createCmsResourceFromResultSet(res, project.getId());
while (res.next()) {
// do nothing only move through all rows because of mssql odbc driver
}
} else {
throw new CmsException("[" + this.getClass().getName() + ".readResource] " + filename, CmsException.C_NOT_FOUND);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception exc) {
throw new CmsException("readResource " + exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return file;
}
/**
* Reads all resource from the Cms, that are in one project.<BR/>
* A resource is either a file header or a folder.
*
* @param project The project in which the resource will be used.
*
* @return A Vecor of resources.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public Vector readResources(CmsProject project) throws CmsException {
Vector resources = new Vector();
CmsResource file;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(project);
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_READBYPROJECT");
// read resource data from database
stmt.setInt(1, project.getId());
res = stmt.executeQuery();
// create new resource
while (res.next()) {
file = createCmsResourceFromResultSet(res, project.getId());
resources.addElement(file);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw new CmsException("[" + this.getClass().getName() + "]", ex);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return resources;
}
/**
* Reads all resources that contains the given string in the resourcename
* and exists in the current project.<BR/>
* A resource is either a file header or a folder.
*
* @param project The project in which the resource will be used.
* @param resourcename A part of the resourcename
*
* @return A Vecor of resources.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public Vector readResourcesLikeName(CmsProject project, String resourcename) throws CmsException {
Vector resources = new Vector();
CmsResource file;
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
String usedStatement = "";
if (project.getId() == I_CmsConstants.C_PROJECT_ONLINE_ID) {
usedStatement = "_ONLINE";
} else {
usedStatement = "";
}
try {
conn = m_sqlManager.getConnection(project);
// read resource data from database
//stmt = conn.prepareStatement(m_sqlManager.get("C_RESOURCES_READ_LIKENAME_1" + usedStatement) + resourcename + m_sqlManager.get("C_RESOURCES_READ_LIKENAME_2" + usedStatement));
stmt = m_sqlManager.getPreparedStatementForSql(conn, m_sqlManager.get("C_RESOURCES_READ_LIKENAME_1" + usedStatement) + resourcename + m_sqlManager.get("C_RESOURCES_READ_LIKENAME_2" + usedStatement));
stmt.setInt(1, project.getId());
res = stmt.executeQuery();
// create new resource
while (res.next()) {
file = createCmsResourceFromResultSet(res, project.getId());
resources.addElement(file);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} catch (Exception ex) {
throw new CmsException("[" + this.getClass().getName() + "]", ex);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return resources;
}
/**
* @see org.opencms.db.I_CmsVfsDriver#removeFile(int, com.opencms.flex.util.CmsUUID)
*/
public void removeFile(CmsProject currentProject, CmsUUID resourceId) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(currentProject);
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_FILE_DELETE_BY_ID");
stmt.setString(1, resourceId.toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
public void removeFile(CmsProject currentProject, CmsUUID parentId, String filename) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(currentProject);
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_FILE_DELETE_BY_NAME");
stmt.setString(1,parentId.toString());
stmt.setString(2,filename);
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Deletes a folder in the database.
* This method is used to physically remove a folder form the database.
*
* @param folder The folder.
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void removeFolder(int projectId, CmsFolder folder) throws CmsException {
// the current implementation only deletes empty folders
// check if the folder has any files in it
Vector files = getFilesInFolder(projectId, folder);
files = getUndeletedResources(files);
if (files.size() == 0) {
// check if the folder has any folders in it
Vector folders = getSubFolders(projectId, folder);
folders = getUndeletedResources(folders);
if (folders.size() == 0) {
//this folder is empty, delete it
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_ID_DELETE");
// delete the folder
stmt.setString(1, folder.getId().toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + folder.getResourceName(), CmsException.C_NOT_EMPTY);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + folder.getResourceName(), CmsException.C_NOT_EMPTY);
}
}
/**
* Deletes a folder in the database.
* This method is used to physically remove a folder form the database.
* It is internally used by the publish project method.
*
* @param project The project in which the resource will be used.
* @param foldername The complete path of the folder.
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void removeFolderForPublish(CmsProject currentProject, CmsUUID folderId) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(currentProject);
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_RESOURCES_DELETE");
// delete the folder
stmt.setString(1, folderId.toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
// close all db-resources
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Removes the temporary files of the given resource
*
* @param file The file of which the remporary files should be deleted
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void removeTemporaryFile(CmsFile file) throws CmsException {
PreparedStatement stmt = null;
PreparedStatement statementCont = null;
PreparedStatement statementProp = null;
Connection conn = null;
ResultSet res = null;
String fileId = null;
String structureId = null;
boolean hasBatch = false;
//String tempFilename = file.getRootName() + file.getPath() + I_CmsConstants.C_TEMP_PREFIX + file.getName() + "%";
String tempFilename = I_CmsConstants.C_TEMP_PREFIX + file.getResourceName() + "%";
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_GETTEMPFILES");
stmt.setString(1, tempFilename);
stmt.setString(2, file.getParentId().toString());
res = stmt.executeQuery();
statementProp = m_sqlManager.getPreparedStatement(conn, "C_PROPERTIES_DELETEALL");
statementCont = m_sqlManager.getPreparedStatement(conn, "C_FILE_CONTENT_DELETE");
while (res.next()) {
hasBatch = true;
fileId = res.getString("FILE_ID");
structureId = res.getString("STRUCTURE_ID");
// delete the properties
statementProp.setString(1, structureId);
statementProp.addBatch();
// delete the file content
statementCont.setString(1, fileId);
statementCont.addBatch();
}
if (hasBatch) {
statementProp.executeBatch();
statementCont.executeBatch();
m_sqlManager.closeAll(null, stmt, res);
stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_DELETETEMPFILES");
stmt.setString(1, tempFilename);
stmt.setString(2, file.getParentId().toString());
stmt.executeUpdate();
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
m_sqlManager.closeAll(null, statementProp, null);
m_sqlManager.closeAll(null, statementCont, null);
}
}
/**
* Renames the file to the new name.
*
* @param project The prect in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param userId The user id
* @param oldfileID The id of the resource which will be renamed.
* @param newname The new name of the resource.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public int renameResource(CmsUser currentUser, CmsProject currentProject, CmsResource resource, String newname) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
int count = 0;
long dateModified = resource.isTouched() ? resource.getDateLastModified() : System.currentTimeMillis();
try {
conn = m_sqlManager.getConnection(currentProject);
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_RESOURCE_RENAME");
stmt.setString(1, newname);
stmt.setTimestamp(2, new Timestamp(dateModified));
stmt.setString(3, currentUser.getId().toString());
stmt.setInt(4, I_CmsConstants.C_STATE_CHANGED);
stmt.setString(5, resource.getId().toString());
count = stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
return count;
}
/**
* Update the resources flag attribute of all resources.
*
* @param theProject the resources in this project are updated
* @param theValue the new int value of the resource fags attribute
* @return the count of affected rows
*/
public int updateAllResourceFlags(CmsProject theProject, int theValue) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
int rowCount = 0;
try {
// execute the query
conn = m_sqlManager.getConnection(theProject);
stmt = m_sqlManager.getPreparedStatement(conn, theProject, "C_UPDATE_ALL_RESOURCE_FLAGS");
stmt.setInt(1, theValue);
rowCount = stmt.executeUpdate();
} catch (SQLException e) {
rowCount = 0;
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
return rowCount;
}
public void updateLockstate(CmsResource res, int projectId) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_UPDATE_LOCK");
stmt.setString(1, res.isLockedBy().toString());
stmt.setInt(2, projectId);
stmt.setString(3, res.getId().toString());
stmt.executeUpdate();
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Update the resource flag attribute for a given resource.
*
* @param theProject the CmsProject where the resource is updated
* @param theResourceID the ID of the resource which is updated
* @param theValue the new value of the resource flag attribute
* @return the count of affected rows (should be 1, unless an error occurred)
*/
public int updateResourceFlags(CmsProject theProject, int theResourceID, int theValue) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
int rowCount = 0;
try {
// execute the query
conn = m_sqlManager.getConnection(theProject);
stmt = m_sqlManager.getPreparedStatement(conn, theProject, "C_UPDATE_RESOURCE_FLAGS");
stmt.setInt(1, theValue);
stmt.setInt(2, theResourceID);
rowCount = stmt.executeUpdate();
} catch (SQLException e) {
rowCount = 0;
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
return rowCount;
}
/**
* Updates the state of a Resource.
*
* @param res com.opencms.file.CmsResource
* @throws com.opencms.core.CmsException The exception description.
*/
public void updateResourcestate(CmsResource res) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(res.getProjectId());
stmt = m_sqlManager.getPreparedStatement(conn, res.getProjectId(), "C_RESOURCES_UPDATE_STATE");
stmt.setInt(1, res.getState());
stmt.setString(2, res.getId().toString());
stmt.executeUpdate();
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
// close all db-resources
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Writes a file to the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param file The new file.
* @param changed Flag indicating if the file state must be set to changed.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void writeFile(CmsProject project, CmsFile file, boolean changed) throws CmsException {
writeFile(project, file, changed, file.getResourceLastModifiedBy());
}
/**
* Writes a file to the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param file The new file.
* @param changed Flag indicating if the file state must be set to changed.
* @param userId The id of the user who has changed the resource.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void writeFile(CmsProject project, CmsFile file, boolean changed, CmsUUID userId) throws CmsException {
writeFileHeader(project, file, changed, userId);
writeFileContent(file.getFileId(), file.getContents(), project.getId(), false);
}
/**
* Writes the file content of an existing file
*
* @param fileId The ID of the file to update
* @param fileContent The new content of the file
* @param usedPool The name of the database pool to use
* @param usedStatement Specifies which tables must be used: offline, online or backup
*/
public void writeFileContent(CmsUUID fileId, byte[] fileContent, int projectId, boolean writeBackup) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
try {
if (writeBackup) {
conn = m_sqlManager.getConnectionForBackup();
stmt = m_sqlManager.getPreparedStatement(conn, "C_FILES_UPDATE_BACKUP");
}
else {
conn = m_sqlManager.getConnection(projectId);
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_FILES_UPDATE");
}
// update the file content in the FILES database.
if (fileContent.length < 2000) {
stmt.setBytes(1, fileContent);
} else {
stmt.setBinaryStream(1, new ByteArrayInputStream(fileContent), fileContent.length);
}
stmt.setString(2, fileId.toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Writes the fileheader to the Cms.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param file The new file.
* @param changed Flag indicating if the file state must be set to changed.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void writeFileHeader(CmsProject project, CmsFile file, boolean changed) throws CmsException {
writeFileHeader(project, file, changed, file.getResourceLastModifiedBy());
}
/**
* Writes the fileheader to the Cms.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param file The new file.
* @param changed Flag indicating if the file state must be set to changed.
* @param userId The id of the user who has changed the resource.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void writeFileHeader(CmsProject project, CmsFile file, boolean changed, CmsUUID userId) throws CmsException {
// this task is split into two statements because Oracle doesnt support muti-table updates
PreparedStatement stmt = null;
Connection conn = null;
//CmsUUID modifiedByUserId = userId;
long dateModified = file.isTouched() ? file.getDateLastModified() : System.currentTimeMillis();
//Savepoint savepoint = null;
try {
conn = m_sqlManager.getConnection(project);
//savepoint = conn.setSavepoint("before_update");
// update the resource
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_UPDATE_RESOURCES");
stmt.setInt(1, file.getType());
stmt.setInt(2, file.getFlags());
stmt.setInt(3, file.getLauncherType());
stmt.setString(4, file.getLauncherClassname());
stmt.setTimestamp(5, new Timestamp(dateModified));
stmt.setInt(6, file.getLength());
stmt.setString(7, file.getFileId().toString());
stmt.setString(8, file.getResourceId().toString());
stmt.executeUpdate();
m_sqlManager.closeAll(null, stmt, null);
// update the structure
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_UPDATE_STRUCTURE");
stmt.setString(1, file.getParentId().toString());
stmt.setInt(2, file.getProjectId());
stmt.setString(3, file.getResourceName());
stmt.setInt(4, 0);
int state = file.getState();
if ((state == com.opencms.core.I_CmsConstants.C_STATE_NEW) || (state == com.opencms.core.I_CmsConstants.C_STATE_CHANGED)) {
stmt.setInt(5, state);
} else {
if (changed == true) {
stmt.setInt(5, com.opencms.core.I_CmsConstants.C_STATE_CHANGED);
} else {
stmt.setInt(5, file.getState());
}
}
stmt.setString(6, file.isLockedBy().toString());
stmt.setString(7, userId.toString());
stmt.setString(8, file.getId().toString());
stmt.executeUpdate();
// stmt.setInt(1, file.getProjectId());
// int state = file.getState();
// if ((state == com.opencms.core.I_CmsConstants.C_STATE_NEW) || (state == com.opencms.core.I_CmsConstants.C_STATE_CHANGED)) {
// stmt.setInt(2, state);
// } else {
// if (changed == true) {
// stmt.setInt(2, com.opencms.core.I_CmsConstants.C_STATE_CHANGED);
// } else {
// stmt.setInt(2, file.getState());
// stmt.setString(3, file.isLockedBy().toString());
// stmt.setString(4, modifiedByUserId.toString());
// stmt.setString(5, file.getResourceName());
// stmt.setString(6, file.getId().toString());
// stmt.executeUpdate();
//m_sqlManager.commit(conn);
} catch (SQLException e) {
//m_sqlManager.rollback(conn, savepoint);
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
//m_sqlManager.releaseSavepoint(conn, savepoint);
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Writes a folder to the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param folder The folder to be written.
* @param changed Flag indicating if the file state must be set to changed.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void writeFolder(CmsProject project, CmsFolder folder, boolean changed) throws CmsException {
writeFolder(project, folder, changed, folder.getResourceLastModifiedBy());
}
/**
* Writes a folder to the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param folder The folder to be written.
* @param changed Flag indicating if the file state must be set to changed.
* @param userId The user who has changed the resource
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void writeFolder(CmsProject project, CmsFolder folder, boolean changed, CmsUUID userId) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
//CmsUUID modifiedByUserId = userId;
long dateModified = folder.isTouched() ? folder.getDateLastModified() : System.currentTimeMillis();
//Savepoint savepoint = null;
try {
conn = m_sqlManager.getConnection(project);
//savepoint = conn.setSavepoint("before_update");
// update the resource
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_UPDATE_RESOURCES");
stmt.setInt(1, folder.getType());
stmt.setInt(2, folder.getFlags());
stmt.setInt(3, folder.getLauncherType());
stmt.setString(4, folder.getLauncherClassname());
stmt.setTimestamp(5, new Timestamp(dateModified));
stmt.setInt(6, 0);
stmt.setString(7, CmsUUID.getNullUUID().toString());
stmt.setString(8, folder.getResourceId().toString());
stmt.executeUpdate();
m_sqlManager.closeAll(null, stmt, null);
// update the structure
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_UPDATE_STRUCTURE");
stmt.setString(1, folder.getParentId().toString());
stmt.setInt(2, folder.getProjectId());
stmt.setString(3, folder.getResourceName());
stmt.setInt(4, 0);
int state = folder.getState();
if ((state == com.opencms.core.I_CmsConstants.C_STATE_NEW) || (state == com.opencms.core.I_CmsConstants.C_STATE_CHANGED)) {
stmt.setInt(5, state);
} else {
if (changed == true) {
stmt.setInt(5, com.opencms.core.I_CmsConstants.C_STATE_CHANGED);
} else {
stmt.setInt(5, folder.getState());
}
}
stmt.setString(6, folder.isLockedBy().toString());
stmt.setString(7, userId.toString());
stmt.setString(8, folder.getId().toString());
stmt.executeUpdate();
// stmt.setInt(1, folder.getProjectId());
// int state = folder.getState();
// if ((state == com.opencms.core.I_CmsConstants.C_STATE_NEW) || (state == com.opencms.core.I_CmsConstants.C_STATE_CHANGED)) {
// stmt.setInt(2, state);
// } else {
// if (changed == true) {
// stmt.setInt(2, com.opencms.core.I_CmsConstants.C_STATE_CHANGED);
// } else {
// stmt.setInt(2, folder.getState());
// stmt.setString(3, folder.isLockedBy().toString());
// stmt.setString(4, modifiedByUserId.toString());
// stmt.setString(5, folder.getResourceName());
// stmt.setString(6, folder.getId().toString());
// stmt.executeUpdate();
//m_sqlManager.commit(conn);
} catch (SQLException e) {
//m_sqlManager.rollback(conn, savepoint);
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
//m_sqlManager.releaseSavepoint(conn, savepoint);
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* Writes a couple of Properties for a file or folder.
*
* @param propertyinfos A Hashtable with propertydefinition- property-pairs as strings.
* @param projectId The id of the current project.
* @param resource The CmsResource object of the resource that gets the properties.
* @param resourceType The Type of the resource.
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void writeProperties(Map propertyinfos, int projectId, CmsResource resource, int resourceType) throws CmsException {
this.writeProperties(propertyinfos, projectId, resource, resourceType, false);
}
/**
* Writes a couple of Properties for a file or folder.
*
* @param propertyinfos A Hashtable with propertydefinition- property-pairs as strings.
* @param projectId The id of the current project.
* @param resource The CmsResource object of the resource that gets the properties.
* @param resourceType The Type of the resource.
* @param addDefinition If <code>true</code> then the propertydefinition is added if it not exists
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void writeProperties(Map propertyinfos, int projectId, CmsResource resource, int resourceType, boolean addDefinition) throws CmsException {
// get all metadefs
Iterator keys = propertyinfos.keySet().iterator();
// one metainfo-name:
String key;
while (keys.hasNext()) {
key = (String) keys.next();
writeProperty(key, projectId, (String) propertyinfos.get(key), resource, resourceType, addDefinition);
}
}
/**
* Writes a property for a file or folder.
*
* @param meta The property-name of which the property has to be read.
* @param value The value for the property to be set.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
* @param addDefinition If <code>true</code> then the propertydefinition is added if it not exists
*
* @throws CmsException Throws CmsException if operation was not succesful
*/
public void writeProperty(String meta, int projectId, String value, CmsResource resource, int resourceType, boolean addDefinition) throws CmsException {
CmsPropertydefinition propdef = null;
try {
propdef = readPropertydefinition(meta, 0, resourceType);
} catch (CmsException ex) {
// do nothing
}
if (propdef == null) {
// there is no propertydefinition for with the overgiven name for the resource
// add this definition or throw an exception
if (addDefinition) {
createPropertydefinition(meta, projectId, resourceType);
} else {
throw new CmsException("[" + this.getClass().getName() + ".writeProperty/1] " + meta, CmsException.C_NOT_FOUND);
}
} else {
// write the property into the db
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(projectId);
if (readProperty(propdef.getName(), projectId, resource, resourceType) != null) {
// property exists already - use update.
// create statement
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_PROPERTIES_UPDATE");
stmt.setString(1, m_sqlManager.validateNull(value));
stmt.setString(2, resource.getId().toString());
stmt.setInt(3, propdef.getId());
stmt.executeUpdate();
} else {
// property dosen't exist - use create.
// create statement
stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_PROPERTIES_CREATE");
stmt.setInt(1, m_sqlManager.nextId(m_sqlManager.get(projectId, "C_TABLE_PROPERTIES")));
stmt.setInt(2, propdef.getId());
stmt.setString(3, resource.getId().toString());
stmt.setString(4, m_sqlManager.validateNull(value));
stmt.executeUpdate();
}
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
}
}
/**
* Updates the name of the propertydefinition for the resource type.<BR/>
*
* Only the admin can do this.
*
* @param metadef The propertydef to be written.
* @return The propertydefinition, that was written.
* @throws CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition writePropertydefinition(CmsPropertydefinition metadef) throws CmsException {
PreparedStatement stmt = null;
CmsPropertydefinition returnValue = null;
Connection conn = null;
try {
for (int i = 0; i < 3; i++) {
// write the propertydef in the offline db
if (i == 0) {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTYDEF_UPDATE");
}
// write the propertydef in the online db
else if (i == 1) {
conn = m_sqlManager.getConnection(I_CmsConstants.C_PROJECT_ONLINE_ID);
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTYDEF_UPDATE_ONLINE");
}
// write the propertydef in the backup db
else {
conn = m_sqlManager.getConnectionForBackup();
stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTYDEF_UPDATE_BACKUP");
}
stmt.setString(1, metadef.getName());
stmt.setInt(2, metadef.getId());
stmt.executeUpdate();
stmt.close();
conn.close();
}
// read the propertydefinition
returnValue = readPropertydefinition(metadef.getName(), 0, metadef.getType());
} catch (SQLException exc) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
return returnValue;
}
/**
* Writes a folder to the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param folder The folder to be written.
* @param changed Flag indicating if the file state must be set to changed.
* @param userId The user who has changed the resource
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public void writeResource(CmsProject project, CmsResource resource, byte[] filecontent, boolean isChanged, CmsUUID userId) throws CmsException {
PreparedStatement stmt = null;
Connection conn = null;
//CmsUUID modifiedByUserId = userId;
long dateModified = resource.isTouched() ? resource.getDateLastModified() : System.currentTimeMillis();
boolean isFolder = false;
//Savepoint savepoint = null;
if (resource.getType() == I_CmsConstants.C_TYPE_FOLDER) {
isFolder = true;
}
if (filecontent == null) {
filecontent = new byte[0];
}
if (project.getId() == I_CmsConstants.C_PROJECT_ONLINE_ID) {
userId = resource.getResourceLastModifiedBy();
}
try {
conn = m_sqlManager.getConnection(project);
//savepoint = conn.setSavepoint("before_update");
// update the resource
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_UPDATE_RESOURCES");
stmt.setInt(1, resource.getType());
stmt.setInt(2, resource.getFlags());
stmt.setInt(3, resource.getLauncherType());
stmt.setString(4, resource.getLauncherClassname());
stmt.setTimestamp(5, new Timestamp(dateModified));
stmt.setInt(6, filecontent.length);
stmt.setString(7, resource.getFileId().toString());
stmt.setString(8, resource.getResourceId().toString());
stmt.executeUpdate();
m_sqlManager.closeAll(null, stmt, null);
stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_UPDATE_STRUCTURE");
stmt.setString(1, resource.getParentId().toString());
stmt.setInt(2, resource.getProjectId());
stmt.setString(3, resource.getResourceName());
stmt.setInt(4, 0);
int state = resource.getState();
if ((state == I_CmsConstants.C_STATE_NEW) || (state == I_CmsConstants.C_STATE_CHANGED)) {
stmt.setInt(5, state);
} else {
if (isChanged == true) {
stmt.setInt(5, I_CmsConstants.C_STATE_CHANGED);
} else {
stmt.setInt(5, resource.getState());
}
}
stmt.setString(6, resource.isLockedBy().toString());
stmt.setString(7, userId.toString());
stmt.setString(8, resource.getId().toString());
stmt.executeUpdate();
// stmt.setInt(1, resource.getProjectId());
// int state = resource.getState();
// if ((state == I_CmsConstants.C_STATE_NEW) || (state == I_CmsConstants.C_STATE_CHANGED)) {
// stmt.setInt(2, state);
// } else {
// if (isChanged == true) {
// stmt.setInt(2, I_CmsConstants.C_STATE_CHANGED);
// } else {
// stmt.setInt(2, resource.getState());
// stmt.setString(3, resource.isLockedBy().toString());
// stmt.setString(4, modifiedByUserId.toString());
// stmt.setString(5, resource.getResourceName());
// stmt.setString(6, resource.getId().toString());
// stmt.executeUpdate();
//m_sqlManager.commit(conn);
} catch (SQLException e) {
//m_sqlManager.rollback(conn, savepoint);
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
//m_sqlManager.releaseSavepoint(conn, savepoint);
m_sqlManager.closeAll(conn, stmt, null);
}
// write the filecontent if this is a file
if (!isFolder) {
this.writeFileContent(resource.getFileId(), filecontent, project.getId(), false);
}
}
/**
* Internal helper to update an online resource with the values of the corresponding
* offline resource during publishing.
*
* @param onlineResource the resource that is updated
* @param offlineResource the resource that is read
* @throws SQLException in case of an SQL error
*/
public void updateOnlineResourceFromOfflineResource(CmsResource onlineResource, CmsResource offlineResource) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
//Savepoint savepoint = null;
try {
int resourceSize = 0;
conn = m_sqlManager.getConnection(I_CmsConstants.C_PROJECT_ONLINE_ID);
//savepoint = conn.setSavepoint("before_update");
if (offlineResource instanceof CmsFile) {
resourceSize = offlineResource.getLength();
}
// update the online res. with attribs. of the corresponding offline res.
stmt = m_sqlManager.getPreparedStatement(conn, I_CmsConstants.C_PROJECT_ONLINE_ID, "C_RESOURCES_UPDATE_RESOURCES");
stmt.setInt(1, offlineResource.getType());
stmt.setInt(2, offlineResource.getFlags());
stmt.setInt(3, offlineResource.getLauncherType());
stmt.setString(4, offlineResource.getLauncherClassname());
stmt.setTimestamp(5, new Timestamp(offlineResource.getDateLastModified()));
stmt.setInt(6, resourceSize);
stmt.setString(7, offlineResource.getFileId().toString());
stmt.setString(8, offlineResource.getResourceId().toString());
stmt.executeUpdate();
m_sqlManager.closeAll(null, stmt, null);
// update the online structure with attribs. of the corresponding offline structure
stmt = m_sqlManager.getPreparedStatement(conn, I_CmsConstants.C_PROJECT_ONLINE_ID, "C_RESOURCES_UPDATE_STRUCTURE");
stmt.setString(1, offlineResource.getParentId().toString());
stmt.setInt(2, offlineResource.getProjectId());
stmt.setString(3, offlineResource.getResourceName());
stmt.setInt(4, 0);
stmt.setInt(5, I_CmsConstants.C_STATE_UNCHANGED);
stmt.setString(6, CmsUUID.getNullUUID().toString());
stmt.setString(7, offlineResource.getResourceLastModifiedBy().toString());
stmt.setString(8, offlineResource.getId().toString());
stmt.executeUpdate();
//m_sqlManager.commit(conn);
} catch (SQLException e) {
//m_sqlManager.rollback(conn, savepoint);
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
//m_sqlManager.releaseSavepoint(conn, savepoint);
m_sqlManager.closeAll(conn, stmt, null);
}
}
/**
* @see org.opencms.db.I_CmsVfsDriver#fetchProjectsForPath(com.opencms.file.CmsProject, java.lang.String)
*/
public int[] getProjectsForPath(int projectId, String path) throws CmsException {
int[] projectID = null;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet res = null;
int rowCount = 0;
try {
conn = m_sqlManager.getConnection();
stmt = m_sqlManager.getPreparedStatement(conn, "C_SELECT_PROJECTS_FOR_PATH");
stmt.setString(1,path);
stmt.setInt(2, projectId);
res = stmt.executeQuery();
while (res.next()) {
rowCount++;
}
if (rowCount>0) {
res.beforeFirst();
projectID = new int[rowCount];
for (int i=0;res.next() && i<rowCount;i++) {
projectID[i] = res.getInt(m_sqlManager.get("C_RESOURCES_PROJECT_ID"));
}
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return projectID;
}
public List readAllFileHeaders(CmsProject currentProject) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet res = null;
CmsResource currentResource = null;
List allResources = (List) new ArrayList();
try {
conn = m_sqlManager.getConnection(currentProject);
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_RESOURCES_READ_ALL");
res = stmt.executeQuery();
while (res.next()) {
currentResource = createCmsResourceFromResultSet(res, currentProject.getId());
allResources.add(currentResource);
}
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, res);
}
return allResources;
}
/**
* @see org.opencms.db.I_CmsVfsDriver#moveResourcemoveFile(com.opencms.file.CmsUser, com.opencms.file.CmsProject, com.opencms.file.CmsResource, com.opencms.file.CmsResource)
*/
public int moveResource(CmsUser currentUser, CmsProject currentProject, CmsResource resource, CmsResource destinationFolder, String resourceName) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
long dateModified = resource.isTouched() ? resource.getDateLastModified() : System.currentTimeMillis();
int count = 0;
try {
conn = m_sqlManager.getConnection(currentProject);
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_RESOURCE_MOVE");
stmt.setString(1, destinationFolder.getId().toString());
stmt.setTimestamp(2, new Timestamp(dateModified));
stmt.setString(3, currentUser.getId().toString());
int state = resource.getState();
if ((state == I_CmsConstants.C_STATE_NEW) || (state == I_CmsConstants.C_STATE_CHANGED)) {
stmt.setInt(4, state);
} else if (state == I_CmsConstants.C_STATE_UNCHANGED) {
stmt.setInt(4, I_CmsConstants.C_STATE_CHANGED);
} else {
stmt.setInt(4, state);
}
stmt.setString(5, resourceName);
stmt.setString(6, resource.getId().toString());
count = stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
return count;
}
/**
* @see org.opencms.db.I_CmsVfsDriver#replaceResource(com.opencms.file.CmsUser, com.opencms.file.CmsProject, com.opencms.file.CmsResource, java.util.Map, byte[])
*/
public CmsResource replaceResource(CmsUser currentUser, CmsProject currentProject, CmsResource res, byte[] resContent, I_CmsResourceType newResType) throws CmsException {
Connection conn = null;
PreparedStatement stmt = null;
long dateModified = res.isTouched() ? res.getDateLastModified() : System.currentTimeMillis();
try {
// write the file content
if (resContent!=null) {
writeFileContent(res.getFileId(), resContent, currentProject.getId(), false);
}
// update the resource and structure
conn = m_sqlManager.getConnection(currentProject);
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_RESOURCE_REPLACE");
stmt.setInt(1, newResType.getResourceType());
stmt.setTimestamp(2, new Timestamp(dateModified));
stmt.setString(3, currentUser.getId().toString());
stmt.setInt(4, I_CmsConstants.C_STATE_CHANGED);
stmt.setString(5, res.getId().toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false);
} finally {
m_sqlManager.closeAll(conn, stmt, null);
}
return null;
}
}
|
package org.redkale.convert.json;
import java.nio.ByteBuffer;
import org.redkale.convert.Writer;
import org.redkale.util.*;
public class JsonWriter extends Writer {
private static final char[] CHARS_TUREVALUE = "true".toCharArray();
private static final char[] CHARS_FALSEVALUE = "false".toCharArray();
private static final int defaultSize = Integer.getInteger("convert.json.writer.buffer.defsize", 1024);
private int count;
private char[] content;
protected boolean tiny;
public static ObjectPool<JsonWriter> createPool(int max) {
return new ObjectPool<>(max, (Object... params) -> new JsonWriter(), null, (JsonWriter t) -> t.recycle());
}
public JsonWriter() {
this(defaultSize);
}
public JsonWriter(int size) {
this.content = new char[size > 128 ? size : 128];
}
@Override
public boolean tiny() {
return tiny;
}
public JsonWriter tiny(boolean tiny) {
this.tiny = tiny;
return this;
}
/**
*
*
* @param len
*
* @return
*/
private char[] expand(int len) {
int newcount = count + len;
if (newcount <= content.length) return content;
char[] newdata = new char[Math.max(content.length * 3 / 2, newcount)];
System.arraycopy(content, 0, newdata, 0, count);
this.content = newdata;
return newdata;
}
public void writeTo(final char ch) { // 0 - 127
expand(1);
content[count++] = ch;
}
public void writeTo(final char[] chs, final int start, final int len) { // 0 - 127
expand(len);
System.arraycopy(chs, start, content, count, len);
count += len;
}
/**
* <b></b> Stringnull enumdoubleBigIntegerString
*
* @param quote
* @param value nullString
*/
public void writeTo(final boolean quote, final String value) {
int len = value.length();
expand(len + (quote ? 2 : 0));
if (quote) content[count++] = '"';
value.getChars(0, len, content, count);
count += len;
if (quote) content[count++] = '"';
}
protected boolean recycle() {
this.count = 0;
if (this.content.length > defaultSize) {
this.content = new char[defaultSize];
}
return true;
}
public ByteBuffer[] toBuffers() {
return new ByteBuffer[]{ByteBuffer.wrap(Utility.encodeUTF8(content, 0, count))};
}
public byte[] toBytes() {
return Utility.encodeUTF8(content, 0, count);
}
public int count() {
return this.count;
}
@Override
public void writeString(String value) {
if (value == null) {
writeNull();
return;
}
expand(value.length() * 2 + 2);
content[count++] = '"';
for (char ch : Utility.charArray(value)) {
switch (ch) {
case '\n':
content[count++] = '\\';
content[count++] = 'n';
break;
case '\r':
content[count++] = '\\';
content[count++] = 'r';
break;
case '\t':
content[count++] = '\\';
content[count++] = 't';
break;
case '\\':
content[count++] = '\\';
content[count++] = ch;
break;
case '"':
content[count++] = '\\';
content[count++] = ch;
break;
default:
content[count++] = ch;
break;
}
}
content[count++] = '"';
}
@Override
public final void writeFieldName(Attribute attribute) {
if (this.comma) writeTo(',');
writeTo(true, attribute.field());
writeTo(':');
}
@Override
public final void writeSmallString(String value) {
writeTo(true, value);
}
@Override
public String toString() {
return new String(content, 0, count);
}
public final void writeTo(final char... chs) { // 0 - 127
writeTo(chs, 0, chs.length);
}
@Override
public final void writeBoolean(boolean value) {
writeTo(value ? CHARS_TUREVALUE : CHARS_FALSEVALUE);
}
@Override
public final void writeByte(byte value) {
writeInt(value);
}
@Override
public final void writeChar(char value) {
writeTo('\'', value, '\'');
}
@Override
public final void writeShort(short value) {
writeInt(value);
}
@Override
public void writeInt(int value) {
final char sign = value >= 0 ? 0 : '-';
if (value < 0) value = -value;
int size;
for (int i = 0;; i++) {
if (value <= sizeTable[i]) {
size = i + 1;
break;
}
}
if (sign != 0) size++;
expand(size);
int q, r;
int charPos = count + size;
// Generate two digits per iteration
while (value >= 65536) {
q = value / 100;
// really: r = i - (q * 100);
r = value - ((q << 6) + (q << 5) + (q << 2));
value = q;
content[--charPos] = DigitOnes[r];
content[--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
for (;;) {
q = (value * 52429) >>> (16 + 3);
r = value - ((q << 3) + (q << 1)); // r = i-(q*10) ...
content[--charPos] = digits[r];
value = q;
if (value == 0) break;
}
if (sign != 0) content[--charPos] = sign;
count += size;
}
@Override
public void writeLong(long value) {
final char sign = value >= 0 ? 0 : '-';
if (value < 0) value = -value;
int size = 19;
long p = 10;
for (int i = 1; i < 19; i++) {
if (value < p) {
size = i;
break;
}
p = 10 * p;
}
if (sign != 0) size++;
expand(size);
long q;
int r;
int charPos = count + size;
// Get 2 digits/iteration using longs until quotient fits into an int
while (value > Integer.MAX_VALUE) {
q = value / 100;
// really: r = i - (q * 100);
r = (int) (value - ((q << 6) + (q << 5) + (q << 2)));
value = q;
content[--charPos] = DigitOnes[r];
content[--charPos] = DigitTens[r];
}
// Get 2 digits/iteration using ints
int q2;
int i2 = (int) value;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 100);
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
content[--charPos] = DigitOnes[r];
content[--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i2 <= 65536, i2);
for (;;) {
q2 = (i2 * 52429) >>> (16 + 3);
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
content[--charPos] = digits[r];
i2 = q2;
if (i2 == 0) break;
}
if (sign != 0) content[--charPos] = sign;
count += size;
}
@Override
public final void writeFloat(float value) {
writeTo(false, String.valueOf(value));
}
@Override
public final void writeDouble(double value) {
writeTo(false, String.valueOf(value));
}
@Override
public final boolean needWriteClassName() {
return false;
}
@Override
public final void writeClassName(String clazz) {
}
@Override
public final void writeObjectB(Object obj) {
super.writeObjectB(obj);
writeTo('{');
}
@Override
public final void writeObjectE(Object obj) {
writeTo('}');
}
@Override
public final void writeNull() {
writeTo('n', 'u', 'l', 'l');
}
@Override
public final void writeArrayB(int size) {
writeTo('[');
}
@Override
public final void writeArrayMark() {
writeTo(',');
}
@Override
public final void writeArrayE() {
writeTo(']');
}
@Override
public final void writeMapB(int size) {
writeTo('{');
}
@Override
public final void writeMapMark() {
writeTo(':');
}
@Override
public final void writeMapE() {
writeTo('}');
}
final static char[] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9'
};
final static char[] DigitOnes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
final static char[] digits = {
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
};
final static int[] sizeTable = {9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE};
}
|
/**
* It contains a quick overview to the Java language.
*
* <h2>Java Keywords:</h2>
* <p>
* The following list shows the reserved words in Java. These reserved words may not be used as
* constant or variable or any other identifier names.
* </p>
* <style> table { border-collapse: collapse; width: 100%; vertical-align: middle; text-align:
* center;} table, td, th { border: 1px solid black; } </style>
* <table>
* <tbody>
* <tr>
* <td>abstract</td>
* <td>assert</td>
* <td>boolean</td>
* <td>break</td>
* </tr>
* <tr>
* <td>byte</td>
* <td>case</td>
* <td>catch</td>
* <td>char</td>
* </tr>
* <tr>
* <td>class</td>
* <td>const</td>
* <td>continue</td>
* <td>default</td>
* </tr>
* <tr>
* <td>do</td>
* <td>double</td>
* <td>else</td>
* <td>enum</td>
* </tr>
* <tr>
* <td>extends</td>
* <td>final</td>
* <td>finally</td>
* <td>float</td>
* </tr>
* <tr>
* <td>for</td>
* <td>goto</td>
* <td>if</td>
* <td>implements</td>
* </tr>
* <tr>
* <td>import</td>
* <td>instanceof</td>
* <td>int</td>
* <td>interface</td>
* </tr>
* <tr>
* <td>long</td>
* <td>native</td>
* <td>new</td>
* <td>package</td>
* </tr>
* <tr>
* <td>private</td>
* <td>protected</td>
* <td>public</td>
* <td>return</td>
* </tr>
* <tr>
* <td>short</td>
* <td>static</td>
* <td>strictfp</td>
* <td>super</td>
* </tr>
* <tr>
* <td>switch</td>
* <td>synchronized</td>
* <td>this</td>
* <td>throw</td>
* </tr>
* <tr>
* <td>throws</td>
* <td>transient</td>
* <td>try</td>
* <td>void</td>
* </tr>
* <tr>
* <td>volatile</td>
* <td>while</td>
* <td></td>
* <td></td>
* </tr>
* </tbody>
* </table>
*/
package tutorialspoint.quickguide;
|
package org.dashbuilder.dataset.client;
import org.jboss.errai.bus.client.api.messaging.Message;
/**
* <p>Default error produced by data set backend services. It encapsulates the underlying Errai technology.</p>
*
* @since 0.3.0
*/
public class DataSetClientServiceError {
private Message errorMessage;
private Throwable throwable;
public DataSetClientServiceError(Message errorMessage, Throwable throwable) {
this.errorMessage = errorMessage;
this.throwable = throwable;
}
public Object getMessage() {
return errorMessage;
}
public Throwable getThrowable() {
return throwable;
}
}
|
package org.usfirst.frc.team4468.robot;
import com.kauailabs.navx.frc.AHRS;
import drive.GearShift;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.CounterBase.EncodingType;
import gears.GearSubsystem;
import vision.visionSubsystem;
import PIDsub.*;
import climber.ClimbSubsystem;
import drive.LeftDriveTrain;
import drive.RightDriveTrain;
public class CMap {
public final static double wheelDiameter = 4;
//Need to find these values either through trial-and-error or complex math.
public final static double pulsePerRevolution = 1800; //Low Gear
public final static double lowEncoderGearRatio = 15.32;
public final static double lowGearRatio = 15.32;
public final static double highEncoderGearRatio = 4.17;
public final static double highGearRatio = 4.17;
public final static double lowDistancePerPulse = (1/pulsePerRevolution) * Math.PI * wheelDiameter;
public final static double highDistancePerPulse = Math.PI*wheelDiameter/pulsePerRevolution /
highEncoderGearRatio/highGearRatio * 1;
//Encoders
public static Encoder leftEncoder,
rightEncoder;
//Gyroscope
public static AHRS gyro;
//Motors
public static VictorSP leftTopDrive,
leftMiddleDrive,
leftBottomDrive,
rightTopDrive,
rightMiddleDrive,
rightBottomDrive,
climbMotor1,
climbMotor2;
//Joysticks
public static Joystick leftStick, rightStick, auxStick;
//Pnematics
public static DoubleSolenoid gearMechanism,
driveShift;
//Drive Train Subsystems
public static LeftDriveTrain leftDrive;
public static RightDriveTrain rightDrive;
//PID Subsystems
public static leftDrive leftPID;
public static rightDrive rightPID;
public static turnPID turnController;
//Regular Subsystems
public static visionSubsystem vision;
public static GearSubsystem gears;
public static GearShift shift;
public static ClimbSubsystem climber;
public static CameraServer server;
public static void initialize(){
//Motors
leftTopDrive = new VictorSP(0);
leftMiddleDrive = new VictorSP(1);
leftBottomDrive = new VictorSP(2);
rightTopDrive = new VictorSP(3);
rightMiddleDrive = new VictorSP(4);
rightBottomDrive = new VictorSP(5);
climbMotor1 = new VictorSP(6);
climbMotor2 = new VictorSP(7);
//Invert Left Side of Motors to Make PIDs Easier
leftTopDrive.setInverted(true);
leftMiddleDrive.setInverted(true);
leftBottomDrive.setInverted(true);
leftDrive = new LeftDriveTrain(leftTopDrive, leftMiddleDrive, leftBottomDrive);
rightDrive = new RightDriveTrain(rightTopDrive, rightMiddleDrive, rightBottomDrive);
//Encoders
leftEncoder = new Encoder(0, 1, true, EncodingType.k4X);
rightEncoder = new Encoder(2, 3, false, EncodingType.k4X);
leftEncoder.reset();
rightEncoder.reset();
leftEncoder.setReverseDirection(true);
leftEncoder.setDistancePerPulse(lowDistancePerPulse);
rightEncoder.setDistancePerPulse(lowDistancePerPulse);
//gyro = new AHRS(SerialPort.Port.kUSB1);
//gyro.reset();
//Pnumatics
gearMechanism = new DoubleSolenoid(4, 5);
driveShift = new DoubleSolenoid(6, 7);
//Joysticks
leftStick = new Joystick(0);
rightStick = new Joystick(1);
auxStick = new Joystick(2);
//PID Subsystems
leftPID = new leftDrive();
rightPID = new rightDrive();
//turnController = new turnPID();
leftPID.getPIDController().enable();
rightPID.getPIDController().enable();
leftPID.getPIDController().setOutputRange(-.6, .6);
rightPID.getPIDController().setOutputRange(-.6, .6);
//leftPID.getPIDController().setOutputRange(-.2, .2);
//turnController.getPIDController().disable();
//vision = new visionSubsystem("LINKSVision");
leftDrive = new LeftDriveTrain(leftTopDrive, leftMiddleDrive, leftBottomDrive);
rightDrive = new RightDriveTrain(rightTopDrive, rightMiddleDrive, rightBottomDrive);
shift = new GearShift(driveShift);
climber = new ClimbSubsystem(climbMotor1, climbMotor2);
gears = new GearSubsystem(gearMechanism);
server = CameraServer.getInstance();
server.startAutomaticCapture();
System.out.println("Robot is Initialized");
}
}
|
package net.echinopsii.ariane.community.core.mapping.ds.blueprintsimpl.service.tools;
import net.echinopsii.ariane.community.core.mapping.ds.MappingDSException;
import net.echinopsii.ariane.community.core.mapping.ds.blueprintsimpl.graphdb.MappingDSGraphDB;
import net.echinopsii.ariane.community.core.mapping.ds.service.tools.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import static net.echinopsii.ariane.community.core.mapping.ds.blueprintsimpl.service.tools.SessionImpl.SessionWorker.*;
public class SessionImpl implements Session {
private final static Logger log = LoggerFactory.getLogger(SessionImpl.class);
class SessionWorkerRequest {
String action;
Object instance;
Method method;
Object[] args;
LinkedBlockingQueue<SessionWorkerReply> replyQ;
public SessionWorkerRequest(String action, Object instance, Method method,
Object[] args, LinkedBlockingQueue<SessionWorkerReply> repQ) {
this.action = action;
this.instance = instance;
this.method = method;
this.args = args;
this.replyQ = repQ;
}
public String getAction() {
return action;
}
public Object getInstance() {
return instance;
}
public Method getMethod() {
return method;
}
public Object[] getArgs() {
return args;
}
public LinkedBlockingQueue<SessionWorkerReply> getReplyQ() {
return replyQ;
}
}
class SessionWorkerReply {
boolean error;
Object ret;
String error_msg;
public SessionWorkerReply(boolean error, Object ret, String error_msg) {
this.error = error;
this.ret = ret;
this.error_msg = error_msg;
}
public boolean isError() {
return error;
}
public Object getRet() {
return ret;
}
public String getError_msg() {
return error_msg;
}
}
class SessionWorker implements Runnable {
public final static String EXECUTE = "EXECUTE";
public final static String STOP = "STOP";
public final static String COMMIT = "COMMIT";
public final static String ROLLBACK = "ROLLBACK";
private LinkedBlockingQueue<SessionWorkerRequest> fifoInputQ = new LinkedBlockingQueue<>();
private boolean running = true;
private void returnToQueue(SessionWorkerRequest req, Object ret) {
if (req.getReplyQ() != null) {
try {
req.getReplyQ().put(new SessionWorkerReply(false, ret, null));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
MappingDSGraphDB.setAutocommit(false);
while (running) {
SessionWorkerRequest msg = null;
try {
msg = fifoInputQ.poll(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (msg != null) {
if (msg.getAction().equals(STOP)) running = false;
else if (msg.getAction().equals(COMMIT)) {
MappingDSGraphDB.commit();
this.returnToQueue(msg, Void.TYPE);
} else if (msg.getAction().equals(ROLLBACK)) {
MappingDSGraphDB.rollback();
this.returnToQueue(msg, Void.TYPE);
} else if (msg.getAction().equals(EXECUTE)) {
try {
Object ret = msg.getMethod().invoke(msg.getInstance(), msg.getArgs());
if (msg.getMethod().getReturnType().equals(Void.TYPE))
ret = Void.TYPE;
this.returnToQueue(msg, ret);
} catch (Exception e) {
this.returnToQueue(msg, new SessionWorkerReply(true, null, e.getMessage()));
}
}
}
}
MappingDSGraphDB.unsetAutocommit();
}
public LinkedBlockingQueue<SessionWorkerRequest> getFifoInputQ() {
return fifoInputQ;
}
public boolean isRunning() {
return running;
}
}
private String sessionId = null;
private SessionWorker sessionWorker = new SessionWorker();
private Thread sessionThread = new Thread(sessionWorker);
public SessionImpl(String clientId) {
this.sessionId = clientId + '-' + UUID.randomUUID();
this.sessionThread.setName(sessionId);
}
@Override
public String getSessionID() {
return sessionId;
}
@Override
public Session stop() {
try {
this.sessionWorker.getFifoInputQ().put(new SessionWorkerRequest(STOP, null, null, null, null));
} catch (InterruptedException e) {
e.printStackTrace();
}
while(sessionWorker.isRunning())
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
return this;
}
@Override
public Session start() {
this.sessionThread.start();
return this;
}
@Override
public boolean isRunning() {
return sessionWorker.isRunning();
}
private SessionWorkerReply getReply(LinkedBlockingQueue<SessionWorkerReply> repQ) throws MappingDSException {
SessionWorkerReply reply = null;
while (reply==null)
try {
reply = repQ.poll(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new MappingDSException(e.getMessage());
}
return reply;
}
@Override
public Object execute(Object o, String methodName, Object[] args) throws MappingDSException {
log.debug("["+ sessionId +".execute] {"+o.getClass().getName()+","+methodName+"}");
LinkedBlockingQueue<SessionWorkerReply> repQ = new LinkedBlockingQueue<>();
try {
Class[] parametersType = null;
String parameters = "";
if (args !=null) {
parametersType = new Class[args.length];
for (int i = 0; i < args.length; i++) {
parametersType[i] = args[i].getClass();
parameters += args[i].getClass().getName();
if (i < args.length-1) parameters += ", ";
}
}
Method m = null;
try {
m = o.getClass().getMethod(methodName, parametersType);
} catch (NoSuchMethodException e) {
Method[] methods = o.getClass().getMethods();
methodLoop: for (Method method : methods) {
if (!methodName.equals(method.getName())) {
continue;
}
Class<?>[] paramTypes = method.getParameterTypes();
if (args == null && paramTypes == null) {
m = method;
break;
} else if (args == null || paramTypes == null
|| paramTypes.length != args.length) {
continue;
}
for (int i = 0; i < args.length; ++i) {
if (!paramTypes[i].isAssignableFrom(args[i].getClass())) {
continue methodLoop;
}
}
m = method;
}
if (m == null) throw new MappingDSException("Method " + methodName + "(" + parameters + ")" +
"@" + o.getClass().getName() + " does not exists !");
}
this.sessionWorker.getFifoInputQ().put(new SessionWorkerRequest(EXECUTE, o, m, args, repQ));
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("["+ sessionId +".execute] wait reply ...");
SessionWorkerReply reply = getReply(repQ);
log.debug("["+ sessionId +".execute] reply error : " + reply.isError());
if (! reply.isError()) return reply.getRet();
else throw new MappingDSException(reply.getError_msg());
}
@Override
public Session commit() throws MappingDSException {
LinkedBlockingQueue<SessionWorkerReply> repQ = new LinkedBlockingQueue<>();
try {
this.sessionWorker.getFifoInputQ().put(new SessionWorkerRequest(COMMIT, null, null, null, repQ));
} catch (InterruptedException e) {
e.printStackTrace();
}
getReply(repQ);
return this;
}
@Override
public Session rollback() throws MappingDSException {
LinkedBlockingQueue<SessionWorkerReply> repQ = new LinkedBlockingQueue<>();
try {
this.sessionWorker.getFifoInputQ().put(new SessionWorkerRequest(ROLLBACK, null, null, null, repQ));
} catch (InterruptedException e) {
e.printStackTrace();
}
getReply(repQ);
return this;
}
}
|
package uk.co.uwcs.choob.modules;
import java.util.*;
import uk.co.uwcs.choob.support.*;
import uk.co.uwcs.choob.support.events.*;
import uk.co.uwcs.choob.*;
import java.net.URL;
import java.io.IOException;
import java.util.*;
import java.util.regex.*;
import org.jibble.pircbot.Colors;
// I'm going to assume that java caches regex stuff.
/**
* Module providing functionality allowing the BOT to extract information from a website.
*/
public final class ScraperModule {
private Map <java.net.URL, GetContentsCached>sites=Collections.synchronizedMap(new HashMap<URL, GetContentsCached>()); // URL -> GetContentsCached.
private final static HashMap <String, Character>EntityMap=new HashMap<String, Character>();
static {
// Paste from entitygen.sh.
EntityMap.put("nbsp", new Character((char)160));
EntityMap.put("#160", new Character((char)160));
EntityMap.put("iexcl", new Character((char)161));
EntityMap.put("#161", new Character((char)161));
EntityMap.put("cent", new Character((char)162));
EntityMap.put("#162", new Character((char)162));
EntityMap.put("pound", new Character((char)163));
EntityMap.put("#163", new Character((char)163));
EntityMap.put("curren", new Character((char)164));
EntityMap.put("#164", new Character((char)164));
EntityMap.put("yen", new Character((char)165));
EntityMap.put("#165", new Character((char)165));
EntityMap.put("brvbar", new Character((char)166));
EntityMap.put("#166", new Character((char)166));
EntityMap.put("sect", new Character((char)167));
EntityMap.put("#167", new Character((char)167));
EntityMap.put("uml", new Character((char)168));
EntityMap.put("#168", new Character((char)168));
EntityMap.put("copy", new Character((char)169));
EntityMap.put("#169", new Character((char)169));
EntityMap.put("ordf", new Character((char)170));
EntityMap.put("#170", new Character((char)170));
EntityMap.put("laquo", new Character((char)171));
EntityMap.put("#171", new Character((char)171));
EntityMap.put("not", new Character((char)172));
EntityMap.put("#172", new Character((char)172));
EntityMap.put("shy", new Character((char)173));
EntityMap.put("#173", new Character((char)173));
EntityMap.put("reg", new Character((char)174));
EntityMap.put("#174", new Character((char)174));
EntityMap.put("macr", new Character((char)175));
EntityMap.put("#175", new Character((char)175));
EntityMap.put("deg", new Character((char)176));
EntityMap.put("#176", new Character((char)176));
EntityMap.put("plusmn", new Character((char)177));
EntityMap.put("#177", new Character((char)177));
EntityMap.put("sup2", new Character((char)178));
EntityMap.put("#178", new Character((char)178));
EntityMap.put("sup3", new Character((char)179));
EntityMap.put("#179", new Character((char)179));
EntityMap.put("acute", new Character((char)180));
EntityMap.put("#180", new Character((char)180));
EntityMap.put("micro", new Character((char)181));
EntityMap.put("#181", new Character((char)181));
EntityMap.put("para", new Character((char)182));
EntityMap.put("#182", new Character((char)182));
EntityMap.put("middot", new Character((char)183));
EntityMap.put("#183", new Character((char)183));
EntityMap.put("cedil", new Character((char)184));
EntityMap.put("#184", new Character((char)184));
EntityMap.put("sup1", new Character((char)185));
EntityMap.put("#185", new Character((char)185));
EntityMap.put("ordm", new Character((char)186));
EntityMap.put("#186", new Character((char)186));
EntityMap.put("raquo", new Character((char)187));
EntityMap.put("#187", new Character((char)187));
EntityMap.put("frac14", new Character((char)188));
EntityMap.put("#188", new Character((char)188));
EntityMap.put("frac12", new Character((char)189));
EntityMap.put("#189", new Character((char)189));
EntityMap.put("frac34", new Character((char)190));
EntityMap.put("#190", new Character((char)190));
EntityMap.put("iquest", new Character((char)191));
EntityMap.put("#191", new Character((char)191));
EntityMap.put("Agrave", new Character((char)192));
EntityMap.put("#192", new Character((char)192));
EntityMap.put("Aacute", new Character((char)193));
EntityMap.put("#193", new Character((char)193));
EntityMap.put("Acirc", new Character((char)194));
EntityMap.put("#194", new Character((char)194));
EntityMap.put("Atilde", new Character((char)195));
EntityMap.put("#195", new Character((char)195));
EntityMap.put("Auml", new Character((char)196));
EntityMap.put("#196", new Character((char)196));
EntityMap.put("Aring", new Character((char)197));
EntityMap.put("#197", new Character((char)197));
EntityMap.put("AElig", new Character((char)198));
EntityMap.put("#198", new Character((char)198));
EntityMap.put("Ccedil", new Character((char)199));
EntityMap.put("#199", new Character((char)199));
EntityMap.put("Egrave", new Character((char)200));
EntityMap.put("#200", new Character((char)200));
EntityMap.put("Eacute", new Character((char)201));
EntityMap.put("#201", new Character((char)201));
EntityMap.put("Ecirc", new Character((char)202));
EntityMap.put("#202", new Character((char)202));
EntityMap.put("Euml", new Character((char)203));
EntityMap.put("#203", new Character((char)203));
EntityMap.put("Igrave", new Character((char)204));
EntityMap.put("#204", new Character((char)204));
EntityMap.put("Iacute", new Character((char)205));
EntityMap.put("#205", new Character((char)205));
EntityMap.put("Icirc", new Character((char)206));
EntityMap.put("#206", new Character((char)206));
EntityMap.put("Iuml", new Character((char)207));
EntityMap.put("#207", new Character((char)207));
EntityMap.put("ETH", new Character((char)208));
EntityMap.put("#208", new Character((char)208));
EntityMap.put("Ntilde", new Character((char)209));
EntityMap.put("#209", new Character((char)209));
EntityMap.put("Ograve", new Character((char)210));
EntityMap.put("#210", new Character((char)210));
EntityMap.put("Oacute", new Character((char)211));
EntityMap.put("#211", new Character((char)211));
EntityMap.put("Ocirc", new Character((char)212));
EntityMap.put("#212", new Character((char)212));
EntityMap.put("Otilde", new Character((char)213));
EntityMap.put("#213", new Character((char)213));
EntityMap.put("Ouml", new Character((char)214));
EntityMap.put("#214", new Character((char)214));
EntityMap.put("times", new Character((char)215));
EntityMap.put("#215", new Character((char)215));
EntityMap.put("Oslash", new Character((char)216));
EntityMap.put("#216", new Character((char)216));
EntityMap.put("Ugrave", new Character((char)217));
EntityMap.put("#217", new Character((char)217));
EntityMap.put("Uacute", new Character((char)218));
EntityMap.put("#218", new Character((char)218));
EntityMap.put("Ucirc", new Character((char)219));
EntityMap.put("#219", new Character((char)219));
EntityMap.put("Uuml", new Character((char)220));
EntityMap.put("#220", new Character((char)220));
EntityMap.put("Yacute", new Character((char)221));
EntityMap.put("#221", new Character((char)221));
EntityMap.put("THORN", new Character((char)222));
EntityMap.put("#222", new Character((char)222));
EntityMap.put("szlig", new Character((char)223));
EntityMap.put("#223", new Character((char)223));
EntityMap.put("agrave", new Character((char)224));
EntityMap.put("#224", new Character((char)224));
EntityMap.put("aacute", new Character((char)225));
EntityMap.put("#225", new Character((char)225));
EntityMap.put("acirc", new Character((char)226));
EntityMap.put("#226", new Character((char)226));
EntityMap.put("atilde", new Character((char)227));
EntityMap.put("#227", new Character((char)227));
EntityMap.put("auml", new Character((char)228));
EntityMap.put("#228", new Character((char)228));
EntityMap.put("aring", new Character((char)229));
EntityMap.put("#229", new Character((char)229));
EntityMap.put("aelig", new Character((char)230));
EntityMap.put("#230", new Character((char)230));
EntityMap.put("ccedil", new Character((char)231));
EntityMap.put("#231", new Character((char)231));
EntityMap.put("egrave", new Character((char)232));
EntityMap.put("#232", new Character((char)232));
EntityMap.put("eacute", new Character((char)233));
EntityMap.put("#233", new Character((char)233));
EntityMap.put("ecirc", new Character((char)234));
EntityMap.put("#234", new Character((char)234));
EntityMap.put("euml", new Character((char)235));
EntityMap.put("#235", new Character((char)235));
EntityMap.put("igrave", new Character((char)236));
EntityMap.put("#236", new Character((char)236));
EntityMap.put("iacute", new Character((char)237));
EntityMap.put("#237", new Character((char)237));
EntityMap.put("icirc", new Character((char)238));
EntityMap.put("#238", new Character((char)238));
EntityMap.put("iuml", new Character((char)239));
EntityMap.put("#239", new Character((char)239));
EntityMap.put("eth", new Character((char)240));
EntityMap.put("#240", new Character((char)240));
EntityMap.put("ntilde", new Character((char)241));
EntityMap.put("#241", new Character((char)241));
EntityMap.put("ograve", new Character((char)242));
EntityMap.put("#242", new Character((char)242));
EntityMap.put("oacute", new Character((char)243));
EntityMap.put("#243", new Character((char)243));
EntityMap.put("ocirc", new Character((char)244));
EntityMap.put("#244", new Character((char)244));
EntityMap.put("otilde", new Character((char)245));
EntityMap.put("#245", new Character((char)245));
EntityMap.put("ouml", new Character((char)246));
EntityMap.put("#246", new Character((char)246));
EntityMap.put("divide", new Character((char)247));
EntityMap.put("#247", new Character((char)247));
EntityMap.put("oslash", new Character((char)248));
EntityMap.put("#248", new Character((char)248));
EntityMap.put("ugrave", new Character((char)249));
EntityMap.put("#249", new Character((char)249));
EntityMap.put("uacute", new Character((char)250));
EntityMap.put("#250", new Character((char)250));
EntityMap.put("ucirc", new Character((char)251));
EntityMap.put("#251", new Character((char)251));
EntityMap.put("uuml", new Character((char)252));
EntityMap.put("#252", new Character((char)252));
EntityMap.put("yacute", new Character((char)253));
EntityMap.put("#253", new Character((char)253));
EntityMap.put("thorn", new Character((char)254));
EntityMap.put("#254", new Character((char)254));
EntityMap.put("yuml", new Character((char)255));
EntityMap.put("#255", new Character((char)255));
EntityMap.put("fnof", new Character((char)402));
EntityMap.put("#402", new Character((char)402));
EntityMap.put("Alpha", new Character((char)913));
EntityMap.put("#913", new Character((char)913));
EntityMap.put("Beta", new Character((char)914));
EntityMap.put("#914", new Character((char)914));
EntityMap.put("Gamma", new Character((char)915));
EntityMap.put("#915", new Character((char)915));
EntityMap.put("Delta", new Character((char)916));
EntityMap.put("#916", new Character((char)916));
EntityMap.put("Epsilon", new Character((char)917));
EntityMap.put("#917", new Character((char)917));
EntityMap.put("Zeta", new Character((char)918));
EntityMap.put("#918", new Character((char)918));
EntityMap.put("Eta", new Character((char)919));
EntityMap.put("#919", new Character((char)919));
EntityMap.put("Theta", new Character((char)920));
EntityMap.put("#920", new Character((char)920));
EntityMap.put("Iota", new Character((char)921));
EntityMap.put("#921", new Character((char)921));
EntityMap.put("Kappa", new Character((char)922));
EntityMap.put("#922", new Character((char)922));
EntityMap.put("Lambda", new Character((char)923));
EntityMap.put("#923", new Character((char)923));
EntityMap.put("Mu", new Character((char)924));
EntityMap.put("#924", new Character((char)924));
EntityMap.put("Nu", new Character((char)925));
EntityMap.put("#925", new Character((char)925));
EntityMap.put("Xi", new Character((char)926));
EntityMap.put("#926", new Character((char)926));
EntityMap.put("Omicron", new Character((char)927));
EntityMap.put("#927", new Character((char)927));
EntityMap.put("Pi", new Character((char)928));
EntityMap.put("#928", new Character((char)928));
EntityMap.put("Rho", new Character((char)929));
EntityMap.put("#929", new Character((char)929));
EntityMap.put("Sigma", new Character((char)931));
EntityMap.put("#931", new Character((char)931));
EntityMap.put("Tau", new Character((char)932));
EntityMap.put("#932", new Character((char)932));
EntityMap.put("Upsilon", new Character((char)933));
EntityMap.put("#933", new Character((char)933));
EntityMap.put("Phi", new Character((char)934));
EntityMap.put("#934", new Character((char)934));
EntityMap.put("Chi", new Character((char)935));
EntityMap.put("#935", new Character((char)935));
EntityMap.put("Psi", new Character((char)936));
EntityMap.put("#936", new Character((char)936));
EntityMap.put("Omega", new Character((char)937));
EntityMap.put("#937", new Character((char)937));
EntityMap.put("alpha", new Character((char)945));
EntityMap.put("#945", new Character((char)945));
EntityMap.put("beta", new Character((char)946));
EntityMap.put("#946", new Character((char)946));
EntityMap.put("gamma", new Character((char)947));
EntityMap.put("#947", new Character((char)947));
EntityMap.put("delta", new Character((char)948));
EntityMap.put("#948", new Character((char)948));
EntityMap.put("epsilon", new Character((char)949));
EntityMap.put("#949", new Character((char)949));
EntityMap.put("zeta", new Character((char)950));
EntityMap.put("#950", new Character((char)950));
EntityMap.put("eta", new Character((char)951));
EntityMap.put("#951", new Character((char)951));
EntityMap.put("theta", new Character((char)952));
EntityMap.put("#952", new Character((char)952));
EntityMap.put("iota", new Character((char)953));
EntityMap.put("#953", new Character((char)953));
EntityMap.put("kappa", new Character((char)954));
EntityMap.put("#954", new Character((char)954));
EntityMap.put("lambda", new Character((char)955));
EntityMap.put("#955", new Character((char)955));
EntityMap.put("mu", new Character((char)956));
EntityMap.put("#956", new Character((char)956));
EntityMap.put("nu", new Character((char)957));
EntityMap.put("#957", new Character((char)957));
EntityMap.put("xi", new Character((char)958));
EntityMap.put("#958", new Character((char)958));
EntityMap.put("omicron", new Character((char)959));
EntityMap.put("#959", new Character((char)959));
EntityMap.put("pi", new Character((char)960));
EntityMap.put("#960", new Character((char)960));
EntityMap.put("rho", new Character((char)961));
EntityMap.put("#961", new Character((char)961));
EntityMap.put("sigmaf", new Character((char)962));
EntityMap.put("#962", new Character((char)962));
EntityMap.put("sigma", new Character((char)963));
EntityMap.put("#963", new Character((char)963));
EntityMap.put("tau", new Character((char)964));
EntityMap.put("#964", new Character((char)964));
EntityMap.put("upsilon", new Character((char)965));
EntityMap.put("#965", new Character((char)965));
EntityMap.put("phi", new Character((char)966));
EntityMap.put("#966", new Character((char)966));
EntityMap.put("chi", new Character((char)967));
EntityMap.put("#967", new Character((char)967));
EntityMap.put("psi", new Character((char)968));
EntityMap.put("#968", new Character((char)968));
EntityMap.put("omega", new Character((char)969));
EntityMap.put("#969", new Character((char)969));
EntityMap.put("thetasym", new Character((char)977));
EntityMap.put("#977", new Character((char)977));
EntityMap.put("upsih", new Character((char)978));
EntityMap.put("#978", new Character((char)978));
EntityMap.put("piv", new Character((char)982));
EntityMap.put("#982", new Character((char)982));
EntityMap.put("bull", new Character((char)8226));
EntityMap.put("#8226", new Character((char)8226));
EntityMap.put("hellip", new Character((char)8230));
EntityMap.put("#8230", new Character((char)8230));
EntityMap.put("prime", new Character((char)8242));
EntityMap.put("#8242", new Character((char)8242));
EntityMap.put("Prime", new Character((char)8243));
EntityMap.put("#8243", new Character((char)8243));
EntityMap.put("oline", new Character((char)8254));
EntityMap.put("#8254", new Character((char)8254));
EntityMap.put("frasl", new Character((char)8260));
EntityMap.put("#8260", new Character((char)8260));
EntityMap.put("weierp", new Character((char)8472));
EntityMap.put("#8472", new Character((char)8472));
EntityMap.put("image", new Character((char)8465));
EntityMap.put("#8465", new Character((char)8465));
EntityMap.put("real", new Character((char)8476));
EntityMap.put("#8476", new Character((char)8476));
EntityMap.put("trade", new Character((char)8482));
EntityMap.put("#8482", new Character((char)8482));
EntityMap.put("alefsym", new Character((char)8501));
EntityMap.put("#8501", new Character((char)8501));
EntityMap.put("larr", new Character((char)8592));
EntityMap.put("#8592", new Character((char)8592));
EntityMap.put("uarr", new Character((char)8593));
EntityMap.put("#8593", new Character((char)8593));
EntityMap.put("rarr", new Character((char)8594));
EntityMap.put("#8594", new Character((char)8594));
EntityMap.put("darr", new Character((char)8595));
EntityMap.put("#8595", new Character((char)8595));
EntityMap.put("harr", new Character((char)8596));
EntityMap.put("#8596", new Character((char)8596));
EntityMap.put("crarr", new Character((char)8629));
EntityMap.put("#8629", new Character((char)8629));
EntityMap.put("lArr", new Character((char)8656));
EntityMap.put("#8656", new Character((char)8656));
EntityMap.put("uArr", new Character((char)8657));
EntityMap.put("#8657", new Character((char)8657));
EntityMap.put("rArr", new Character((char)8658));
EntityMap.put("#8658", new Character((char)8658));
EntityMap.put("dArr", new Character((char)8659));
EntityMap.put("#8659", new Character((char)8659));
EntityMap.put("hArr", new Character((char)8660));
EntityMap.put("#8660", new Character((char)8660));
EntityMap.put("forall", new Character((char)8704));
EntityMap.put("#8704", new Character((char)8704));
EntityMap.put("part", new Character((char)8706));
EntityMap.put("#8706", new Character((char)8706));
EntityMap.put("exist", new Character((char)8707));
EntityMap.put("#8707", new Character((char)8707));
EntityMap.put("empty", new Character((char)8709));
EntityMap.put("#8709", new Character((char)8709));
EntityMap.put("nabla", new Character((char)8711));
EntityMap.put("#8711", new Character((char)8711));
EntityMap.put("isin", new Character((char)8712));
EntityMap.put("#8712", new Character((char)8712));
EntityMap.put("notin", new Character((char)8713));
EntityMap.put("#8713", new Character((char)8713));
EntityMap.put("ni", new Character((char)8715));
EntityMap.put("#8715", new Character((char)8715));
EntityMap.put("prod", new Character((char)8719));
EntityMap.put("#8719", new Character((char)8719));
EntityMap.put("sum", new Character((char)8721));
EntityMap.put("#8721", new Character((char)8721));
EntityMap.put("minus", new Character((char)8722));
EntityMap.put("#8722", new Character((char)8722));
EntityMap.put("lowast", new Character((char)8727));
EntityMap.put("#8727", new Character((char)8727));
EntityMap.put("radic", new Character((char)8730));
EntityMap.put("#8730", new Character((char)8730));
EntityMap.put("prop", new Character((char)8733));
EntityMap.put("#8733", new Character((char)8733));
EntityMap.put("infin", new Character((char)8734));
EntityMap.put("#8734", new Character((char)8734));
EntityMap.put("ang", new Character((char)8736));
EntityMap.put("#8736", new Character((char)8736));
EntityMap.put("and", new Character((char)8743));
EntityMap.put("#8743", new Character((char)8743));
EntityMap.put("or", new Character((char)8744));
EntityMap.put("#8744", new Character((char)8744));
EntityMap.put("cap", new Character((char)8745));
EntityMap.put("#8745", new Character((char)8745));
EntityMap.put("cup", new Character((char)8746));
EntityMap.put("#8746", new Character((char)8746));
EntityMap.put("int", new Character((char)8747));
EntityMap.put("#8747", new Character((char)8747));
EntityMap.put("there4", new Character((char)8756));
EntityMap.put("#8756", new Character((char)8756));
EntityMap.put("sim", new Character((char)8764));
EntityMap.put("#8764", new Character((char)8764));
EntityMap.put("cong", new Character((char)8773));
EntityMap.put("#8773", new Character((char)8773));
EntityMap.put("asymp", new Character((char)8776));
EntityMap.put("#8776", new Character((char)8776));
EntityMap.put("ne", new Character((char)8800));
EntityMap.put("#8800", new Character((char)8800));
EntityMap.put("equiv", new Character((char)8801));
EntityMap.put("#8801", new Character((char)8801));
EntityMap.put("le", new Character((char)8804));
EntityMap.put("#8804", new Character((char)8804));
EntityMap.put("ge", new Character((char)8805));
EntityMap.put("#8805", new Character((char)8805));
EntityMap.put("sub", new Character((char)8834));
EntityMap.put("#8834", new Character((char)8834));
EntityMap.put("sup", new Character((char)8835));
EntityMap.put("#8835", new Character((char)8835));
EntityMap.put("nsub", new Character((char)8836));
EntityMap.put("#8836", new Character((char)8836));
EntityMap.put("sube", new Character((char)8838));
EntityMap.put("#8838", new Character((char)8838));
EntityMap.put("supe", new Character((char)8839));
EntityMap.put("#8839", new Character((char)8839));
EntityMap.put("oplus", new Character((char)8853));
EntityMap.put("#8853", new Character((char)8853));
EntityMap.put("otimes", new Character((char)8855));
EntityMap.put("#8855", new Character((char)8855));
EntityMap.put("perp", new Character((char)8869));
EntityMap.put("#8869", new Character((char)8869));
EntityMap.put("sdot", new Character((char)8901));
EntityMap.put("#8901", new Character((char)8901));
EntityMap.put("lceil", new Character((char)8968));
EntityMap.put("#8968", new Character((char)8968));
EntityMap.put("rceil", new Character((char)8969));
EntityMap.put("#8969", new Character((char)8969));
EntityMap.put("lfloor", new Character((char)8970));
EntityMap.put("#8970", new Character((char)8970));
EntityMap.put("rfloor", new Character((char)8971));
EntityMap.put("#8971", new Character((char)8971));
EntityMap.put("lang", new Character((char)9001));
EntityMap.put("#9001", new Character((char)9001));
EntityMap.put("rang", new Character((char)9002));
EntityMap.put("#9002", new Character((char)9002));
EntityMap.put("loz", new Character((char)9674));
EntityMap.put("#9674", new Character((char)9674));
EntityMap.put("spades", new Character((char)9824));
EntityMap.put("#9824", new Character((char)9824));
EntityMap.put("clubs", new Character((char)9827));
EntityMap.put("#9827", new Character((char)9827));
EntityMap.put("hearts", new Character((char)9829));
EntityMap.put("#9829", new Character((char)9829));
EntityMap.put("diams", new Character((char)9830));
EntityMap.put("#9830", new Character((char)9830));
EntityMap.put("quot", new Character((char)34));
EntityMap.put("#34", new Character((char)34));
EntityMap.put("amp", new Character((char)38));
EntityMap.put("#38", new Character((char)38));
EntityMap.put("lt", new Character((char)60));
EntityMap.put("#60", new Character((char)60));
EntityMap.put("gt", new Character((char)62));
EntityMap.put("#62", new Character((char)62));
EntityMap.put("OElig", new Character((char)338));
EntityMap.put("#338", new Character((char)338));
EntityMap.put("oelig", new Character((char)339));
EntityMap.put("#339", new Character((char)339));
EntityMap.put("Scaron", new Character((char)352));
EntityMap.put("#352", new Character((char)352));
EntityMap.put("scaron", new Character((char)353));
EntityMap.put("#353", new Character((char)353));
EntityMap.put("Yuml", new Character((char)376));
EntityMap.put("#376", new Character((char)376));
EntityMap.put("circ", new Character((char)710));
EntityMap.put("#710", new Character((char)710));
EntityMap.put("tilde", new Character((char)732));
EntityMap.put("#732", new Character((char)732));
EntityMap.put("ensp", new Character((char)8194));
EntityMap.put("#8194", new Character((char)8194));
EntityMap.put("emsp", new Character((char)8195));
EntityMap.put("#8195", new Character((char)8195));
EntityMap.put("thinsp", new Character((char)8201));
EntityMap.put("#8201", new Character((char)8201));
EntityMap.put("zwnj", new Character((char)8204));
EntityMap.put("#8204", new Character((char)8204));
EntityMap.put("zwj", new Character((char)8205));
EntityMap.put("#8205", new Character((char)8205));
EntityMap.put("lrm", new Character((char)8206));
EntityMap.put("#8206", new Character((char)8206));
EntityMap.put("rlm", new Character((char)8207));
EntityMap.put("#8207", new Character((char)8207));
EntityMap.put("ndash", new Character((char)8211));
EntityMap.put("#8211", new Character((char)8211));
EntityMap.put("mdash", new Character((char)8212));
EntityMap.put("#8212", new Character((char)8212));
EntityMap.put("lsquo", new Character((char)8216));
EntityMap.put("#8216", new Character((char)8216));
EntityMap.put("rsquo", new Character((char)8217));
EntityMap.put("#8217", new Character((char)8217));
EntityMap.put("sbquo", new Character((char)8218));
EntityMap.put("#8218", new Character((char)8218));
EntityMap.put("ldquo", new Character((char)8220));
EntityMap.put("#8220", new Character((char)8220));
EntityMap.put("rdquo", new Character((char)8221));
EntityMap.put("#8221", new Character((char)8221));
EntityMap.put("bdquo", new Character((char)8222));
EntityMap.put("#8222", new Character((char)8222));
EntityMap.put("dagger", new Character((char)8224));
EntityMap.put("#8224", new Character((char)8224));
EntityMap.put("Dagger", new Character((char)8225));
EntityMap.put("#8225", new Character((char)8225));
EntityMap.put("permil", new Character((char)8240));
EntityMap.put("#8240", new Character((char)8240));
EntityMap.put("lsaquo", new Character((char)8249));
EntityMap.put("#8249", new Character((char)8249));
EntityMap.put("rsaquo", new Character((char)8250));
EntityMap.put("#8250", new Character((char)8250));
EntityMap.put("euro", new Character((char)8364));
EntityMap.put("#8364", new Character((char)8364));
}
ScraperModule() {}
/**
* Get the contents, with caching, of the given URL, using the default timeout.
* @param url The URL to get the contents of.
* @throws java.io.IOException
* @return The contents of the URL provided.
*/
public String getContentsCached(URL url) throws IOException {
return getContentsCached(url, GetContentsCached.DEFAULT_TIMEOUT);
}
/**
* Get the contents, with caching, of the given URL.
* @param url The URL to get the contents of.
* @param timeout The timeout to use when performing the operation.
* @throws java.io.IOException
* @return The contents of the URL provided.
*/
public String getContentsCached(URL url, long timeout) throws IOException {
GetContentsCached gcc=sites.get(url);
if (gcc==null) {
gcc=new GetContentsCached(url, timeout);
sites.put(url, gcc);
} else {
if (gcc.getTimeout()>timeout)
gcc.setTimeout(timeout);
}
synchronized (sites) {
Iterator i=(sites.entrySet()).iterator();
while (i.hasNext()) {
if (((GetContentsCached)((Map.Entry)i.next()).getValue()).expired()) {
i.remove();
}
}
}
return gcc.getContents();
}
/**
* Get the regular expression Matcher object for a specific URL and regular expression.
* @param url The URL to perform the regular expression on.
* @param timeout The timeout to use when performing this operation.
* @param regex The regular expression to use.
* @throws java.io.IOException
* @return The Matcher object requested.
*/
public Matcher getMatcher(URL url, long timeout, String regex) throws IOException {
return getMatcher(url, timeout, Pattern.compile(regex));
}
/**
* Get the regular expression Matcher object for a specific URL and regular expression.
* @param url The URL to perform the regular expression on.
* @param regex The regular expression to use.
* @throws java.io.IOException
* @return The Matcher object requested.
*/
public Matcher getMatcher(URL url, String regex) throws IOException {
return getMatcher(url, Pattern.compile(regex));
}
/**
* Get the regular expression Matcher object for a specific URL and regular expression.
* @param url The URL to perform the regular expression on.
* @param regex The Pattern object containing the regular expression to use.
* @throws java.io.IOException
* @return The Matcher object requested.
*/
public Matcher getMatcher(URL url, Pattern regex) throws IOException {
return regex.matcher(getContentsCached(url));
}
/**
* Get the regular expression Matcher object for a specific URL and regular expression.
* @param url The URL to perform the regular expression on.
* @param timeout The timeout to use when performing this operation.
* @param regex The Pattern object containing the regular expression to use.
* @throws java.io.IOException
* @return The Matcher object requested.
*/
public Matcher getMatcher(URL url, long timeout, Pattern regex) throws IOException {
return regex.matcher(getContentsCached(url, timeout));
}
/**
* Replace HTML special character codes with the actual character.
* @param html The String to perform the replacement upon.
* @return The String after replacement has been performed.
*/
public String convertEntities(final String html) {
// Sorry, I just couldn't bring myself to do foreach (hashmap => key, val) html=html.replaceall(key, val);
StringBuilder buf = new StringBuilder();
int l=html.length();
int p=0;
int lastp=0;
while (p<l) {
p=html.indexOf("&", p);
if (p==-1) {
break;
}
int semi=html.indexOf(";",p);
if (semi==-1) {
break;
}
Character c=EntityMap.get(html.substring(p+1,semi));
if (c==null) {
buf.append(html.substring(lastp, semi+1));
} else {
buf.append(html.substring(lastp,p)).append(c);
}
p=semi+1;
lastp=p;
}
buf.append(html.substring(lastp));
return buf.toString();
}
/**
* Replace bold HTML tags with the IRC equivalent.
* @param html The HTML String to perform the replacement on.
* @return The String suitably formatted to perform bold on IRC.
*/
public String boldTags(String html) {
return html.replaceAll("(?i)<b>", Colors.BOLD).replaceAll("(?i)</b>", Colors.NORMAL);
}
public String quoteURLs(String html) {
//return html.replaceAll("<a +?href *= *\"(.*?)\" *?>","[$1] ").replaceAll("</a>","");
return html;
//This is going to require more than: return html.replaceAll("<a +?href *= *\"(.*?)\" *?>",Colors.REVERSE + "<$1> " + Colors.NORMAL).replaceAll("</a>","");
}
/**
* Remove all tags from a String of HTML.
* @param html The String to filter.
* @return The String, minus any HTML tags.
*/
public String stripTags(String html) {
return html.replaceAll("<.*?>","");
}
/**
* Tidy up a string of HTML, removing newlines and HTML special characters.
* @param html The HTML to tidy.
* @return The tidy HTML.
*/
public String cleanup(String html) {
return convertEntities(html.trim().replaceAll("\n",""));
}
/**
* Cleans a Sting of HTML of all tags in order to make it suitable for output in IRC.
* @param html The String containing HTML tags that is to be prepared for IRC output.
* @return A string ready for output into IRC.
*/
public String readyForIrc(String html) {
return stripTags(quoteURLs(boldTags(cleanup(html))));
}
}
|
package io.quarkus.smallrye.openapi.deployment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.openapi.OASConfig;
import org.eclipse.microprofile.openapi.OASFilter;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.CompositeIndex;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.BeanArchiveIndexBuildItem;
import io.quarkus.arc.deployment.SyntheticBeanBuildItem;
import io.quarkus.deployment.Capabilities;
import io.quarkus.deployment.Capability;
import io.quarkus.deployment.Feature;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.AdditionalIndexedClassesBuildItem;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.GeneratedResourceBuildItem;
import io.quarkus.deployment.builditem.HotDeploymentWatchedFileBuildItem;
import io.quarkus.deployment.builditem.LaunchModeBuildItem;
import io.quarkus.deployment.builditem.ShutdownContextBuildItem;
import io.quarkus.deployment.builditem.nativeimage.NativeImageResourceBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveHierarchyBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ServiceProviderBuildItem;
import io.quarkus.deployment.logging.LogCleanupFilterBuildItem;
import io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem;
import io.quarkus.resteasy.common.spi.ResteasyDotNames;
import io.quarkus.resteasy.server.common.spi.AllowedJaxRsAnnotationPrefixBuildItem;
import io.quarkus.resteasy.server.common.spi.ResteasyJaxrsConfigBuildItem;
import io.quarkus.runtime.LaunchMode;
import io.quarkus.smallrye.openapi.common.deployment.SmallRyeOpenApiConfig;
import io.quarkus.smallrye.openapi.deployment.filter.AutoRolesAllowedFilter;
import io.quarkus.smallrye.openapi.deployment.filter.AutoTagFilter;
import io.quarkus.smallrye.openapi.deployment.filter.SecurityConfigFilter;
import io.quarkus.smallrye.openapi.deployment.spi.AddToOpenAPIDefinitionBuildItem;
import io.quarkus.smallrye.openapi.runtime.OpenApiConstants;
import io.quarkus.smallrye.openapi.runtime.OpenApiDocumentService;
import io.quarkus.smallrye.openapi.runtime.OpenApiRecorder;
import io.quarkus.smallrye.openapi.runtime.OpenApiRuntimeConfig;
import io.quarkus.smallrye.openapi.runtime.filter.AutoBasicSecurityFilter;
import io.quarkus.smallrye.openapi.runtime.filter.AutoJWTSecurityFilter;
import io.quarkus.smallrye.openapi.runtime.filter.AutoUrl;
import io.quarkus.smallrye.openapi.runtime.filter.OpenIDConnectSecurityFilter;
import io.quarkus.vertx.http.deployment.HttpRootPathBuildItem;
import io.quarkus.vertx.http.deployment.NonApplicationRootPathBuildItem;
import io.quarkus.vertx.http.deployment.RouteBuildItem;
import io.quarkus.vertx.http.deployment.SecurityInformationBuildItem;
import io.quarkus.vertx.http.deployment.devmode.NotFoundPageDisplayableEndpointBuildItem;
import io.smallrye.openapi.api.OpenApiConfig;
import io.smallrye.openapi.api.OpenApiConfigImpl;
import io.smallrye.openapi.api.OpenApiDocument;
import io.smallrye.openapi.api.constants.SecurityConstants;
import io.smallrye.openapi.api.models.OpenAPIImpl;
import io.smallrye.openapi.api.util.MergeUtil;
import io.smallrye.openapi.jaxrs.JaxRsConstants;
import io.smallrye.openapi.runtime.OpenApiProcessor;
import io.smallrye.openapi.runtime.OpenApiStaticFile;
import io.smallrye.openapi.runtime.io.Format;
import io.smallrye.openapi.runtime.io.OpenApiSerializer;
import io.smallrye.openapi.runtime.scanner.AnnotationScannerExtension;
import io.smallrye.openapi.runtime.scanner.FilteredIndexView;
import io.smallrye.openapi.runtime.scanner.OpenApiAnnotationScanner;
import io.smallrye.openapi.runtime.util.JandexUtil;
import io.smallrye.openapi.spring.SpringConstants;
import io.smallrye.openapi.vertx.VertxConstants;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
/**
* The main OpenAPI Processor. This will scan for JAX-RS, Spring and Vert.x Annotations, and, if any, add supplied schemas.
* The result is added to the deployable unit to be loaded at runtime.
*/
public class SmallRyeOpenApiProcessor {
private static final Logger log = Logger.getLogger("io.quarkus.smallrye.openapi");
private static final String META_INF_OPENAPI_YAML = "META-INF/openapi.yaml";
private static final String WEB_INF_CLASSES_META_INF_OPENAPI_YAML = "WEB-INF/classes/META-INF/openapi.yaml";
private static final String META_INF_OPENAPI_YML = "META-INF/openapi.yml";
private static final String WEB_INF_CLASSES_META_INF_OPENAPI_YML = "WEB-INF/classes/META-INF/openapi.yml";
private static final String META_INF_OPENAPI_JSON = "META-INF/openapi.json";
private static final String WEB_INF_CLASSES_META_INF_OPENAPI_JSON = "WEB-INF/classes/META-INF/openapi.json";
private static final DotName OPENAPI_SCHEMA = DotName.createSimple(Schema.class.getName());
private static final DotName OPENAPI_RESPONSE = DotName.createSimple(APIResponse.class.getName());
private static final DotName OPENAPI_RESPONSES = DotName.createSimple(APIResponses.class.getName());
private static final String OPENAPI_RESPONSE_CONTENT = "content";
private static final String OPENAPI_RESPONSE_SCHEMA = "schema";
private static final String OPENAPI_SCHEMA_NOT = "not";
private static final String OPENAPI_SCHEMA_ONE_OF = "oneOf";
private static final String OPENAPI_SCHEMA_ANY_OF = "anyOf";
private static final String OPENAPI_SCHEMA_ALL_OF = "allOf";
private static final String OPENAPI_SCHEMA_IMPLEMENTATION = "implementation";
private static final String JAX_RS = "JAX-RS";
private static final String SPRING = "Spring";
private static final String VERT_X = "Vert.x";
static {
System.setProperty(io.smallrye.openapi.api.constants.OpenApiConstants.DEFAULT_PRODUCES, "application/json");
System.setProperty(io.smallrye.openapi.api.constants.OpenApiConstants.DEFAULT_CONSUMES, "application/json");
}
@BuildStep
void contributeClassesToIndex(BuildProducer<AdditionalIndexedClassesBuildItem> additionalIndexedClasses) {
// contribute additional JDK classes to the index, because SmallRye OpenAPI will check if some
// app types implement Map and Collection and will go through super classes until Object is reached,
// and yes, it even checks Object
additionalIndexedClasses.produce(new AdditionalIndexedClassesBuildItem(
Collection.class.getName(),
Map.class.getName(),
Object.class.getName()));
}
@BuildStep
void registerNativeImageResources(BuildProducer<ServiceProviderBuildItem> serviceProvider) throws IOException {
// To map from smallrye and mp config to quarkus
serviceProvider.produce(ServiceProviderBuildItem.allProvidersFromClassPath(OpenApiConfigMapping.class.getName()));
}
@BuildStep
void configFiles(BuildProducer<HotDeploymentWatchedFileBuildItem> watchedFiles,
SmallRyeOpenApiConfig openApiConfig,
LaunchModeBuildItem launchMode,
OutputTargetBuildItem outputTargetBuildItem) throws IOException {
// Add any aditional directories if configured
if (launchMode.getLaunchMode().isDevOrTest() && openApiConfig.additionalDocsDirectory.isPresent()) {
List<Path> additionalStaticDocuments = openApiConfig.additionalDocsDirectory.get();
for (Path path : additionalStaticDocuments) {
// Scan all yaml and json files
List<String> filesInDir = getResourceFiles(path.toString(), outputTargetBuildItem.getOutputDirectory());
for (String possibleFile : filesInDir) {
watchedFiles.produce(new HotDeploymentWatchedFileBuildItem(possibleFile));
}
}
}
watchedFiles.produce(new HotDeploymentWatchedFileBuildItem(META_INF_OPENAPI_YAML));
watchedFiles.produce(new HotDeploymentWatchedFileBuildItem(WEB_INF_CLASSES_META_INF_OPENAPI_YAML));
watchedFiles.produce(new HotDeploymentWatchedFileBuildItem(META_INF_OPENAPI_YML));
watchedFiles.produce(new HotDeploymentWatchedFileBuildItem(WEB_INF_CLASSES_META_INF_OPENAPI_YML));
watchedFiles.produce(new HotDeploymentWatchedFileBuildItem(META_INF_OPENAPI_JSON));
watchedFiles.produce(new HotDeploymentWatchedFileBuildItem(WEB_INF_CLASSES_META_INF_OPENAPI_JSON));
}
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
void handler(LaunchModeBuildItem launch,
BuildProducer<NotFoundPageDisplayableEndpointBuildItem> displayableEndpoints,
BuildProducer<SyntheticBeanBuildItem> syntheticBeans,
BuildProducer<RouteBuildItem> routes,
OpenApiRecorder recorder,
NonApplicationRootPathBuildItem nonApplicationRootPathBuildItem,
List<SecurityInformationBuildItem> securityInformationBuildItems,
OpenApiRuntimeConfig openApiRuntimeConfig,
ShutdownContextBuildItem shutdownContext,
SmallRyeOpenApiConfig openApiConfig,
OpenApiFilteredIndexViewBuildItem apiFilteredIndexViewBuildItem) {
/*
* <em>Ugly Hack</em>
* In dev mode, we pass a classloader to load the up to date OpenAPI document.
* This hack is required because using the TCCL would get an outdated version - the initial one.
* This is because the worker thread on which the handler is called captures the TCCL at creation time
* and does not allow updating it.
*
* This classloader must ONLY be used to load the OpenAPI document.
*
* In non dev mode, the TCCL is used.
*/
if (launch.getLaunchMode() == LaunchMode.DEVELOPMENT) {
recorder.setupClDevMode(shutdownContext);
}
OASFilter autoSecurityFilter = null;
if (openApiConfig.autoAddSecurity) {
// Only add the security if there are secured endpoints
OASFilter autoRolesAllowedFilter = getAutoRolesAllowedFilter(openApiConfig.securitySchemeName,
apiFilteredIndexViewBuildItem, openApiConfig);
if (autoRolesAllowedFilter != null) {
autoSecurityFilter = getAutoSecurityFilter(securityInformationBuildItems, openApiConfig);
}
}
syntheticBeans.produce(SyntheticBeanBuildItem.configure(OASFilter.class).setRuntimeInit()
.supplier(recorder.autoSecurityFilterSupplier(autoSecurityFilter)).done());
Handler<RoutingContext> handler = recorder.handler(openApiRuntimeConfig);
routes.produce(nonApplicationRootPathBuildItem.routeBuilder()
.route(openApiConfig.path)
.routeConfigKey("quarkus.smallrye-openapi.path")
.handler(handler)
.displayOnNotFoundPage("Open API Schema document")
.blockingRoute()
.build());
routes.produce(nonApplicationRootPathBuildItem.routeBuilder()
.route(openApiConfig.path + ".json")
.handler(handler)
.build());
routes.produce(nonApplicationRootPathBuildItem.routeBuilder()
.route(openApiConfig.path + ".yaml")
.handler(handler)
.build());
routes.produce(nonApplicationRootPathBuildItem.routeBuilder()
.route(openApiConfig.path + ".yml")
.handler(handler)
.build());
}
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void classLoaderHack(OpenApiRecorder recorder) {
recorder.classLoaderHack();
}
@BuildStep
void additionalBean(BuildProducer<AdditionalBeanBuildItem> additionalBeanProducer) {
additionalBeanProducer.produce(AdditionalBeanBuildItem.builder()
.addBeanClass(OpenApiDocumentService.class)
.setUnremovable().build());
}
@BuildStep
OpenApiFilteredIndexViewBuildItem smallryeOpenApiIndex(CombinedIndexBuildItem combinedIndexBuildItem,
BeanArchiveIndexBuildItem beanArchiveIndexBuildItem) {
CompositeIndex compositeIndex = CompositeIndex.create(combinedIndexBuildItem.getIndex(),
beanArchiveIndexBuildItem.getIndex());
return new OpenApiFilteredIndexViewBuildItem(
new FilteredIndexView(
compositeIndex,
new OpenApiConfigImpl(ConfigProvider.getConfig())));
}
@BuildStep
void addSecurityFilter(BuildProducer<AddToOpenAPIDefinitionBuildItem> addToOpenAPIDefinitionProducer,
OpenApiFilteredIndexViewBuildItem apiFilteredIndexViewBuildItem,
SmallRyeOpenApiConfig config) {
List<AnnotationInstance> rolesAllowedAnnotations = new ArrayList<>();
for (DotName rolesAllowed : SecurityConstants.ROLES_ALLOWED) {
rolesAllowedAnnotations.addAll(apiFilteredIndexViewBuildItem.getIndex().getAnnotations(rolesAllowed));
}
Map<String, List<String>> methodReferences = new HashMap<>();
DotName securityRequirement = DotName.createSimple(SecurityRequirement.class.getName());
for (AnnotationInstance ai : rolesAllowedAnnotations) {
if (ai.target().kind().equals(AnnotationTarget.Kind.METHOD)) {
MethodInfo method = ai.target().asMethod();
if (isValidOpenAPIMethodForAutoAdd(method, securityRequirement)) {
String ref = JandexUtil.createUniqueMethodReference(method.declaringClass(), method);
methodReferences.put(ref, List.of(ai.value().asStringArray()));
}
}
if (ai.target().kind().equals(AnnotationTarget.Kind.CLASS)) {
ClassInfo classInfo = ai.target().asClass();
List<MethodInfo> methods = classInfo.methods();
for (MethodInfo method : methods) {
if (isValidOpenAPIMethodForAutoAdd(method, securityRequirement)) {
String ref = JandexUtil.createUniqueMethodReference(classInfo, method);
methodReferences.put(ref, List.of(ai.value().asStringArray()));
}
}
}
}
// Add a security scheme from config
if (config.securityScheme.isPresent()) {
addToOpenAPIDefinitionProducer
.produce(new AddToOpenAPIDefinitionBuildItem(
new SecurityConfigFilter(config)));
}
// Add Auto roles allowed
OASFilter autoRolesAllowedFilter = getAutoRolesAllowedFilter(config.securitySchemeName, apiFilteredIndexViewBuildItem,
config);
if (autoRolesAllowedFilter != null) {
addToOpenAPIDefinitionProducer.produce(new AddToOpenAPIDefinitionBuildItem(autoRolesAllowedFilter));
}
// Add Auto Tag based on the class name
OASFilter autoTagFilter = getAutoTagFilter(apiFilteredIndexViewBuildItem,
config);
if (autoTagFilter != null) {
addToOpenAPIDefinitionProducer.produce(new AddToOpenAPIDefinitionBuildItem(autoTagFilter));
}
}
private OASFilter getAutoSecurityFilter(List<SecurityInformationBuildItem> securityInformationBuildItems,
SmallRyeOpenApiConfig config) {
// Auto add a security from security extension(s)
if (!config.securityScheme.isPresent() && securityInformationBuildItems != null
&& !securityInformationBuildItems.isEmpty()) {
// This needs to be a filter in runtime as the config we use to auto configure is in runtime
for (SecurityInformationBuildItem securityInformationBuildItem : securityInformationBuildItems) {
SecurityInformationBuildItem.SecurityModel securityModel = securityInformationBuildItem.getSecurityModel();
switch (securityModel) {
case jwt:
return new AutoJWTSecurityFilter(
config.securitySchemeName,
config.securitySchemeDescription,
config.jwtSecuritySchemeValue,
config.jwtBearerFormat);
case basic:
return new AutoBasicSecurityFilter(
config.securitySchemeName,
config.securitySchemeDescription,
config.basicSecuritySchemeValue);
case oidc:
Optional<SecurityInformationBuildItem.OpenIDConnectInformation> maybeInfo = securityInformationBuildItem
.getOpenIDConnectInformation();
if (maybeInfo.isPresent()) {
SecurityInformationBuildItem.OpenIDConnectInformation info = maybeInfo.get();
AutoUrl authorizationUrl = new AutoUrl(
config.oidcOpenIdConnectUrl.orElse(null),
info.getUrlConfigKey(),
"/protocol/openid-connect/auth");
AutoUrl refreshUrl = new AutoUrl(
config.oidcOpenIdConnectUrl.orElse(null),
info.getUrlConfigKey(),
"/protocol/openid-connect/token");
AutoUrl tokenUrl = new AutoUrl(
config.oidcOpenIdConnectUrl.orElse(null),
info.getUrlConfigKey(),
"/protocol/openid-connect/token/introspect");
return new OpenIDConnectSecurityFilter(
config.securitySchemeName,
config.securitySchemeDescription,
authorizationUrl, refreshUrl, tokenUrl);
}
break;
default:
break;
}
}
}
return null;
}
private OASFilter getAutoRolesAllowedFilter(String securitySchemeName,
OpenApiFilteredIndexViewBuildItem apiFilteredIndexViewBuildItem,
SmallRyeOpenApiConfig config) {
if (config.autoAddSecurityRequirement) {
Map<String, List<String>> rolesAllowedMethodReferences = getRolesAllowedMethodReferences(
apiFilteredIndexViewBuildItem);
if (rolesAllowedMethodReferences != null && !rolesAllowedMethodReferences.isEmpty()) {
if (securitySchemeName == null) {
securitySchemeName = config.securitySchemeName;
}
return new AutoRolesAllowedFilter(securitySchemeName, rolesAllowedMethodReferences);
}
}
return null;
}
private OASFilter getAutoTagFilter(OpenApiFilteredIndexViewBuildItem apiFilteredIndexViewBuildItem,
SmallRyeOpenApiConfig config) {
if (config.autoAddTags) {
Map<String, String> classNamesMethodReferences = getClassNamesMethodReferences(apiFilteredIndexViewBuildItem);
if (classNamesMethodReferences != null && !classNamesMethodReferences.isEmpty()) {
return new AutoTagFilter(classNamesMethodReferences);
}
}
return null;
}
private Map<String, List<String>> getRolesAllowedMethodReferences(
OpenApiFilteredIndexViewBuildItem apiFilteredIndexViewBuildItem) {
List<AnnotationInstance> rolesAllowedAnnotations = new ArrayList<>();
for (DotName rolesAllowed : SecurityConstants.ROLES_ALLOWED) {
rolesAllowedAnnotations.addAll(apiFilteredIndexViewBuildItem.getIndex().getAnnotations(rolesAllowed));
}
Map<String, List<String>> methodReferences = new HashMap<>();
DotName securityRequirement = DotName.createSimple(SecurityRequirement.class.getName());
for (AnnotationInstance ai : rolesAllowedAnnotations) {
if (ai.target().kind().equals(AnnotationTarget.Kind.METHOD)) {
MethodInfo method = ai.target().asMethod();
if (isValidOpenAPIMethodForAutoAdd(method, securityRequirement)) {
String ref = JandexUtil.createUniqueMethodReference(method.declaringClass(), method);
methodReferences.put(ref, List.of(ai.value().asStringArray()));
}
}
if (ai.target().kind().equals(AnnotationTarget.Kind.CLASS)) {
ClassInfo classInfo = ai.target().asClass();
List<MethodInfo> methods = classInfo.methods();
for (MethodInfo method : methods) {
if (isValidOpenAPIMethodForAutoAdd(method, securityRequirement)) {
String ref = JandexUtil.createUniqueMethodReference(classInfo, method);
methodReferences.put(ref, List.of(ai.value().asStringArray()));
}
}
}
}
return methodReferences;
}
private Map<String, String> getClassNamesMethodReferences(OpenApiFilteredIndexViewBuildItem apiFilteredIndexViewBuildItem) {
List<AnnotationInstance> openapiAnnotations = new ArrayList<>();
Set<DotName> allOpenAPIEndpoints = getAllOpenAPIEndpoints();
for (DotName dotName : allOpenAPIEndpoints) {
openapiAnnotations.addAll(apiFilteredIndexViewBuildItem.getIndex().getAnnotations(dotName));
}
Map<String, String> classNames = new HashMap<>();
for (AnnotationInstance ai : openapiAnnotations) {
if (ai.target().kind().equals(AnnotationTarget.Kind.METHOD)) {
MethodInfo method = ai.target().asMethod();
if (Modifier.isInterface(method.declaringClass().flags())) {
Collection<ClassInfo> allKnownImplementors = apiFilteredIndexViewBuildItem.getIndex()
.getAllKnownImplementors(method.declaringClass().name());
for (ClassInfo impl : allKnownImplementors) {
MethodInfo implMethod = impl.method(method.name(), method.parameters().toArray(new Type[] {}));
if (implMethod != null) {
String implRef = JandexUtil.createUniqueMethodReference(impl, method);
classNames.put(implRef, impl.simpleName());
}
}
} else if (Modifier.isAbstract(method.declaringClass().flags())) {
Collection<ClassInfo> allKnownSubclasses = apiFilteredIndexViewBuildItem.getIndex()
.getAllKnownSubclasses(method.declaringClass().name());
for (ClassInfo impl : allKnownSubclasses) {
MethodInfo implMethod = impl.method(method.name(), method.parameters().toArray(new Type[] {}));
if (implMethod != null) {
String implRef = JandexUtil.createUniqueMethodReference(impl, method);
classNames.put(implRef, impl.simpleName());
}
}
} else {
String ref = JandexUtil.createUniqueMethodReference(method.declaringClass(), method);
classNames.put(ref, method.declaringClass().simpleName());
}
}
}
return classNames;
}
private boolean isValidOpenAPIMethodForAutoAdd(MethodInfo method, DotName securityRequirement) {
return isOpenAPIEndpoint(method) && !method.hasAnnotation(securityRequirement)
&& method.declaringClass().classAnnotation(securityRequirement) == null;
}
@BuildStep
public List<AllowedJaxRsAnnotationPrefixBuildItem> registerJaxRsSupportedAnnotation() {
List<AllowedJaxRsAnnotationPrefixBuildItem> prefixes = new ArrayList<>();
prefixes.add(new AllowedJaxRsAnnotationPrefixBuildItem("org.eclipse.microprofile.openapi.annotations"));
return prefixes;
}
@BuildStep
public void registerOpenApiSchemaClassesForReflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy,
OpenApiFilteredIndexViewBuildItem openApiFilteredIndexViewBuildItem,
Capabilities capabilities) {
FilteredIndexView index = openApiFilteredIndexViewBuildItem.getIndex();
if (shouldScanAnnotations(capabilities, index)) {
// Generate reflection declaration from MP OpenAPI Schema definition
// They are needed for serialization.
Collection<AnnotationInstance> schemaAnnotationInstances = index.getAnnotations(OPENAPI_SCHEMA);
for (AnnotationInstance schemaAnnotationInstance : schemaAnnotationInstances) {
AnnotationTarget typeTarget = schemaAnnotationInstance.target();
if (typeTarget.kind() != AnnotationTarget.Kind.CLASS) {
continue;
}
produceReflectiveHierarchy(reflectiveHierarchy, Type.create(typeTarget.asClass().name(), Type.Kind.CLASS),
getClass().getSimpleName() + " > " + typeTarget.asClass().name());
}
// Generate reflection declaration from MP OpenAPI APIResponse schema definition
// They are needed for serialization
Collection<AnnotationInstance> apiResponseAnnotationInstances = index.getAnnotations(OPENAPI_RESPONSE);
registerReflectionForApiResponseSchemaSerialization(reflectiveClass, reflectiveHierarchy,
apiResponseAnnotationInstances);
// Generate reflection declaration from MP OpenAPI APIResponses schema definition
// They are needed for serialization
Collection<AnnotationInstance> apiResponsesAnnotationInstances = index.getAnnotations(OPENAPI_RESPONSES);
for (AnnotationInstance apiResponsesAnnotationInstance : apiResponsesAnnotationInstances) {
AnnotationValue apiResponsesAnnotationValue = apiResponsesAnnotationInstance.value();
if (apiResponsesAnnotationValue == null) {
continue;
}
registerReflectionForApiResponseSchemaSerialization(reflectiveClass, reflectiveHierarchy,
Arrays.asList(apiResponsesAnnotationValue.asNestedArray()));
}
}
}
private boolean isOpenAPIEndpoint(MethodInfo method) {
Set<DotName> httpAnnotations = getAllOpenAPIEndpoints();
for (DotName httpAnnotation : httpAnnotations) {
if (method.hasAnnotation(httpAnnotation)) {
return true;
}
}
return false;
}
private Set<DotName> getAllOpenAPIEndpoints() {
Set<DotName> httpAnnotations = new HashSet<>();
httpAnnotations.addAll(JaxRsConstants.HTTP_METHODS);
httpAnnotations.addAll(SpringConstants.HTTP_METHODS);
return httpAnnotations;
}
private void registerReflectionForApiResponseSchemaSerialization(BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy,
Collection<AnnotationInstance> apiResponseAnnotationInstances) {
for (AnnotationInstance apiResponseAnnotationInstance : apiResponseAnnotationInstances) {
AnnotationValue contentAnnotationValue = apiResponseAnnotationInstance.value(OPENAPI_RESPONSE_CONTENT);
if (contentAnnotationValue == null) {
continue;
}
AnnotationInstance[] contents = contentAnnotationValue.asNestedArray();
for (AnnotationInstance content : contents) {
AnnotationValue annotationValue = content.value(OPENAPI_RESPONSE_SCHEMA);
if (annotationValue == null) {
continue;
}
AnnotationInstance schema = annotationValue.asNested();
String source = getClass().getSimpleName() + " > " + schema.target();
AnnotationValue schemaImplementationClass = schema.value(OPENAPI_SCHEMA_IMPLEMENTATION);
if (schemaImplementationClass != null) {
produceReflectiveHierarchy(reflectiveHierarchy, schemaImplementationClass.asClass(), source);
}
AnnotationValue schemaNotClass = schema.value(OPENAPI_SCHEMA_NOT);
if (schemaNotClass != null) {
reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, schemaNotClass.asString()));
}
produceReflectiveHierarchy(reflectiveHierarchy, schema.value(OPENAPI_SCHEMA_ONE_OF), source);
produceReflectiveHierarchy(reflectiveHierarchy, schema.value(OPENAPI_SCHEMA_ANY_OF), source);
produceReflectiveHierarchy(reflectiveHierarchy, schema.value(OPENAPI_SCHEMA_ALL_OF), source);
}
}
}
@BuildStep
public void build(BuildProducer<FeatureBuildItem> feature,
BuildProducer<GeneratedResourceBuildItem> resourceBuildItemBuildProducer,
BuildProducer<NativeImageResourceBuildItem> nativeImageResources,
OpenApiFilteredIndexViewBuildItem openApiFilteredIndexViewBuildItem,
Capabilities capabilities,
List<AddToOpenAPIDefinitionBuildItem> openAPIBuildItems,
HttpRootPathBuildItem httpRootPathBuildItem,
OutputTargetBuildItem out,
SmallRyeOpenApiConfig openApiConfig,
Optional<ResteasyJaxrsConfigBuildItem> resteasyJaxrsConfig,
OutputTargetBuildItem outputTargetBuildItem) throws Exception {
FilteredIndexView index = openApiFilteredIndexViewBuildItem.getIndex();
feature.produce(new FeatureBuildItem(Feature.SMALLRYE_OPENAPI));
OpenAPI staticModel = generateStaticModel(openApiConfig, outputTargetBuildItem.getOutputDirectory());
OpenAPI annotationModel;
if (shouldScanAnnotations(capabilities, index)) {
annotationModel = generateAnnotationModel(index, capabilities, httpRootPathBuildItem, resteasyJaxrsConfig);
} else {
annotationModel = new OpenAPIImpl();
}
OpenApiDocument finalDocument = loadDocument(staticModel, annotationModel, openAPIBuildItems);
for (Format format : Format.values()) {
String name = OpenApiConstants.BASE_NAME + format;
byte[] schemaDocument = OpenApiSerializer.serialize(finalDocument.get(), format).getBytes(StandardCharsets.UTF_8);
resourceBuildItemBuildProducer.produce(new GeneratedResourceBuildItem(name, schemaDocument));
nativeImageResources.produce(new NativeImageResourceBuildItem(name));
}
// Store the document if needed
boolean shouldStore = openApiConfig.storeSchemaDirectory.isPresent();
if (shouldStore) {
storeDocument(out, openApiConfig, staticModel, annotationModel, openAPIBuildItems);
}
}
@BuildStep
LogCleanupFilterBuildItem logCleanup() {
return new LogCleanupFilterBuildItem("io.smallrye.openapi.api.OpenApiDocument",
"OpenAPI document initialized:");
}
private void produceReflectiveHierarchy(BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy,
AnnotationValue annotationValue, String source) {
if (annotationValue != null) {
for (Type type : annotationValue.asClassArray()) {
produceReflectiveHierarchy(reflectiveHierarchy, type, source);
}
}
}
private void produceReflectiveHierarchy(BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy, Type type,
String source) {
reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem.Builder()
.type(type)
.ignoreTypePredicate(ResteasyDotNames.IGNORE_TYPE_FOR_REFLECTION_PREDICATE)
.ignoreFieldPredicate(ResteasyDotNames.IGNORE_FIELD_FOR_REFLECTION_PREDICATE)
.ignoreMethodPredicate(ResteasyDotNames.IGNORE_METHOD_FOR_REFLECTION_PREDICATE)
.source(source)
.build());
}
private void storeGeneratedSchema(SmallRyeOpenApiConfig openApiConfig, OutputTargetBuildItem out, byte[] schemaDocument,
Format format) throws IOException {
Path directory = openApiConfig.storeSchemaDirectory.get();
Path outputDirectory = out.getOutputDirectory();
if (!directory.isAbsolute() && outputDirectory != null) {
directory = Paths.get(outputDirectory.getParent().toString(), directory.toString());
}
if (!Files.exists(directory)) {
Files.createDirectories(directory);
}
Path file = Paths.get(directory.toString(), "openapi." + format.toString().toLowerCase());
if (!Files.exists(file)) {
Files.createFile(file);
}
Files.write(file, schemaDocument, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
log.info("OpenAPI " + format.toString() + " saved: " + file.toString());
}
private boolean shouldScanAnnotations(Capabilities capabilities, IndexView index) {
// Disabled via config
Config config = ConfigProvider.getConfig();
boolean scanDisable = config.getOptionalValue(OASConfig.SCAN_DISABLE, Boolean.class).orElse(false);
if (scanDisable) {
return false;
}
// Only scan if either RESTEasy, Quarkus REST, Spring Web or Vert.x Web (with @Route) is used
boolean isRestEasy = capabilities.isPresent(Capability.RESTEASY);
boolean isQuarkusRest = capabilities.isPresent(Capability.RESTEASY_REACTIVE);
boolean isSpring = capabilities.isPresent(Capability.SPRING_WEB);
boolean isVertx = isUsingVertxRoute(index);
return isRestEasy || isQuarkusRest || isSpring || isVertx;
}
private boolean isUsingVertxRoute(IndexView index) {
if (!index.getAnnotations(VertxConstants.ROUTE).isEmpty()
|| !index.getAnnotations(VertxConstants.ROUTE_BASE).isEmpty()) {
return true;
}
return false;
}
private OpenAPI generateStaticModel(SmallRyeOpenApiConfig openApiConfig, Path target) throws IOException {
if (openApiConfig.ignoreStaticDocument) {
return null;
} else {
List<Result> results = findStaticModels(openApiConfig, target);
if (!results.isEmpty()) {
OpenAPI mergedStaticModel = new OpenAPIImpl();
for (Result result : results) {
try (InputStream is = result.inputStream;
OpenApiStaticFile staticFile = new OpenApiStaticFile(is, result.format)) {
OpenAPI staticFileModel = io.smallrye.openapi.runtime.OpenApiProcessor.modelFromStaticFile(staticFile);
mergedStaticModel = MergeUtil.mergeObjects(mergedStaticModel, staticFileModel);
}
}
return mergedStaticModel;
}
return null;
}
}
private OpenAPI generateAnnotationModel(IndexView indexView, Capabilities capabilities,
HttpRootPathBuildItem httpRootPathBuildItem,
Optional<ResteasyJaxrsConfigBuildItem> resteasyJaxrsConfig) {
Config config = ConfigProvider.getConfig();
OpenApiConfig openApiConfig = OpenApiConfigImpl.fromConfig(config);
List<AnnotationScannerExtension> extensions = new ArrayList<>();
// Add the RESTEasy extension if the capability is present
String defaultPath = httpRootPathBuildItem.getRootPath();
if (capabilities.isPresent(Capability.RESTEASY)) {
extensions.add(new RESTEasyExtension(indexView));
if (resteasyJaxrsConfig.isPresent()) {
defaultPath = resteasyJaxrsConfig.get().getRootPath();
}
} else if (capabilities.isPresent(Capability.RESTEASY_REACTIVE)) {
extensions.add(new RESTEasyExtension(indexView));
openApiConfig.doAllowNakedPathParameter();
Optional<String> maybePath = config.getOptionalValue("quarkus.resteasy-reactive.path", String.class);
if (maybePath.isPresent()) {
defaultPath = maybePath.get();
}
}
if (defaultPath != null && !"/".equals(defaultPath)) {
extensions.add(new CustomPathExtension(defaultPath));
}
OpenApiAnnotationScanner openApiAnnotationScanner = new OpenApiAnnotationScanner(openApiConfig, indexView, extensions);
return openApiAnnotationScanner.scan(getScanners(capabilities, indexView));
}
private String[] getScanners(Capabilities capabilities, IndexView index) {
List<String> scanners = new ArrayList<>();
if (capabilities.isPresent(Capability.RESTEASY) || capabilities.isPresent(Capability.RESTEASY_REACTIVE)) {
scanners.add(JAX_RS);
}
if (capabilities.isPresent(Capability.SPRING_WEB)) {
scanners.add(SPRING);
}
if (isUsingVertxRoute(index)) {
scanners.add(VERT_X);
}
return scanners.toArray(new String[] {});
}
private List<Result> findStaticModels(SmallRyeOpenApiConfig openApiConfig, Path target) {
List<Result> results = new ArrayList<>();
// First check for the file in both META-INF and WEB-INF/classes/META-INF
results = addStaticModelIfExist(results, Format.YAML, META_INF_OPENAPI_YAML);
results = addStaticModelIfExist(results, Format.YAML, WEB_INF_CLASSES_META_INF_OPENAPI_YAML);
results = addStaticModelIfExist(results, Format.YAML, META_INF_OPENAPI_YML);
results = addStaticModelIfExist(results, Format.YAML, WEB_INF_CLASSES_META_INF_OPENAPI_YML);
results = addStaticModelIfExist(results, Format.JSON, META_INF_OPENAPI_JSON);
results = addStaticModelIfExist(results, Format.JSON, WEB_INF_CLASSES_META_INF_OPENAPI_JSON);
// Add any aditional directories if configured
if (openApiConfig.additionalDocsDirectory.isPresent()) {
List<Path> additionalStaticDocuments = openApiConfig.additionalDocsDirectory.get();
for (Path path : additionalStaticDocuments) {
// Scan all yaml and json files
try {
List<String> filesInDir = getResourceFiles(path.toString(), target);
for (String possibleModelFile : filesInDir) {
results = addStaticModelIfExist(results, possibleModelFile);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
return results;
}
private List<Result> addStaticModelIfExist(List<Result> results, String path) {
if (path.endsWith(".json")) {
// Scan a specific json file
results = addStaticModelIfExist(results, Format.JSON, path);
} else if (path.endsWith(".yaml") || path.endsWith(".yml")) {
// Scan a specific yaml file
results = addStaticModelIfExist(results, Format.YAML, path);
}
return results;
}
private List<Result> addStaticModelIfExist(List<Result> results, Format format, String path) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try (InputStream inputStream = cl.getResourceAsStream(path)) {
if (inputStream != null) {
results.add(new Result(format, inputStream));
}
} catch (IOException ex) {
ex.printStackTrace();
}
return results;
}
private List<String> getResourceFiles(String pathName, Path target) throws IOException {
List<String> filenames = new ArrayList<>();
if (target == null) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try (InputStream inputStream = cl.getResourceAsStream(pathName)) {
if (inputStream != null) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String resource;
while ((resource = br.readLine()) != null) {
filenames.add(pathName + "/" + resource);
}
}
}
}
} else {
Path classes = target.resolve("classes");
if (classes != null) {
Path path = classes.resolve(pathName);
return Files.list(path).map((t) -> {
return pathName + "/" + t.getFileName().toString();
}).collect(Collectors.toList());
}
}
return filenames;
}
static class Result {
final Format format;
final InputStream inputStream;
Result(Format format, InputStream inputStream) {
this.format = format;
this.inputStream = inputStream;
}
}
private OpenApiDocument loadDocument(OpenAPI staticModel, OpenAPI annotationModel,
List<AddToOpenAPIDefinitionBuildItem> openAPIBuildItems) {
OpenApiDocument document = prepareOpenApiDocument(staticModel, annotationModel, openAPIBuildItems);
Config c = ConfigProvider.getConfig();
String title = c.getOptionalValue("quarkus.application.name", String.class).orElse("Generated");
String version = c.getOptionalValue("quarkus.application.version", String.class).orElse("1.0");
document.archiveName(title);
document.version(version);
document.initialize();
return document;
}
private void storeDocument(OutputTargetBuildItem out,
SmallRyeOpenApiConfig smallRyeOpenApiConfig,
OpenAPI staticModel,
OpenAPI annotationModel,
List<AddToOpenAPIDefinitionBuildItem> openAPIBuildItems) throws IOException {
Config config = ConfigProvider.getConfig();
OpenApiConfig openApiConfig = new OpenApiConfigImpl(config);
OpenApiDocument document = prepareOpenApiDocument(staticModel, annotationModel, openAPIBuildItems);
document.filter(filter(openApiConfig)); // This usually happens at runtime, so when storing we want to filter here too.
document.initialize();
for (Format format : Format.values()) {
String name = OpenApiConstants.BASE_NAME + format;
byte[] schemaDocument = OpenApiSerializer.serialize(document.get(), format).getBytes(StandardCharsets.UTF_8);
storeGeneratedSchema(smallRyeOpenApiConfig, out, schemaDocument, format);
}
}
private OpenApiDocument prepareOpenApiDocument(OpenAPI staticModel,
OpenAPI annotationModel,
List<AddToOpenAPIDefinitionBuildItem> openAPIBuildItems) {
Config config = ConfigProvider.getConfig();
OpenApiConfig openApiConfig = new OpenApiConfigImpl(config);
OpenAPI readerModel = OpenApiProcessor.modelFromReader(openApiConfig,
Thread.currentThread().getContextClassLoader());
OpenApiDocument document = createDocument(openApiConfig);
if (annotationModel != null) {
document.modelFromAnnotations(annotationModel);
}
document.modelFromReader(readerModel);
document.modelFromStaticFile(staticModel);
for (AddToOpenAPIDefinitionBuildItem openAPIBuildItem : openAPIBuildItems) {
OASFilter otherExtensionFilter = openAPIBuildItem.getOASFilter();
document.filter(otherExtensionFilter);
}
return document;
}
private OpenApiDocument createDocument(OpenApiConfig openApiConfig) {
OpenApiDocument document = OpenApiDocument.INSTANCE;
document.reset();
document.config(openApiConfig);
return document;
}
private OASFilter filter(OpenApiConfig openApiConfig) {
return OpenApiProcessor.getFilter(openApiConfig,
Thread.currentThread().getContextClassLoader());
}
}
|
package peergos.shared.user.fs;
import jsinterop.annotations.*;
import peergos.shared.*;
import peergos.shared.crypto.*;
import peergos.shared.crypto.asymmetric.*;
import peergos.shared.crypto.random.*;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.io.ipfs.multihash.*;
import peergos.shared.user.*;
import peergos.shared.user.fs.cryptree.*;
import peergos.shared.util.*;
import java.io.*;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
import java.util.stream.*;
public class FileTreeNode {
final static int[] BMP = new int[]{66, 77};
final static int[] GIF = new int[]{71, 73, 70};
final static int[] JPEG = new int[]{255, 216};
final static int[] PNG = new int[]{137, 80, 78, 71, 13, 10, 26, 10};
final static int HEADER_BYTES_TO_IDENTIFY_IMAGE_FILE = 8;
final static int THUMBNAIL_SIZE = 100;
private final NativeJSThumbnail thumbnail;
private final RetrievedFilePointer pointer;
private final FileProperties props;
private final String ownername;
private final Optional<TrieNode> globalRoot;
private final Set<String> readers;
private final Set<String> writers;
private final Optional<SecretSigningKey> entryWriterKey;
private AtomicBoolean modified = new AtomicBoolean(); // This only used as a guard against concurrent modifications
/**
*
* @param globalRoot This is only present for if this is the global root
* @param pointer
* @param ownername
* @param readers
* @param writers
* @param entryWriterKey
*/
public FileTreeNode(Optional<TrieNode> globalRoot, RetrievedFilePointer pointer, String ownername,
Set<String> readers, Set<String> writers, Optional<SecretSigningKey> entryWriterKey) {
this.globalRoot = globalRoot;
this.pointer = pointer == null ? null : pointer.withWriter(entryWriterKey);
this.ownername = ownername;
this.readers = readers;
this.writers = writers;
this.entryWriterKey = entryWriterKey;
if (pointer == null)
props = new FileProperties("/", 0, LocalDateTime.MIN, false, Optional.empty());
else {
SymmetricKey parentKey = this.getParentKey();
props = pointer.fileAccess.getProperties(parentKey);
}
thumbnail = new NativeJSThumbnail();
}
public FileTreeNode(RetrievedFilePointer pointer, String ownername,
Set<String> readers, Set<String> writers, Optional<SecretSigningKey> entryWriterKey) {
this(Optional.empty(), pointer, ownername, readers, writers, entryWriterKey);
}
public FileTreeNode withTrieNode(TrieNode trie) {
return new FileTreeNode(Optional.of(trie), pointer, ownername, readers, writers, entryWriterKey);
}
private FileTreeNode withCryptreeNode(CryptreeNode access) {
return new FileTreeNode(globalRoot, new RetrievedFilePointer(getPointer().filePointer, access), ownername,
readers, writers, entryWriterKey);
}
@JsMethod
public boolean equals(Object other) {
if (other == null)
return false;
if (!(other instanceof FileTreeNode))
return false;
return pointer.equals(((FileTreeNode)other).getPointer());
}
public RetrievedFilePointer getPointer() {
return pointer;
}
public boolean isRoot() {
return props.name.equals("/");
}
public CompletableFuture<String> getPath(NetworkAccess network) {
return retrieveParent(network).thenCompose(parent -> {
if (!parent.isPresent() || parent.get().isRoot())
return CompletableFuture.completedFuture("/" + props.name);
return parent.get().getPath(network).thenApply(parentPath -> parentPath + "/" + props.name);
});
}
public CompletableFuture<Optional<FileTreeNode>> getDescendentByPath(String path, NetworkAccess network) {
ensureUnmodified();
if (path.length() == 0)
return CompletableFuture.completedFuture(Optional.of(this));
if (path.equals("/"))
if (isDirectory())
return CompletableFuture.completedFuture(Optional.of(this));
else
return CompletableFuture.completedFuture(Optional.empty());
if (path.startsWith("/"))
path = path.substring(1);
int slash = path.indexOf("/");
String prefix = slash > 0 ? path.substring(0, slash) : path;
String suffix = slash > 0 ? path.substring(slash + 1) : "";
return getChildren(network).thenCompose(children -> {
for (FileTreeNode child : children)
if (child.getFileProperties().name.equals(prefix)) {
return child.getDescendentByPath(suffix, network);
}
return CompletableFuture.completedFuture(Optional.empty());
});
}
private void ensureUnmodified() {
if (modified.get())
throw new IllegalStateException("This file has already been modified, use the returned instance");
}
private void setModified() {
if (modified.get())
throw new IllegalStateException("This file has already been modified, use the returned instance");
modified.set(true);
}
/** Marks a file/directory and all its descendants as dirty. Directories are immediately cleaned,
* but files have all their keys except the actual data key cleaned. That is cleaned lazily, the next time it is modified
*
* @param network
* @param parent
* @param readersToRemove
* @return
* @throws IOException
*/
public CompletableFuture<FileTreeNode> makeDirty(NetworkAccess network, SafeRandom random,
FileTreeNode parent, Set<String> readersToRemove) {
if (!isWritable())
throw new IllegalStateException("You cannot mark a file as dirty without write access!");
if (isDirectory()) {
// create a new baseKey == subfoldersKey and make all descendants dirty
SymmetricKey newSubfoldersKey = SymmetricKey.random();
FilePointer ourNewPointer = pointer.filePointer.withBaseKey(newSubfoldersKey);
SymmetricKey newParentKey = SymmetricKey.random();
FileProperties props = getFileProperties();
DirAccess existing = (DirAccess) pointer.fileAccess;
// Create new DirAccess, but don't upload it
DirAccess newDirAccess = DirAccess.create(existing.committedHash(), newSubfoldersKey, props, parent.pointer.filePointer.getLocation(),
parent.getParentKey(), newParentKey);
// re add children
List<FilePointer> subdirs = existing.getSubfolders().stream().map(link ->
new FilePointer(link.targetLocation(pointer.filePointer.baseKey),
Optional.empty(), link.target(pointer.filePointer.baseKey))).collect(Collectors.toList());
return newDirAccess.addSubdirsAndCommit(subdirs, newSubfoldersKey, ourNewPointer, getSigner(), network, random)
.thenCompose(updatedDirAccess -> {
SymmetricKey filesKey = existing.getFilesKey(pointer.filePointer.baseKey);
List<FilePointer> files = existing.getFiles().stream()
.map(link -> new FilePointer(link.targetLocation(filesKey), Optional.empty(), link.target(filesKey)))
.collect(Collectors.toList());
return updatedDirAccess.addFilesAndCommit(files, newSubfoldersKey, ourNewPointer, getSigner(), network, random)
.thenCompose(fullyUpdatedDirAccess -> {
readers.removeAll(readersToRemove);
RetrievedFilePointer ourNewRetrievedPointer = new RetrievedFilePointer(ourNewPointer, fullyUpdatedDirAccess);
FileTreeNode theNewUs = new FileTreeNode(ourNewRetrievedPointer,
ownername, readers, writers, entryWriterKey);
// clean all subtree keys except file dataKeys (lazily re-key and re-encrypt them)
return getChildren(network).thenCompose(children -> {
for (FileTreeNode child : children) {
child.makeDirty(network, random, theNewUs, readersToRemove);
}
// update pointer from parent to us
return ((DirAccess) parent.pointer.fileAccess)
.updateChildLink(parent.pointer.filePointer, this.pointer,
ourNewRetrievedPointer, getSigner(), network, random)
.thenApply(x -> theNewUs);
});
});
}).thenApply(x -> {
setModified();
return x;
});
} else {
// create a new baseKey == parentKey and mark the metaDataKey as dirty
SymmetricKey parentKey = SymmetricKey.random();
return ((FileAccess) pointer.fileAccess).markDirty(writableFilePointer(), parentKey, network).thenCompose(newFileAccess -> {
// changing readers here will only affect the returned FileTreeNode, as the readers are derived from the entry point
TreeSet<String> newReaders = new TreeSet<>(readers);
newReaders.removeAll(readersToRemove);
RetrievedFilePointer newPointer = new RetrievedFilePointer(this.pointer.filePointer.withBaseKey(parentKey), newFileAccess);
// update link from parent folder to file to have new baseKey
return ((DirAccess) parent.pointer.fileAccess)
.updateChildLink(parent.writableFilePointer(), pointer, newPointer, getSigner(), network, random)
.thenApply(x -> new FileTreeNode(newPointer, ownername, newReaders, writers, entryWriterKey));
}).thenApply(x -> {
setModified();
return x;
});
}
}
public CompletableFuture<Boolean> hasChildWithName(String name, NetworkAccess network) {
ensureUnmodified();
return getChildren(network)
.thenApply(children -> children.stream().filter(c -> c.props.name.equals(name)).findAny().isPresent());
}
public CompletableFuture<FileTreeNode> removeChild(FileTreeNode child, NetworkAccess network) {
setModified();
return ((DirAccess)pointer.fileAccess)
.removeChild(child.getPointer(), pointer.filePointer, getSigner(), network)
.thenApply(updated -> new FileTreeNode(globalRoot,
new RetrievedFilePointer(getPointer().filePointer, updated), ownername, readers,
writers, entryWriterKey));
}
public CompletableFuture<FileTreeNode> addLinkTo(FileTreeNode file, NetworkAccess network, SafeRandom random) {
ensureUnmodified();
CompletableFuture<FileTreeNode> error = new CompletableFuture<>();
if (!this.isDirectory() || !this.isWritable()) {
error.completeExceptionally(new IllegalArgumentException("Can only add link toa writable directory!"));
return error;
}
String name = file.getFileProperties().name;
return hasChildWithName(name, network).thenCompose(hasChild -> {
if (hasChild) {
error.completeExceptionally(new IllegalStateException("Child already exists with name: " + name));
return error;
}
DirAccess toUpdate = (DirAccess) pointer.fileAccess;
return (file.isDirectory() ?
toUpdate.addSubdirAndCommit(file.pointer.filePointer, this.getKey(),
pointer.filePointer, getSigner(), network, random) :
toUpdate.addFileAndCommit(file.pointer.filePointer, this.getKey(),
pointer.filePointer, getSigner(), network, random))
.thenApply(dirAccess -> new FileTreeNode(this.pointer, ownername, readers, writers, entryWriterKey));
});
}
@JsMethod
public String toLink() {
return pointer.filePointer.toLink();
}
@JsMethod
public boolean isWritable() {
return entryWriterKey.isPresent();
}
@JsMethod
public boolean isReadable() {
try {
pointer.fileAccess.getMetaKey(pointer.filePointer.baseKey);
return false;
} catch (Exception e) {}
return true;
}
public SymmetricKey getKey() {
return pointer.filePointer.baseKey;
}
public Location getLocation() {
return pointer.filePointer.getLocation();
}
private SigningPrivateKeyAndPublicHash getSigner() {
if (! isWritable())
throw new IllegalStateException("Can only get a signer for a writable directory!");
return new SigningPrivateKeyAndPublicHash(getLocation().writer, entryWriterKey.get());
}
public Set<Location> getChildrenLocations() {
ensureUnmodified();
if (!this.isDirectory())
return Collections.emptySet();
return ((DirAccess)pointer.fileAccess).getChildrenLocations(pointer.filePointer.baseKey);
}
public CompletableFuture<Optional<FileTreeNode>> retrieveParent(NetworkAccess network) {
ensureUnmodified();
if (pointer == null)
return CompletableFuture.completedFuture(Optional.empty());
SymmetricKey parentKey = getParentKey();
CompletableFuture<RetrievedFilePointer> parent = pointer.fileAccess.getParent(parentKey, network);
return parent.thenApply(parentRFP -> {
if (parentRFP == null)
return Optional.empty();
return Optional.of(new FileTreeNode(parentRFP, ownername, Collections.emptySet(), Collections.emptySet(), entryWriterKey));
});
}
public SymmetricKey getParentKey() {
ensureUnmodified();
SymmetricKey parentKey = pointer.filePointer.baseKey;
if (this.isDirectory())
try {
parentKey = pointer.fileAccess.getParentKey(parentKey);
} catch (Exception e) {
// if we don't have read access to this folder, then we must just have the parent key already
}
return parentKey;
}
@JsMethod
public CompletableFuture<Set<FileTreeNode>> getChildren(NetworkAccess network) {
ensureUnmodified();
if (globalRoot.isPresent())
return globalRoot.get().getChildren("/", network);
if (isReadable()) {
return retrieveChildren(network).thenApply(childrenRFPs -> {
Set<FileTreeNode> newChildren = childrenRFPs.stream()
.map(x -> new FileTreeNode(x, ownername, readers, writers, entryWriterKey))
.collect(Collectors.toSet());
return newChildren.stream().collect(Collectors.toSet());
});
}
throw new IllegalStateException("Unreadable FileTreeNode!");
}
public CompletableFuture<Optional<FileTreeNode>> getChild(String name, NetworkAccess network) {
return getChildren(network)
.thenApply(children -> children.stream().filter(f -> f.getName().equals(name)).findAny());
}
private CompletableFuture<Set<RetrievedFilePointer>> retrieveChildren(NetworkAccess network) {
FilePointer filePointer = pointer.filePointer;
CryptreeNode fileAccess = pointer.fileAccess;
SymmetricKey rootDirKey = filePointer.baseKey;
if (isReadable())
return ((DirAccess) fileAccess).getChildren(network, rootDirKey);
throw new IllegalStateException("No credentials to retrieve children!");
}
public CompletableFuture<FileTreeNode> cleanUnreachableChildren(NetworkAccess network) {
setModified();
FilePointer filePointer = pointer.filePointer;
CryptreeNode fileAccess = pointer.fileAccess;
SymmetricKey rootDirKey = filePointer.baseKey;
if (isReadable())
return ((DirAccess) fileAccess).cleanUnreachableChildren(network, rootDirKey, filePointer, getSigner())
.thenApply(da -> new FileTreeNode(globalRoot,
new RetrievedFilePointer(filePointer, da), ownername, readers, writers, entryWriterKey));
throw new IllegalStateException("No credentials to retrieve children!");
}
@JsMethod
public String getOwner() {
return ownername;
}
@JsMethod
public boolean isDirectory() {
boolean isNull = pointer == null;
return isNull || pointer.fileAccess.isDirectory();
}
public boolean isDirty() {
ensureUnmodified();
return pointer.fileAccess.isDirty(pointer.filePointer.baseKey);
}
/**
*
* @param network
* @param random
* @param parent
* @param fragmenter
* @return updated parent dir
*/
public CompletableFuture<FileTreeNode> clean(NetworkAccess network, SafeRandom random,
FileTreeNode parent, peergos.shared.user.fs.Fragmenter fragmenter) {
if (!isDirty())
return CompletableFuture.completedFuture(this);
if (isDirectory()) {
throw new IllegalStateException("Directories are never dirty (they are cleaned immediately)!");
} else {
FileProperties props = getFileProperties();
SymmetricKey baseKey = pointer.filePointer.baseKey;
// stream download and re-encrypt with new metaKey
return getInputStream(network, random, l -> {}).thenCompose(in -> {
byte[] tmp = new byte[16];
new Random().nextBytes(tmp);
String tmpFilename = ArrayOps.bytesToHex(tmp) + ".tmp";
CompletableFuture<FileTreeNode> reuploaded = parent.uploadFileSection(tmpFilename, in, 0, props.size,
Optional.of(baseKey), network, random, l -> {}, fragmenter);
return reuploaded.thenCompose(upload -> upload.getDescendentByPath(tmpFilename, network)
.thenCompose(tmpChild -> tmpChild.get().rename(props.name, network, upload, true))
.thenApply(res -> {
setModified();
return res;
}));
});
}
}
@JsMethod
public CompletableFuture<FileTreeNode> uploadFileJS(String filename, AsyncReader fileData, int lengthHi, int lengthLow,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor, Fragmenter fragmenter) {
return uploadFile(filename, fileData, lengthLow + ((lengthHi & 0xFFFFFFFFL) << 32), network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFile(String filename, AsyncReader fileData, long length,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor, Fragmenter fragmenter) {
return uploadFileSection(filename, fileData, 0, length, Optional.empty(), network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFile(String filename,
AsyncReader fileData,
boolean isHidden,
long length,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor,
Fragmenter fragmenter) {
return uploadFileSection(filename, fileData, isHidden, 0, length, Optional.empty(), network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFileSection(String filename, AsyncReader fileData, long startIndex, long endIndex,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor, Fragmenter fragmenter) {
return uploadFileSection(filename, fileData, startIndex, endIndex, Optional.empty(), network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFileSection(String filename, AsyncReader fileData,
long startIndex, long endIndex,
Optional<SymmetricKey> baseKey,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor,
Fragmenter fragmenter) {
return uploadFileSection(filename, fileData, false, startIndex, endIndex, baseKey, network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFileSection(String filename, AsyncReader fileData,
boolean isHidden,
long startIndex, long endIndex,
Optional<SymmetricKey> baseKey,
NetworkAccess network,
SafeRandom random,
ProgressConsumer<Long> monitor,
Fragmenter fragmenter) {
if (!isLegalName(filename)) {
CompletableFuture<FileTreeNode> res = new CompletableFuture<>();
res.completeExceptionally(new IllegalStateException("Illegal filename: " + filename));
return res;
}
if (! isDirectory()) {
CompletableFuture<FileTreeNode> res = new CompletableFuture<>();
res.completeExceptionally(new IllegalStateException("Cannot upload a sub file to a file!"));
return res;
}
return getDescendentByPath(filename, network).thenCompose(childOpt -> {
if (childOpt.isPresent()) {
return updateExistingChild(childOpt.get(), fileData, startIndex, endIndex, network, random, monitor, fragmenter);
}
if (startIndex > 0) {
// TODO if startIndex > 0 prepend with a zero section
throw new IllegalStateException("Unimplemented!");
}
SymmetricKey fileKey = baseKey.orElseGet(SymmetricKey::random);
SymmetricKey fileMetaKey = SymmetricKey.random();
SymmetricKey rootRKey = pointer.filePointer.baseKey;
DirAccess dirAccess = (DirAccess) pointer.fileAccess;
SymmetricKey dirParentKey = dirAccess.getParentKey(rootRKey);
Location parentLocation = getLocation();
int thumbnailSrcImageSize = startIndex == 0 && endIndex < Integer.MAX_VALUE ? (int)endIndex : 0;
return generateThumbnail(network, fileData, thumbnailSrcImageSize, filename).thenCompose(thumbData -> {
return fileData.reset().thenCompose(resetResult -> {
FileProperties fileProps = new FileProperties(filename, endIndex, LocalDateTime.now(), isHidden, Optional.of(thumbData));
FileUploader chunks = new FileUploader(filename, fileData, startIndex, endIndex, fileKey, fileMetaKey, parentLocation, dirParentKey, monitor, fileProps,
fragmenter);
byte[] mapKey = random.randomBytes(32);
Location nextChunkLocation = new Location(getLocation().owner, getLocation().writer, mapKey);
return chunks.upload(network, random, parentLocation.owner, getSigner(), nextChunkLocation)
.thenCompose(fileLocation -> {
FilePointer filePointer = new FilePointer(fileLocation, Optional.empty(), fileKey);
return addChildPointer(filename, filePointer, network, random, 2);
});
});
});
});
}
private CompletableFuture<FileTreeNode> addChildPointer(String filename,
FilePointer childPointer,
NetworkAccess network,
SafeRandom random,
int retries) {
CompletableFuture<FileTreeNode> result = new CompletableFuture<>();
((DirAccess) pointer.fileAccess).addFileAndCommit(childPointer, pointer.filePointer.baseKey, pointer.filePointer, getSigner(), network, random)
.thenAccept(uploadResult -> {
setModified();
result.complete(this.withCryptreeNode(uploadResult));
}).exceptionally(e -> {
if (e.getCause() instanceof Btree.CasException) {
// reload directory and try again
network.getMetadata(getLocation()).thenCompose(opt -> {
DirAccess updatedUs = (DirAccess) opt.get();
// Check another file of same name hasn't been added in the concurrent change
RetrievedFilePointer updatedPointer = new RetrievedFilePointer(pointer.filePointer, updatedUs);
FileTreeNode us = new FileTreeNode(globalRoot, updatedPointer, ownername, readers, writers, entryWriterKey);
return us.getChildren(network).thenCompose(children -> {
Set<String> childNames = children.stream()
.map(f -> f.getName())
.collect(Collectors.toSet());
String safeName = nextSafeReplacementFilename(filename, childNames);
// rename file in place as we've already uploaded it
return network.getMetadata(childPointer.location).thenCompose(renameOpt -> {
CryptreeNode fileToRename = renameOpt.get();
RetrievedFilePointer updatedChildPointer =
new RetrievedFilePointer(childPointer, fileToRename);
FileTreeNode toRename = new FileTreeNode(Optional.empty(),
updatedChildPointer, ownername, readers, writers, entryWriterKey);
return toRename.rename(safeName, network, us).thenCompose(usAgain ->
((DirAccess)usAgain.pointer.fileAccess)
.addFileAndCommit(childPointer, pointer.filePointer.baseKey,
pointer.filePointer, getSigner(), network, random)
.thenAccept(uploadResult -> {
setModified();
result.complete(this.withCryptreeNode(uploadResult));
}));
});
});
}).exceptionally(ex -> {
if (e.getCause() instanceof Btree.CasException && retries > 0)
addChildPointer(filename, childPointer, network, random, retries - 1)
.thenApply(f -> result.complete(f))
.exceptionally(e2 -> {
result.completeExceptionally(e2);
return null;
});
else
result.completeExceptionally(e);
return null;
});
} else
result.completeExceptionally(e);
return null;
});
return result;
}
private static String nextSafeReplacementFilename(String desired, Set<String> existing) {
if (! existing.contains(desired))
return desired;
for (int counter = 1; counter < 1000; counter++) {
int dot = desired.lastIndexOf(".");
String candidate = dot >= 0 ?
desired.substring(0, dot) + "[" + counter + "]" + desired.substring(dot) :
desired + "[" + counter + "]";
if (! existing.contains(candidate))
return candidate;
}
throw new IllegalStateException("Too many concurrent writes trying to add a file of the same name!");
}
private CompletableFuture<FileTreeNode> updateExistingChild(FileTreeNode existingChild, AsyncReader fileData,
long inputStartIndex, long endIndex,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor, Fragmenter fragmenter) {
String filename = existingChild.getFileProperties().name;
System.out.println("Overwriting section [" + Long.toHexString(inputStartIndex) + ", " + Long.toHexString(endIndex) + "] of child with name: " + filename);
Supplier<Location> locationSupplier = () -> new Location(getLocation().owner, getLocation().writer, random.randomBytes(32));
return (existingChild.isDirty() ?
existingChild.clean(network, random, this, fragmenter)
.thenCompose(us -> us.getChild(filename, network)
.thenApply(cleanedChild -> new Pair<>(us, cleanedChild.get()))) :
CompletableFuture.completedFuture(new Pair<>(this, existingChild))
).thenCompose(updatedPair -> {
FileTreeNode us = updatedPair.left;
FileTreeNode child = updatedPair.right;
FileProperties childProps = child.getFileProperties();
final AtomicLong filesSize = new AtomicLong(childProps.size);
FileRetriever retriever = child.getRetriever();
SymmetricKey baseKey = child.pointer.filePointer.baseKey;
FileAccess fileAccess = (FileAccess) child.pointer.fileAccess;
SymmetricKey dataKey = fileAccess.getDataKey(baseKey);
List<Long> startIndexes = new ArrayList<>();
for (long startIndex = inputStartIndex; startIndex < endIndex; startIndex = startIndex + Chunk.MAX_SIZE - (startIndex % Chunk.MAX_SIZE))
startIndexes.add(startIndex);
boolean identity = true;
BiFunction<Boolean, Long, CompletableFuture<Boolean>> composer = (id, startIndex) -> {
return retriever.getChunkInputStream(network, random, dataKey, startIndex, filesSize.get(),
child.getLocation(), child.pointer.fileAccess.committedHash(), monitor)
.thenCompose(currentLocation -> {
CompletableFuture<Optional<Location>> locationAt = retriever
.getLocationAt(child.getLocation(), startIndex + Chunk.MAX_SIZE, dataKey, network);
return locationAt.thenCompose(location ->
CompletableFuture.completedFuture(new Pair<>(currentLocation, location)));
}
).thenCompose(pair -> {
if (!pair.left.isPresent()) {
CompletableFuture<Boolean> result = new CompletableFuture<>();
result.completeExceptionally(new IllegalStateException("Current chunk not present"));
return result;
}
LocatedChunk currentOriginal = pair.left.get();
Optional<Location> nextChunkLocationOpt = pair.right;
Location nextChunkLocation = nextChunkLocationOpt.orElseGet(locationSupplier);
System.out.println("********** Writing to chunk at mapkey: " + ArrayOps.bytesToHex(currentOriginal.location.getMapKey()) + " next: " + nextChunkLocation);
// modify chunk, re-encrypt and upload
int internalStart = (int) (startIndex % Chunk.MAX_SIZE);
int internalEnd = endIndex - (startIndex - internalStart) > Chunk.MAX_SIZE ?
Chunk.MAX_SIZE : (int) (endIndex - (startIndex - internalStart));
byte[] rawData = currentOriginal.chunk.data();
// extend data array if necessary
if (rawData.length < internalEnd)
rawData = Arrays.copyOfRange(rawData, 0, internalEnd);
byte[] raw = rawData;
return fileData.readIntoArray(raw, internalStart, internalEnd - internalStart).thenCompose(read -> {
byte[] nonce = random.randomBytes(TweetNaCl.SECRETBOX_NONCE_BYTES);
Chunk updated = new Chunk(raw, dataKey, currentOriginal.location.getMapKey(), nonce);
LocatedChunk located = new LocatedChunk(currentOriginal.location, currentOriginal.existingHash, updated);
long currentSize = filesSize.get();
FileProperties newProps = new FileProperties(childProps.name, endIndex > currentSize ? endIndex : currentSize,
LocalDateTime.now(), childProps.isHidden, childProps.thumbnail);
CompletableFuture<Multihash> chunkUploaded = FileUploader.uploadChunk(getSigner(),
newProps, getLocation(), us.getParentKey(), baseKey, located,
fragmenter,
nextChunkLocation, network, monitor);
return chunkUploaded.thenCompose(isUploaded -> {
//update indices to be relative to next chunk
long updatedLength = startIndex + internalEnd - internalStart;
if (updatedLength > filesSize.get()) {
filesSize.set(updatedLength);
if (updatedLength > Chunk.MAX_SIZE) {
// update file size in FileProperties of first chunk
CompletableFuture<Boolean> updatedSize = getChildren(network).thenCompose(children -> {
Optional<FileTreeNode> updatedChild = children.stream()
.filter(f -> f.getFileProperties().name.equals(filename))
.findAny();
return updatedChild.get().setProperties(child.getFileProperties().withSize(endIndex), network, this);
});
}
}
return CompletableFuture.completedFuture(true);
});
});
});
};
BiFunction<Boolean, Boolean, Boolean> combiner = (left, right) -> left && right;
return Futures.reduceAll(startIndexes, identity, composer, combiner)
.thenApply(b -> us);
});
}
static boolean isLegalName(String name) {
return !name.contains("/");
}
@JsMethod
public CompletableFuture<FilePointer> mkdir(String newFolderName, NetworkAccess network, boolean isSystemFolder,
SafeRandom random) throws IOException {
return mkdir(newFolderName, network, null, isSystemFolder, random);
}
public CompletableFuture<FilePointer> mkdir(String newFolderName,
NetworkAccess network,
SymmetricKey requestedBaseSymmetricKey,
boolean isSystemFolder,
SafeRandom random) {
CompletableFuture<FilePointer> result = new CompletableFuture<>();
if (!this.isDirectory()) {
result.completeExceptionally(new IllegalStateException("Cannot mkdir in a file!"));
return result;
}
if (!isLegalName(newFolderName)) {
result.completeExceptionally(new IllegalStateException("Illegal directory name: " + newFolderName));
return result;
}
return hasChildWithName(newFolderName, network).thenCompose(hasChild -> {
if (hasChild) {
result.completeExceptionally(new IllegalStateException("Child already exists with name: " + newFolderName));
return result;
}
FilePointer dirPointer = pointer.filePointer;
DirAccess dirAccess = (DirAccess) pointer.fileAccess;
SymmetricKey rootDirKey = dirPointer.baseKey;
return dirAccess.mkdir(newFolderName, network, dirPointer.location.owner, getSigner(), dirPointer.getLocation().getMapKey(), rootDirKey,
requestedBaseSymmetricKey, isSystemFolder, random).thenApply(x -> {
setModified();
return x;
});
});
}
@JsMethod
public CompletableFuture<FileTreeNode> rename(String newFilename, NetworkAccess network, FileTreeNode parent) {
return rename(newFilename, network, parent, false);
}
/**
*
* @param newFilename
* @param network
* @param parent
* @param overwrite
* @return the updated parent
*/
public CompletableFuture<FileTreeNode> rename(String newFilename, NetworkAccess network,
FileTreeNode parent, boolean overwrite) {
setModified();
if (! isLegalName(newFilename))
return CompletableFuture.completedFuture(parent);
CompletableFuture<Optional<FileTreeNode>> childExists = parent == null ?
CompletableFuture.completedFuture(Optional.empty()) :
parent.getDescendentByPath(newFilename, network);
return childExists
.thenCompose(existing -> {
if (existing.isPresent() && !overwrite)
return CompletableFuture.completedFuture(parent);
return ((overwrite && existing.isPresent()) ?
existing.get().remove(network, parent) :
CompletableFuture.completedFuture(parent)
).thenCompose(res -> {
//get current props
FilePointer filePointer = pointer.filePointer;
SymmetricKey baseKey = filePointer.baseKey;
CryptreeNode fileAccess = pointer.fileAccess;
SymmetricKey key = this.isDirectory() ? fileAccess.getParentKey(baseKey) : baseKey;
FileProperties currentProps = fileAccess.getProperties(key);
FileProperties newProps = new FileProperties(newFilename, currentProps.size, currentProps.modified, currentProps.isHidden, currentProps.thumbnail);
return fileAccess.updateProperties(writableFilePointer(), newProps, network)
.thenApply(fa -> res);
});
});
}
public CompletableFuture<Boolean> setProperties(FileProperties updatedProperties, NetworkAccess network, FileTreeNode parent) {
setModified();
String newName = updatedProperties.name;
CompletableFuture<Boolean> result = new CompletableFuture<>();
if (!isLegalName(newName)) {
result.completeExceptionally(new IllegalArgumentException("Illegal file name: " + newName));
return result;
}
return (parent == null ?
CompletableFuture.completedFuture(false) :
parent.hasChildWithName(newName, network))
.thenCompose(hasChild -> {
if (hasChild && parent!= null && !parent.getChildrenLocations().stream()
.map(l -> new ByteArrayWrapper(l.getMapKey()))
.collect(Collectors.toSet())
.contains(new ByteArrayWrapper(pointer.filePointer.getLocation().getMapKey()))) {
result.completeExceptionally(new IllegalStateException("Cannot rename to same name as an existing file"));
return result;
}
CryptreeNode fileAccess = pointer.fileAccess;
return fileAccess.updateProperties(writableFilePointer(), updatedProperties, network)
.thenApply(fa -> true);
});
}
private FilePointer writableFilePointer() {
FilePointer filePointer = pointer.filePointer;
SymmetricKey baseKey = filePointer.baseKey;
return new FilePointer(filePointer.location, entryWriterKey, baseKey);
}
public Optional<SecretSigningKey> getEntryWriterKey() {
return entryWriterKey;
}
@JsMethod
public CompletableFuture<FileTreeNode> copyTo(FileTreeNode target,
NetworkAccess network,
SafeRandom random,
Fragmenter fragmenter) {
ensureUnmodified();
CompletableFuture<FileTreeNode> result = new CompletableFuture<>();
if (! target.isDirectory()) {
result.completeExceptionally(new IllegalStateException("CopyTo target " + target + " must be a directory"));
return result;
}
return target.hasChildWithName(getFileProperties().name, network).thenCompose(childExists -> {
if (childExists) {
result.completeExceptionally(new IllegalStateException("CopyTo target " + target + " already has child with name " + getFileProperties().name));
return result;
}
boolean sameWriter = getLocation().writer.equals(target.getLocation().writer);
//make new FileTreeNode pointing to the same file if we are the same writer, but with a different location
if (sameWriter) {
byte[] newMapKey = new byte[32];
random.randombytes(newMapKey, 0, 32);
SymmetricKey ourBaseKey = this.getKey();
SymmetricKey newBaseKey = SymmetricKey.random();
FilePointer newRFP = new FilePointer(target.getLocation().owner, target.getLocation().writer, newMapKey, newBaseKey);
Location newParentLocation = target.getLocation();
SymmetricKey newParentParentKey = target.getParentKey();
return pointer.fileAccess.copyTo(ourBaseKey, newBaseKey, newParentLocation, newParentParentKey,
target.getLocation().writer, getSigner(), newMapKey, network, random)
.thenCompose(newAccess -> {
// upload new metadatablob
RetrievedFilePointer newRetrievedFilePointer = new RetrievedFilePointer(newRFP, newAccess);
FileTreeNode newFileTreeNode = new FileTreeNode(newRetrievedFilePointer, target.getOwner(),
Collections.emptySet(), Collections.emptySet(), target.getEntryWriterKey());
return target.addLinkTo(newFileTreeNode, network, random);
});
} else {
return getInputStream(network, random, x -> {})
.thenCompose(stream -> target.uploadFile(getName(), stream, getSize(), network, random, x -> {}, fragmenter)
.thenApply(b -> target));
}
});
}
/**
*
* @param network
* @param parent
* @return updated parent
*/
@JsMethod
public CompletableFuture<FileTreeNode> remove(NetworkAccess network, FileTreeNode parent) {
ensureUnmodified();
Supplier<CompletableFuture<Boolean>> supplier = () -> new RetrievedFilePointer(writableFilePointer(), pointer.fileAccess)
.remove(network, null, getSigner());
if (parent != null) {
return parent.removeChild(this, network)
.thenCompose(updated -> supplier.get()
.thenApply(x -> updated));
}
return supplier.get().thenApply(x -> parent);
}
public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor) {
return getInputStream(network, random, getFileProperties().size, monitor);
}
@JsMethod
public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network,
SafeRandom random,
int fileSizeHi,
int fileSizeLow,
ProgressConsumer<Long> monitor) {
return getInputStream(network, random, fileSizeLow + ((fileSizeHi & 0xFFFFFFFFL) << 32), monitor);
}
public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network,
SafeRandom random,
long fileSize,
ProgressConsumer<Long> monitor) {
ensureUnmodified();
if (pointer.fileAccess.isDirectory())
throw new IllegalStateException("Cannot get input stream for a directory!");
FileAccess fileAccess = (FileAccess) pointer.fileAccess;
SymmetricKey baseKey = pointer.filePointer.baseKey;
SymmetricKey dataKey = fileAccess.getDataKey(baseKey);
return fileAccess.retriever().getFile(network, random, dataKey, fileSize, getLocation(), fileAccess.committedHash(), monitor);
}
private FileRetriever getRetriever() {
if (pointer.fileAccess.isDirectory())
throw new IllegalStateException("Cannot get input stream for a directory!");
FileAccess fileAccess = (FileAccess) pointer.fileAccess;
return fileAccess.retriever();
}
@JsMethod
public String getBase64Thumbnail() {
Optional<byte[]> thumbnail = props.thumbnail;
if(thumbnail.isPresent()){
String base64Data = Base64.getEncoder().encodeToString(thumbnail.get());
return "data:image/png;base64," + base64Data;
}else{
return "";
}
}
@JsMethod
public FileProperties getFileProperties() {
ensureUnmodified();
return props;
}
public String getName() {
return getFileProperties().name;
}
public long getSize() {
return getFileProperties().size;
}
public String toString() {
return getFileProperties().name;
}
public static FileTreeNode createRoot(TrieNode root) {
return new FileTreeNode(Optional.of(root), null, null, Collections.EMPTY_SET, Collections.EMPTY_SET, null);
}
private CompletableFuture<byte[]> generateThumbnail(NetworkAccess network, AsyncReader fileData, int fileSize, String filename)
{
CompletableFuture<byte[]> fut = new CompletableFuture<>();
if(network.isJavascript() && fileSize > 0) {
isImage(fileData).thenAccept(isThumbnail -> {
if(isThumbnail) {
thumbnail.generateThumbnail(fileData, fileSize, filename).thenAccept(base64Str -> {
byte[] bytesOfData = Base64.getDecoder().decode(base64Str);
fut.complete(bytesOfData);
});
} else{
fut.complete(new byte[0]);
}
});
} else {
fut.complete(new byte[0]);
}
return fut;
}
private CompletableFuture<Boolean> isImage(AsyncReader imageBlob)
{
CompletableFuture<Boolean> result = new CompletableFuture<>();
byte[] data = new byte[HEADER_BYTES_TO_IDENTIFY_IMAGE_FILE];
imageBlob.readIntoArray(data, 0, HEADER_BYTES_TO_IDENTIFY_IMAGE_FILE).thenAccept(numBytesRead -> {
imageBlob.reset().thenAccept(resetResult -> {
if(numBytesRead < HEADER_BYTES_TO_IDENTIFY_IMAGE_FILE) {
result.complete(false);
}else {
byte[] tempBytes = Arrays.copyOfRange(data, 0, 2);
if (!compareArrayContents(Arrays.copyOfRange(data, 0, BMP.length), BMP)
&& !compareArrayContents(Arrays.copyOfRange(data, 0, GIF.length), GIF)
&& !compareArrayContents(Arrays.copyOfRange(data, 0, PNG.length), PNG)
&& !compareArrayContents(Arrays.copyOfRange(data, 0, 2), JPEG)) {
result.complete(false);
}else {
result.complete(true);
}
}
});
});
return result;
}
private boolean compareArrayContents(byte[] a, int[] a2) {
if (a==null || a2==null){
return false;
}
int length = a.length;
if (a2.length != length){
return false;
}
for (int i=0; i<length; i++) {
if (a[i] != a2[i]) {
return false;
}
}
return true;
}
}
|
package peergos.shared.user.fs;
import jsinterop.annotations.*;
import peergos.shared.*;
import peergos.shared.crypto.*;
import peergos.shared.crypto.asymmetric.*;
import peergos.shared.crypto.random.*;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.io.ipfs.multihash.*;
import peergos.shared.user.*;
import peergos.shared.user.fs.cryptree.*;
import peergos.shared.util.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.AlphaComposite;
import java.awt.RenderingHints;
import java.io.*;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
import java.util.stream.*;
public class FileTreeNode {
final static int[] ID3 = new int[]{'I', 'D', '3'};
final static int[] MP3 = new int[]{0xff, 0xfb};
final static int[] MP4 = new int[]{'f', 't', 'y', 'p'};
final static int[] BMP = new int[]{66, 77};
final static int[] GIF = new int[]{71, 73, 70};
final static int[] JPEG = new int[]{255, 216};
final static int[] PNG = new int[]{137, 80, 78, 71, 13, 10, 26, 10};
final static int HEADER_BYTES_TO_IDENTIFY_IMAGE_FILE = 8;
final static int THUMBNAIL_SIZE = 100;
private final NativeJSThumbnail thumbnail;
private final RetrievedFilePointer pointer;
private final FileProperties props;
private final String ownername;
private final Optional<TrieNode> globalRoot;
private final Set<String> readers;
private final Set<String> writers;
private final Optional<SecretSigningKey> entryWriterKey;
private AtomicBoolean modified = new AtomicBoolean(); // This only used as a guard against concurrent modifications
/**
*
* @param globalRoot This is only present for if this is the global root
* @param pointer
* @param ownername
* @param readers
* @param writers
* @param entryWriterKey
*/
public FileTreeNode(Optional<TrieNode> globalRoot, RetrievedFilePointer pointer, String ownername,
Set<String> readers, Set<String> writers, Optional<SecretSigningKey> entryWriterKey) {
this.globalRoot = globalRoot;
this.pointer = pointer == null ? null : pointer.withWriter(entryWriterKey);
this.ownername = ownername;
this.readers = readers;
this.writers = writers;
this.entryWriterKey = entryWriterKey;
if (pointer == null)
props = new FileProperties("/", "", 0, LocalDateTime.MIN, false, Optional.empty());
else {
SymmetricKey parentKey = this.getParentKey();
props = pointer.fileAccess.getProperties(parentKey);
}
thumbnail = new NativeJSThumbnail();
}
public FileTreeNode(RetrievedFilePointer pointer, String ownername,
Set<String> readers, Set<String> writers, Optional<SecretSigningKey> entryWriterKey) {
this(Optional.empty(), pointer, ownername, readers, writers, entryWriterKey);
}
public FileTreeNode withTrieNode(TrieNode trie) {
return new FileTreeNode(Optional.of(trie), pointer, ownername, readers, writers, entryWriterKey);
}
private FileTreeNode withCryptreeNode(CryptreeNode access) {
return new FileTreeNode(globalRoot, new RetrievedFilePointer(getPointer().filePointer, access), ownername,
readers, writers, entryWriterKey);
}
@JsMethod
public boolean equals(Object other) {
if (other == null)
return false;
if (!(other instanceof FileTreeNode))
return false;
return pointer.equals(((FileTreeNode)other).getPointer());
}
public RetrievedFilePointer getPointer() {
return pointer;
}
public boolean isRoot() {
return props.name.equals("/");
}
public CompletableFuture<String> getPath(NetworkAccess network) {
return retrieveParent(network).thenCompose(parent -> {
if (!parent.isPresent() || parent.get().isRoot())
return CompletableFuture.completedFuture("/" + props.name);
return parent.get().getPath(network).thenApply(parentPath -> parentPath + "/" + props.name);
});
}
public CompletableFuture<Optional<FileTreeNode>> getDescendentByPath(String path, NetworkAccess network) {
ensureUnmodified();
if (path.length() == 0)
return CompletableFuture.completedFuture(Optional.of(this));
if (path.equals("/"))
if (isDirectory())
return CompletableFuture.completedFuture(Optional.of(this));
else
return CompletableFuture.completedFuture(Optional.empty());
if (path.startsWith("/"))
path = path.substring(1);
int slash = path.indexOf("/");
String prefix = slash > 0 ? path.substring(0, slash) : path;
String suffix = slash > 0 ? path.substring(slash + 1) : "";
return getChildren(network).thenCompose(children -> {
for (FileTreeNode child : children)
if (child.getFileProperties().name.equals(prefix)) {
return child.getDescendentByPath(suffix, network);
}
return CompletableFuture.completedFuture(Optional.empty());
});
}
private void ensureUnmodified() {
if (modified.get())
throw new IllegalStateException("This file has already been modified, use the returned instance");
}
private void setModified() {
if (modified.get())
throw new IllegalStateException("This file has already been modified, use the returned instance");
modified.set(true);
}
/** Marks a file/directory and all its descendants as dirty. Directories are immediately cleaned,
* but files have all their keys except the actual data key cleaned. That is cleaned lazily, the next time it is modified
*
* @param network
* @param parent
* @param readersToRemove
* @return
* @throws IOException
*/
public CompletableFuture<FileTreeNode> makeDirty(NetworkAccess network, SafeRandom random,
FileTreeNode parent, Set<String> readersToRemove) {
if (!isWritable())
throw new IllegalStateException("You cannot mark a file as dirty without write access!");
if (isDirectory()) {
// create a new baseKey == subfoldersKey and make all descendants dirty
SymmetricKey newSubfoldersKey = SymmetricKey.random();
FilePointer ourNewPointer = pointer.filePointer.withBaseKey(newSubfoldersKey);
SymmetricKey newParentKey = SymmetricKey.random();
FileProperties props = getFileProperties();
DirAccess existing = (DirAccess) pointer.fileAccess;
// Create new DirAccess, but don't upload it
DirAccess newDirAccess = DirAccess.create(existing.committedHash(), newSubfoldersKey, props, parent.pointer.filePointer.getLocation(),
parent.getParentKey(), newParentKey);
// re add children
List<FilePointer> subdirs = existing.getSubfolders().stream().map(link ->
new FilePointer(link.targetLocation(pointer.filePointer.baseKey),
Optional.empty(), link.target(pointer.filePointer.baseKey))).collect(Collectors.toList());
return newDirAccess.addSubdirsAndCommit(subdirs, newSubfoldersKey, ourNewPointer, getSigner(), network, random)
.thenCompose(updatedDirAccess -> {
SymmetricKey filesKey = existing.getFilesKey(pointer.filePointer.baseKey);
List<FilePointer> files = existing.getFiles().stream()
.map(link -> new FilePointer(link.targetLocation(filesKey), Optional.empty(), link.target(filesKey)))
.collect(Collectors.toList());
return updatedDirAccess.addFilesAndCommit(files, newSubfoldersKey, ourNewPointer, getSigner(), network, random)
.thenCompose(fullyUpdatedDirAccess -> {
readers.removeAll(readersToRemove);
RetrievedFilePointer ourNewRetrievedPointer = new RetrievedFilePointer(ourNewPointer, fullyUpdatedDirAccess);
FileTreeNode theNewUs = new FileTreeNode(ourNewRetrievedPointer,
ownername, readers, writers, entryWriterKey);
// clean all subtree keys except file dataKeys (lazily re-key and re-encrypt them)
return getChildren(network).thenCompose(children -> {
for (FileTreeNode child : children) {
child.makeDirty(network, random, theNewUs, readersToRemove);
}
// update pointer from parent to us
return ((DirAccess) parent.pointer.fileAccess)
.updateChildLink(parent.pointer.filePointer, this.pointer,
ourNewRetrievedPointer, getSigner(), network, random)
.thenApply(x -> theNewUs);
});
});
}).thenApply(x -> {
setModified();
return x;
});
} else {
// create a new baseKey == parentKey and mark the metaDataKey as dirty
SymmetricKey parentKey = SymmetricKey.random();
return ((FileAccess) pointer.fileAccess).markDirty(writableFilePointer(), parentKey, network).thenCompose(newFileAccess -> {
// changing readers here will only affect the returned FileTreeNode, as the readers are derived from the entry point
TreeSet<String> newReaders = new TreeSet<>(readers);
newReaders.removeAll(readersToRemove);
RetrievedFilePointer newPointer = new RetrievedFilePointer(this.pointer.filePointer.withBaseKey(parentKey), newFileAccess);
// update link from parent folder to file to have new baseKey
return ((DirAccess) parent.pointer.fileAccess)
.updateChildLink(parent.writableFilePointer(), pointer, newPointer, getSigner(), network, random)
.thenApply(x -> new FileTreeNode(newPointer, ownername, newReaders, writers, entryWriterKey));
}).thenApply(x -> {
setModified();
return x;
});
}
}
public CompletableFuture<Boolean> hasChildWithName(String name, NetworkAccess network) {
ensureUnmodified();
return getChildren(network)
.thenApply(children -> children.stream().filter(c -> c.props.name.equals(name)).findAny().isPresent());
}
public CompletableFuture<FileTreeNode> removeChild(FileTreeNode child, NetworkAccess network) {
setModified();
return ((DirAccess)pointer.fileAccess)
.removeChild(child.getPointer(), pointer.filePointer, getSigner(), network)
.thenApply(updated -> new FileTreeNode(globalRoot,
new RetrievedFilePointer(getPointer().filePointer, updated), ownername, readers,
writers, entryWriterKey));
}
public CompletableFuture<FileTreeNode> addLinkTo(FileTreeNode file, NetworkAccess network, SafeRandom random) {
ensureUnmodified();
CompletableFuture<FileTreeNode> error = new CompletableFuture<>();
if (!this.isDirectory() || !this.isWritable()) {
error.completeExceptionally(new IllegalArgumentException("Can only add link toa writable directory!"));
return error;
}
String name = file.getFileProperties().name;
return hasChildWithName(name, network).thenCompose(hasChild -> {
if (hasChild) {
error.completeExceptionally(new IllegalStateException("Child already exists with name: " + name));
return error;
}
DirAccess toUpdate = (DirAccess) pointer.fileAccess;
return (file.isDirectory() ?
toUpdate.addSubdirAndCommit(file.pointer.filePointer, this.getKey(),
pointer.filePointer, getSigner(), network, random) :
toUpdate.addFileAndCommit(file.pointer.filePointer, this.getKey(),
pointer.filePointer, getSigner(), network, random))
.thenApply(dirAccess -> new FileTreeNode(this.pointer, ownername, readers, writers, entryWriterKey));
});
}
@JsMethod
public String toLink() {
return pointer.filePointer.toLink();
}
@JsMethod
public boolean isWritable() {
return entryWriterKey.isPresent();
}
@JsMethod
public boolean isReadable() {
try {
pointer.fileAccess.getMetaKey(pointer.filePointer.baseKey);
return false;
} catch (Exception e) {}
return true;
}
public SymmetricKey getKey() {
return pointer.filePointer.baseKey;
}
public Location getLocation() {
return pointer.filePointer.getLocation();
}
private SigningPrivateKeyAndPublicHash getSigner() {
if (! isWritable())
throw new IllegalStateException("Can only get a signer for a writable directory!");
return new SigningPrivateKeyAndPublicHash(getLocation().writer, entryWriterKey.get());
}
public Set<Location> getChildrenLocations() {
ensureUnmodified();
if (!this.isDirectory())
return Collections.emptySet();
return ((DirAccess)pointer.fileAccess).getChildrenLocations(pointer.filePointer.baseKey);
}
public CompletableFuture<Optional<FileTreeNode>> retrieveParent(NetworkAccess network) {
ensureUnmodified();
if (pointer == null)
return CompletableFuture.completedFuture(Optional.empty());
SymmetricKey parentKey = getParentKey();
CompletableFuture<RetrievedFilePointer> parent = pointer.fileAccess.getParent(parentKey, network);
return parent.thenApply(parentRFP -> {
if (parentRFP == null)
return Optional.empty();
return Optional.of(new FileTreeNode(parentRFP, ownername, Collections.emptySet(), Collections.emptySet(), entryWriterKey));
});
}
public SymmetricKey getParentKey() {
ensureUnmodified();
SymmetricKey parentKey = pointer.filePointer.baseKey;
if (this.isDirectory())
try {
parentKey = pointer.fileAccess.getParentKey(parentKey);
} catch (Exception e) {
// if we don't have read access to this folder, then we must just have the parent key already
}
return parentKey;
}
@JsMethod
public CompletableFuture<Set<FileTreeNode>> getChildren(NetworkAccess network) {
ensureUnmodified();
if (globalRoot.isPresent())
return globalRoot.get().getChildren("/", network);
if (isReadable()) {
return retrieveChildren(network).thenApply(childrenRFPs -> {
Set<FileTreeNode> newChildren = childrenRFPs.stream()
.map(x -> new FileTreeNode(x, ownername, readers, writers, entryWriterKey))
.collect(Collectors.toSet());
return newChildren.stream().collect(Collectors.toSet());
});
}
throw new IllegalStateException("Unreadable FileTreeNode!");
}
public CompletableFuture<Optional<FileTreeNode>> getChild(String name, NetworkAccess network) {
return getChildren(network)
.thenApply(children -> children.stream().filter(f -> f.getName().equals(name)).findAny());
}
private CompletableFuture<Set<RetrievedFilePointer>> retrieveChildren(NetworkAccess network) {
FilePointer filePointer = pointer.filePointer;
CryptreeNode fileAccess = pointer.fileAccess;
SymmetricKey rootDirKey = filePointer.baseKey;
if (isReadable())
return ((DirAccess) fileAccess).getChildren(network, rootDirKey);
throw new IllegalStateException("No credentials to retrieve children!");
}
public CompletableFuture<FileTreeNode> cleanUnreachableChildren(NetworkAccess network) {
setModified();
FilePointer filePointer = pointer.filePointer;
CryptreeNode fileAccess = pointer.fileAccess;
SymmetricKey rootDirKey = filePointer.baseKey;
if (isReadable())
return ((DirAccess) fileAccess).cleanUnreachableChildren(network, rootDirKey, filePointer, getSigner())
.thenApply(da -> new FileTreeNode(globalRoot,
new RetrievedFilePointer(filePointer, da), ownername, readers, writers, entryWriterKey));
throw new IllegalStateException("No credentials to retrieve children!");
}
@JsMethod
public String getOwner() {
return ownername;
}
@JsMethod
public boolean isDirectory() {
boolean isNull = pointer == null;
return isNull || pointer.fileAccess.isDirectory();
}
public boolean isDirty() {
ensureUnmodified();
return pointer.fileAccess.isDirty(pointer.filePointer.baseKey);
}
/**
*
* @param network
* @param random
* @param parent
* @param fragmenter
* @return updated parent dir
*/
public CompletableFuture<FileTreeNode> clean(NetworkAccess network, SafeRandom random,
FileTreeNode parent, peergos.shared.user.fs.Fragmenter fragmenter) {
if (!isDirty())
return CompletableFuture.completedFuture(this);
if (isDirectory()) {
throw new IllegalStateException("Directories are never dirty (they are cleaned immediately)!");
} else {
FileProperties props = getFileProperties();
SymmetricKey baseKey = pointer.filePointer.baseKey;
// stream download and re-encrypt with new metaKey
return getInputStream(network, random, l -> {}).thenCompose(in -> {
byte[] tmp = new byte[16];
new Random().nextBytes(tmp);
String tmpFilename = ArrayOps.bytesToHex(tmp) + ".tmp";
CompletableFuture<FileTreeNode> reuploaded = parent.uploadFileSection(tmpFilename, in, 0, props.size,
Optional.of(baseKey), network, random, l -> {}, fragmenter);
return reuploaded.thenCompose(upload -> upload.getDescendentByPath(tmpFilename, network)
.thenCompose(tmpChild -> tmpChild.get().rename(props.name, network, upload, true))
.thenApply(res -> {
setModified();
return res;
}));
});
}
}
@JsMethod
public CompletableFuture<FileTreeNode> uploadFileJS(String filename, AsyncReader fileData, int lengthHi, int lengthLow,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor, Fragmenter fragmenter) {
return uploadFile(filename, fileData, lengthLow + ((lengthHi & 0xFFFFFFFFL) << 32), network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFile(String filename, AsyncReader fileData, long length,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor, Fragmenter fragmenter) {
return uploadFileSection(filename, fileData, 0, length, Optional.empty(), network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFile(String filename,
AsyncReader fileData,
boolean isHidden,
long length,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor,
Fragmenter fragmenter) {
return uploadFileSection(filename, fileData, isHidden, 0, length, Optional.empty(), network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFileSection(String filename, AsyncReader fileData, long startIndex, long endIndex,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor, Fragmenter fragmenter) {
return uploadFileSection(filename, fileData, startIndex, endIndex, Optional.empty(), network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFileSection(String filename, AsyncReader fileData,
long startIndex, long endIndex,
Optional<SymmetricKey> baseKey,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor,
Fragmenter fragmenter) {
return uploadFileSection(filename, fileData, false, startIndex, endIndex, baseKey, network, random, monitor, fragmenter);
}
public CompletableFuture<FileTreeNode> uploadFileSection(String filename, AsyncReader fileData,
boolean isHidden,
long startIndex, long endIndex,
Optional<SymmetricKey> baseKey,
NetworkAccess network,
SafeRandom random,
ProgressConsumer<Long> monitor,
Fragmenter fragmenter) {
if (!isLegalName(filename)) {
CompletableFuture<FileTreeNode> res = new CompletableFuture<>();
res.completeExceptionally(new IllegalStateException("Illegal filename: " + filename));
return res;
}
if (! isDirectory()) {
CompletableFuture<FileTreeNode> res = new CompletableFuture<>();
res.completeExceptionally(new IllegalStateException("Cannot upload a sub file to a file!"));
return res;
}
return getDescendentByPath(filename, network).thenCompose(childOpt -> {
if (childOpt.isPresent()) {
return updateExistingChild(childOpt.get(), fileData, startIndex, endIndex, network, random, monitor, fragmenter);
}
if (startIndex > 0) {
// TODO if startIndex > 0 prepend with a zero section
throw new IllegalStateException("Unimplemented!");
}
SymmetricKey fileKey = baseKey.orElseGet(SymmetricKey::random);
SymmetricKey fileMetaKey = SymmetricKey.random();
SymmetricKey rootRKey = pointer.filePointer.baseKey;
DirAccess dirAccess = (DirAccess) pointer.fileAccess;
SymmetricKey dirParentKey = dirAccess.getParentKey(rootRKey);
Location parentLocation = getLocation();
int thumbnailSrcImageSize = startIndex == 0 && endIndex < Integer.MAX_VALUE ? (int)endIndex : 0;
boolean hasMime = thumbnailSrcImageSize > 0;
return generateThumbnail(network, fileData, thumbnailSrcImageSize, filename)
.thenCompose(thumbData -> fileData.reset()
.thenCompose(forMime -> (hasMime ? calculateMimeType(forMime) : CompletableFuture.completedFuture(""))
.thenCompose(mimeType -> fileData.reset().thenCompose(resetReader -> {
FileProperties fileProps = new FileProperties(filename, mimeType, endIndex,
LocalDateTime.now(), isHidden, Optional.of(thumbData));
FileUploader chunks = new FileUploader(filename, mimeType, resetReader,
startIndex, endIndex, fileKey, fileMetaKey, parentLocation, dirParentKey, monitor, fileProps,
fragmenter);
byte[] mapKey = random.randomBytes(32);
Location nextChunkLocation = new Location(getLocation().owner, getLocation().writer, mapKey);
return chunks.upload(network, random, parentLocation.owner, getSigner(), nextChunkLocation)
.thenCompose(fileLocation -> {
FilePointer filePointer = new FilePointer(fileLocation, Optional.empty(), fileKey);
return addChildPointer(filename, filePointer, network, random, 2);
});
}))
)
);
});
}
private CompletableFuture<FileTreeNode> addChildPointer(String filename,
FilePointer childPointer,
NetworkAccess network,
SafeRandom random,
int retries) {
CompletableFuture<FileTreeNode> result = new CompletableFuture<>();
((DirAccess) pointer.fileAccess).addFileAndCommit(childPointer, pointer.filePointer.baseKey, pointer.filePointer, getSigner(), network, random)
.thenAccept(uploadResult -> {
setModified();
result.complete(this.withCryptreeNode(uploadResult));
}).exceptionally(e -> {
if (e.getCause() instanceof Btree.CasException) {
// reload directory and try again
network.getMetadata(getLocation()).thenCompose(opt -> {
DirAccess updatedUs = (DirAccess) opt.get();
// Check another file of same name hasn't been added in the concurrent change
RetrievedFilePointer updatedPointer = new RetrievedFilePointer(pointer.filePointer, updatedUs);
FileTreeNode us = new FileTreeNode(globalRoot, updatedPointer, ownername, readers, writers, entryWriterKey);
return us.getChildren(network).thenCompose(children -> {
Set<String> childNames = children.stream()
.map(f -> f.getName())
.collect(Collectors.toSet());
String safeName = nextSafeReplacementFilename(filename, childNames);
// rename file in place as we've already uploaded it
return network.getMetadata(childPointer.location).thenCompose(renameOpt -> {
CryptreeNode fileToRename = renameOpt.get();
RetrievedFilePointer updatedChildPointer =
new RetrievedFilePointer(childPointer, fileToRename);
FileTreeNode toRename = new FileTreeNode(Optional.empty(),
updatedChildPointer, ownername, readers, writers, entryWriterKey);
return toRename.rename(safeName, network, us).thenCompose(usAgain ->
((DirAccess)usAgain.pointer.fileAccess)
.addFileAndCommit(childPointer, pointer.filePointer.baseKey,
pointer.filePointer, getSigner(), network, random)
.thenAccept(uploadResult -> {
setModified();
result.complete(this.withCryptreeNode(uploadResult));
}));
});
});
}).exceptionally(ex -> {
if (e.getCause() instanceof Btree.CasException && retries > 0)
addChildPointer(filename, childPointer, network, random, retries - 1)
.thenApply(f -> result.complete(f))
.exceptionally(e2 -> {
result.completeExceptionally(e2);
return null;
});
else
result.completeExceptionally(e);
return null;
});
} else
result.completeExceptionally(e);
return null;
});
return result;
}
private static String nextSafeReplacementFilename(String desired, Set<String> existing) {
if (! existing.contains(desired))
return desired;
for (int counter = 1; counter < 1000; counter++) {
int dot = desired.lastIndexOf(".");
String candidate = dot >= 0 ?
desired.substring(0, dot) + "[" + counter + "]" + desired.substring(dot) :
desired + "[" + counter + "]";
if (! existing.contains(candidate))
return candidate;
}
throw new IllegalStateException("Too many concurrent writes trying to add a file of the same name!");
}
private CompletableFuture<FileTreeNode> updateExistingChild(FileTreeNode existingChild, AsyncReader fileData,
long inputStartIndex, long endIndex,
NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor, Fragmenter fragmenter) {
String filename = existingChild.getFileProperties().name;
System.out.println("Overwriting section [" + Long.toHexString(inputStartIndex) + ", " + Long.toHexString(endIndex) + "] of child with name: " + filename);
Supplier<Location> locationSupplier = () -> new Location(getLocation().owner, getLocation().writer, random.randomBytes(32));
return (existingChild.isDirty() ?
existingChild.clean(network, random, this, fragmenter)
.thenCompose(us -> us.getChild(filename, network)
.thenApply(cleanedChild -> new Pair<>(us, cleanedChild.get()))) :
CompletableFuture.completedFuture(new Pair<>(this, existingChild))
).thenCompose(updatedPair -> {
FileTreeNode us = updatedPair.left;
FileTreeNode child = updatedPair.right;
FileProperties childProps = child.getFileProperties();
final AtomicLong filesSize = new AtomicLong(childProps.size);
FileRetriever retriever = child.getRetriever();
SymmetricKey baseKey = child.pointer.filePointer.baseKey;
FileAccess fileAccess = (FileAccess) child.pointer.fileAccess;
SymmetricKey dataKey = fileAccess.getDataKey(baseKey);
List<Long> startIndexes = new ArrayList<>();
for (long startIndex = inputStartIndex; startIndex < endIndex; startIndex = startIndex + Chunk.MAX_SIZE - (startIndex % Chunk.MAX_SIZE))
startIndexes.add(startIndex);
boolean identity = true;
BiFunction<Boolean, Long, CompletableFuture<Boolean>> composer = (id, startIndex) -> {
return retriever.getChunkInputStream(network, random, dataKey, startIndex, filesSize.get(),
child.getLocation(), child.pointer.fileAccess.committedHash(), monitor)
.thenCompose(currentLocation -> {
CompletableFuture<Optional<Location>> locationAt = retriever
.getLocationAt(child.getLocation(), startIndex + Chunk.MAX_SIZE, dataKey, network);
return locationAt.thenCompose(location ->
CompletableFuture.completedFuture(new Pair<>(currentLocation, location)));
}
).thenCompose(pair -> {
if (!pair.left.isPresent()) {
CompletableFuture<Boolean> result = new CompletableFuture<>();
result.completeExceptionally(new IllegalStateException("Current chunk not present"));
return result;
}
LocatedChunk currentOriginal = pair.left.get();
Optional<Location> nextChunkLocationOpt = pair.right;
Location nextChunkLocation = nextChunkLocationOpt.orElseGet(locationSupplier);
System.out.println("********** Writing to chunk at mapkey: " + ArrayOps.bytesToHex(currentOriginal.location.getMapKey()) + " next: " + nextChunkLocation);
// modify chunk, re-encrypt and upload
int internalStart = (int) (startIndex % Chunk.MAX_SIZE);
int internalEnd = endIndex - (startIndex - internalStart) > Chunk.MAX_SIZE ?
Chunk.MAX_SIZE : (int) (endIndex - (startIndex - internalStart));
byte[] rawData = currentOriginal.chunk.data();
// extend data array if necessary
if (rawData.length < internalEnd)
rawData = Arrays.copyOfRange(rawData, 0, internalEnd);
byte[] raw = rawData;
return fileData.readIntoArray(raw, internalStart, internalEnd - internalStart).thenCompose(read -> {
byte[] nonce = random.randomBytes(TweetNaCl.SECRETBOX_NONCE_BYTES);
Chunk updated = new Chunk(raw, dataKey, currentOriginal.location.getMapKey(), nonce);
LocatedChunk located = new LocatedChunk(currentOriginal.location, currentOriginal.existingHash, updated);
long currentSize = filesSize.get();
FileProperties newProps = new FileProperties(childProps.name, childProps.mimeType,
endIndex > currentSize ? endIndex : currentSize,
LocalDateTime.now(), childProps.isHidden, childProps.thumbnail);
CompletableFuture<Multihash> chunkUploaded = FileUploader.uploadChunk(getSigner(),
newProps, getLocation(), us.getParentKey(), baseKey, located,
fragmenter,
nextChunkLocation, network, monitor);
return chunkUploaded.thenCompose(isUploaded -> {
//update indices to be relative to next chunk
long updatedLength = startIndex + internalEnd - internalStart;
if (updatedLength > filesSize.get()) {
filesSize.set(updatedLength);
if (updatedLength > Chunk.MAX_SIZE) {
// update file size in FileProperties of first chunk
CompletableFuture<Boolean> updatedSize = getChildren(network).thenCompose(children -> {
Optional<FileTreeNode> updatedChild = children.stream()
.filter(f -> f.getFileProperties().name.equals(filename))
.findAny();
return updatedChild.get().setProperties(child.getFileProperties().withSize(endIndex), network, this);
});
}
}
return CompletableFuture.completedFuture(true);
});
});
});
};
BiFunction<Boolean, Boolean, Boolean> combiner = (left, right) -> left && right;
return Futures.reduceAll(startIndexes, identity, composer, combiner)
.thenApply(b -> us);
});
}
static boolean isLegalName(String name) {
return !name.contains("/");
}
@JsMethod
public CompletableFuture<FilePointer> mkdir(String newFolderName, NetworkAccess network, boolean isSystemFolder,
SafeRandom random) throws IOException {
return mkdir(newFolderName, network, null, isSystemFolder, random);
}
public CompletableFuture<FilePointer> mkdir(String newFolderName,
NetworkAccess network,
SymmetricKey requestedBaseSymmetricKey,
boolean isSystemFolder,
SafeRandom random) {
CompletableFuture<FilePointer> result = new CompletableFuture<>();
if (!this.isDirectory()) {
result.completeExceptionally(new IllegalStateException("Cannot mkdir in a file!"));
return result;
}
if (!isLegalName(newFolderName)) {
result.completeExceptionally(new IllegalStateException("Illegal directory name: " + newFolderName));
return result;
}
return hasChildWithName(newFolderName, network).thenCompose(hasChild -> {
if (hasChild) {
result.completeExceptionally(new IllegalStateException("Child already exists with name: " + newFolderName));
return result;
}
FilePointer dirPointer = pointer.filePointer;
DirAccess dirAccess = (DirAccess) pointer.fileAccess;
SymmetricKey rootDirKey = dirPointer.baseKey;
return dirAccess.mkdir(newFolderName, network, dirPointer.location.owner, getSigner(), dirPointer.getLocation().getMapKey(), rootDirKey,
requestedBaseSymmetricKey, isSystemFolder, random).thenApply(x -> {
setModified();
return x;
});
});
}
@JsMethod
public CompletableFuture<FileTreeNode> rename(String newFilename, NetworkAccess network, FileTreeNode parent) {
return rename(newFilename, network, parent, false);
}
/**
*
* @param newFilename
* @param network
* @param parent
* @param overwrite
* @return the updated parent
*/
public CompletableFuture<FileTreeNode> rename(String newFilename, NetworkAccess network,
FileTreeNode parent, boolean overwrite) {
setModified();
if (! isLegalName(newFilename))
return CompletableFuture.completedFuture(parent);
CompletableFuture<Optional<FileTreeNode>> childExists = parent == null ?
CompletableFuture.completedFuture(Optional.empty()) :
parent.getDescendentByPath(newFilename, network);
return childExists
.thenCompose(existing -> {
if (existing.isPresent() && !overwrite)
return CompletableFuture.completedFuture(parent);
return ((overwrite && existing.isPresent()) ?
existing.get().remove(network, parent) :
CompletableFuture.completedFuture(parent)
).thenCompose(res -> {
//get current props
FilePointer filePointer = pointer.filePointer;
SymmetricKey baseKey = filePointer.baseKey;
CryptreeNode fileAccess = pointer.fileAccess;
SymmetricKey key = this.isDirectory() ? fileAccess.getParentKey(baseKey) : baseKey;
FileProperties currentProps = fileAccess.getProperties(key);
FileProperties newProps = new FileProperties(newFilename, currentProps.mimeType, currentProps.size,
currentProps.modified, currentProps.isHidden, currentProps.thumbnail);
return fileAccess.updateProperties(writableFilePointer(), newProps, network)
.thenApply(fa -> res);
});
});
}
public CompletableFuture<Boolean> setProperties(FileProperties updatedProperties, NetworkAccess network, FileTreeNode parent) {
setModified();
String newName = updatedProperties.name;
CompletableFuture<Boolean> result = new CompletableFuture<>();
if (!isLegalName(newName)) {
result.completeExceptionally(new IllegalArgumentException("Illegal file name: " + newName));
return result;
}
return (parent == null ?
CompletableFuture.completedFuture(false) :
parent.hasChildWithName(newName, network))
.thenCompose(hasChild -> {
if (hasChild && parent!= null && !parent.getChildrenLocations().stream()
.map(l -> new ByteArrayWrapper(l.getMapKey()))
.collect(Collectors.toSet())
.contains(new ByteArrayWrapper(pointer.filePointer.getLocation().getMapKey()))) {
result.completeExceptionally(new IllegalStateException("Cannot rename to same name as an existing file"));
return result;
}
CryptreeNode fileAccess = pointer.fileAccess;
return fileAccess.updateProperties(writableFilePointer(), updatedProperties, network)
.thenApply(fa -> true);
});
}
private FilePointer writableFilePointer() {
FilePointer filePointer = pointer.filePointer;
SymmetricKey baseKey = filePointer.baseKey;
return new FilePointer(filePointer.location, entryWriterKey, baseKey);
}
public Optional<SecretSigningKey> getEntryWriterKey() {
return entryWriterKey;
}
@JsMethod
public CompletableFuture<FileTreeNode> copyTo(FileTreeNode target,
NetworkAccess network,
SafeRandom random,
Fragmenter fragmenter) {
ensureUnmodified();
CompletableFuture<FileTreeNode> result = new CompletableFuture<>();
if (! target.isDirectory()) {
result.completeExceptionally(new IllegalStateException("CopyTo target " + target + " must be a directory"));
return result;
}
return target.hasChildWithName(getFileProperties().name, network).thenCompose(childExists -> {
if (childExists) {
result.completeExceptionally(new IllegalStateException("CopyTo target " + target + " already has child with name " + getFileProperties().name));
return result;
}
boolean sameWriter = getLocation().writer.equals(target.getLocation().writer);
//make new FileTreeNode pointing to the same file if we are the same writer, but with a different location
if (sameWriter) {
byte[] newMapKey = new byte[32];
random.randombytes(newMapKey, 0, 32);
SymmetricKey ourBaseKey = this.getKey();
SymmetricKey newBaseKey = SymmetricKey.random();
FilePointer newRFP = new FilePointer(target.getLocation().owner, target.getLocation().writer, newMapKey, newBaseKey);
Location newParentLocation = target.getLocation();
SymmetricKey newParentParentKey = target.getParentKey();
return pointer.fileAccess.copyTo(ourBaseKey, newBaseKey, newParentLocation, newParentParentKey,
target.getLocation().writer, getSigner(), newMapKey, network, random)
.thenCompose(newAccess -> {
// upload new metadatablob
RetrievedFilePointer newRetrievedFilePointer = new RetrievedFilePointer(newRFP, newAccess);
FileTreeNode newFileTreeNode = new FileTreeNode(newRetrievedFilePointer, target.getOwner(),
Collections.emptySet(), Collections.emptySet(), target.getEntryWriterKey());
return target.addLinkTo(newFileTreeNode, network, random);
});
} else {
return getInputStream(network, random, x -> {})
.thenCompose(stream -> target.uploadFile(getName(), stream, getSize(), network, random, x -> {}, fragmenter)
.thenApply(b -> target));
}
});
}
/**
*
* @param network
* @param parent
* @return updated parent
*/
@JsMethod
public CompletableFuture<FileTreeNode> remove(NetworkAccess network, FileTreeNode parent) {
ensureUnmodified();
Supplier<CompletableFuture<Boolean>> supplier = () -> new RetrievedFilePointer(writableFilePointer(), pointer.fileAccess)
.remove(network, null, getSigner());
if (parent != null) {
return parent.removeChild(this, network)
.thenCompose(updated -> supplier.get()
.thenApply(x -> updated));
}
return supplier.get().thenApply(x -> parent);
}
public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network, SafeRandom random,
ProgressConsumer<Long> monitor) {
return getInputStream(network, random, getFileProperties().size, monitor);
}
@JsMethod
public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network,
SafeRandom random,
int fileSizeHi,
int fileSizeLow,
ProgressConsumer<Long> monitor) {
return getInputStream(network, random, fileSizeLow + ((fileSizeHi & 0xFFFFFFFFL) << 32), monitor);
}
public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network,
SafeRandom random,
long fileSize,
ProgressConsumer<Long> monitor) {
ensureUnmodified();
if (pointer.fileAccess.isDirectory())
throw new IllegalStateException("Cannot get input stream for a directory!");
FileAccess fileAccess = (FileAccess) pointer.fileAccess;
SymmetricKey baseKey = pointer.filePointer.baseKey;
SymmetricKey dataKey = fileAccess.getDataKey(baseKey);
return fileAccess.retriever().getFile(network, random, dataKey, fileSize, getLocation(), fileAccess.committedHash(), monitor);
}
private FileRetriever getRetriever() {
if (pointer.fileAccess.isDirectory())
throw new IllegalStateException("Cannot get input stream for a directory!");
FileAccess fileAccess = (FileAccess) pointer.fileAccess;
return fileAccess.retriever();
}
@JsMethod
public String getBase64Thumbnail() {
Optional<byte[]> thumbnail = props.thumbnail;
if(thumbnail.isPresent()){
String base64Data = Base64.getEncoder().encodeToString(thumbnail.get());
return "data:image/png;base64," + base64Data;
}else{
return "";
}
}
@JsMethod
public FileProperties getFileProperties() {
ensureUnmodified();
return props;
}
public String getName() {
return getFileProperties().name;
}
public long getSize() {
return getFileProperties().size;
}
public String toString() {
return getFileProperties().name;
}
public static FileTreeNode createRoot(TrieNode root) {
return new FileTreeNode(Optional.of(root), null, null, Collections.EMPTY_SET, Collections.EMPTY_SET, null);
}
public static byte[] generateThumbnail(byte[] imageBlob) {
try {
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBlob));
BufferedImage thumbnailImage = new BufferedImage(THUMBNAIL_SIZE, THUMBNAIL_SIZE, image.getType());
Graphics2D g = thumbnailImage.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(image, 0, 0, THUMBNAIL_SIZE, THUMBNAIL_SIZE, null);
g.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(thumbnailImage, "JPG", baos);
baos.close();
return baos.toByteArray();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return new byte[0];
}
private CompletableFuture<byte[]> generateThumbnail(NetworkAccess network, AsyncReader fileData, int fileSize, String filename)
{
CompletableFuture<byte[]> fut = new CompletableFuture<>();
if(fileSize > 0) {
isImage(fileData).thenAccept(isThumbnail -> {
if(isThumbnail) {
if(network.isJavascript()) {
thumbnail.generateThumbnail(fileData, fileSize, filename).thenAccept(base64Str -> {
byte[] bytesOfData = Base64.getDecoder().decode(base64Str);
fut.complete(bytesOfData);
});
} else {
byte[] bytes = new byte[fileSize];
fileData.readIntoArray(bytes, 0, fileSize).thenAccept(data -> {
fut.complete(generateThumbnail(bytes));
});
}
} else{
fut.complete(new byte[0]);
}
});
} else {
fut.complete(new byte[0]);
}
return fut;
}
private CompletableFuture<Boolean> isImage(AsyncReader imageBlob)
{
CompletableFuture<Boolean> result = new CompletableFuture<>();
byte[] data = new byte[HEADER_BYTES_TO_IDENTIFY_IMAGE_FILE];
imageBlob.readIntoArray(data, 0, HEADER_BYTES_TO_IDENTIFY_IMAGE_FILE).thenAccept(numBytesRead -> {
imageBlob.reset().thenAccept(resetResult -> {
if(numBytesRead < HEADER_BYTES_TO_IDENTIFY_IMAGE_FILE) {
result.complete(false);
}else {
byte[] tempBytes = Arrays.copyOfRange(data, 0, 2);
if (!compareArrayContents(Arrays.copyOfRange(data, 0, BMP.length), BMP)
&& !compareArrayContents(Arrays.copyOfRange(data, 0, GIF.length), GIF)
&& !compareArrayContents(Arrays.copyOfRange(data, 0, PNG.length), PNG)
&& !compareArrayContents(Arrays.copyOfRange(data, 0, 2), JPEG)) {
result.complete(false);
}else {
result.complete(true);
}
}
});
});
return result;
}
public static CompletableFuture<String> calculateMimeType(AsyncReader data) {
byte[] header = new byte[8];
return data.readIntoArray(header, 0, header.length)
.thenApply(read -> calculateMimeType(header));
}
public static final String calculateMimeType(byte[] start) {
if (compareArrayContents(Arrays.copyOfRange(start, 0, BMP.length), BMP))
return "image/bmp";
if (compareArrayContents(Arrays.copyOfRange(start, 0, GIF.length), GIF))
return "image/gif";
if (compareArrayContents(Arrays.copyOfRange(start, 0, PNG.length), PNG))
return "image/png";
if (compareArrayContents(Arrays.copyOfRange(start, 0, 2), JPEG))
return "image/jpg";
if (compareArrayContents(Arrays.copyOfRange(start, 4, 8), MP4))
return "video/mp4";
if (compareArrayContents(Arrays.copyOfRange(start, 0, 3), ID3))
return "audio/mpeg3";
if (compareArrayContents(Arrays.copyOfRange(start, 0, 3), MP3))
return "audio/mpeg3";
if (allAscii(start))
return "text/plain";
return "";
}
private static boolean allAscii(byte[] data) {
for (byte b : data) {
if ((b & 0xff) > 0x80)
return false;
if ((b & 0xff) < 0x20 && b != (byte)0x10 && b != (byte) 0x13)
return false;
}
return true;
}
private static boolean compareArrayContents(byte[] a, int[] a2) {
if (a==null || a2==null){
return false;
}
int length = a.length;
if (a2.length != length){
return false;
}
for (int i=0; i<length; i++) {
if ((a[i] & 0xff) != (a2[i] & 0xff)) {
return false;
}
}
return true;
}
}
|
package br.net.mirante.singular.showcase.view.page.form.crud.services;
import javax.inject.Inject;
import java.util.List;
import org.springframework.stereotype.Component;
import br.net.mirante.singular.form.mform.MILista;
import br.net.mirante.singular.form.mform.MInstancia;
import br.net.mirante.singular.form.mform.options.MOptionsProvider;
import br.net.mirante.singular.showcase.dao.form.ExampleFile;
import br.net.mirante.singular.showcase.dao.form.FileDao;
@SuppressWarnings("serial")
@Component("filesChoiceProvider")
public class MFileIdsOptionsProvider implements MOptionsProvider {
@Inject
private FileDao filePersistence;
/**
* Returns a MILista of the type of the field it will be used.
*
* @param optionsInstance : Current instance of the selection.
*/
@Override
// @destacar:bloco
public MILista<? extends MInstancia> listOptions(MInstancia optionsInstance) {
MILista<?> list;
if (optionsInstance instanceof MILista) {
list = ((MILista) optionsInstance).getTipoElementos().novaLista();
} else {
list = optionsInstance.getMTipo().novaLista();
}
files().forEach(f -> list.addValor(f.getId()));
return list;
}
// @destacar:fim
private List<ExampleFile> files() {
return filePersistence.list();
}
}
|
package org.drools.agent;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import org.drools.RuleBase;
import org.drools.RuleBaseConfiguration;
import org.drools.RuleBaseFactory;
import org.drools.RuntimeDroolsException;
import org.drools.rule.Package;
public class RuleAgent {
/**
* Following are property keys to be used in the property
* config file.
*/
public static final String NEW_INSTANCE = "newInstance";
public static final String FILES = "file";
public static final String DIRECTORY = "dir";
public static final String URLS = "url";
public static final String POLL_INTERVAL = "poll";
public static final String CONFIG_NAME = "name"; //name is optional
//this is needed for cold starting when BRMS is down (ie only for URL).
public static final String LOCAL_URL_CACHE = "localCacheDir";
/**
* Here is where we have a map of providers to the key that appears on the configuration.
*/
public static Map PACKAGE_PROVIDERS = new HashMap() {
{
put( FILES,
FileScanner.class );
put( DIRECTORY,
DirectoryScanner.class );
put ( URLS,
URLScanner.class );
}
};
/**
* This is true if the rulebase is created anew each time.
*/
private boolean newInstance;
/**
* The rule base that is being managed.
*/
private RuleBase ruleBase;
/**
* the configuration for the RuleBase
*/
private RuleBaseConfiguration ruleBaseConf;
/**
* The timer that is used to monitor for changes and deal with them.
*/
private Timer timer;
/**
* The providers that actually do the work.
*/
List providers;
/**
* This keeps the packages around that have been loaded.
*/
Map packages = new HashMap();
/**
* For logging events (important for stuff that happens in the background).
*/
AgentEventListener listener = getDefaultListener();
/**
* Polling interval value, in seconds, used in the Timer.
*/
private int secondsToRefresh;
/**
* Properties configured to load up packages into a rulebase (and monitor them
* for changes).
*/
public static RuleAgent newRuleAgent(Properties config) {
return newRuleAgent(config, null, null);
}
/**
* Properties configured to load up packages into a rulebase with the provided
* configuration (and monitor them for changes).
*/
public static RuleAgent newRuleAgent(Properties config, RuleBaseConfiguration ruleBaseConf) {
return newRuleAgent(config, null, ruleBaseConf);
}
/**
* This allows an optional listener to be passed in.
* The default one prints some stuff out to System.err only when really needed.
*/
public static RuleAgent newRuleAgent(Properties config, AgentEventListener listener) {
return newRuleAgent(config, listener, null);
}
/**
* This allows an optional listener to be passed in.
* The default one prints some stuff out to System.err only when really needed.
*/
public static RuleAgent newRuleAgent(Properties config, AgentEventListener listener, RuleBaseConfiguration ruleBaseConf) {
RuleAgent agent = new RuleAgent(ruleBaseConf);
if ( listener != null ) {
agent.listener = listener;
}
agent.init(config);
return agent;
}
void init(Properties config) {
boolean newInstance = Boolean.valueOf( config.getProperty( NEW_INSTANCE,
"false" ) ).booleanValue();
int secondsToRefresh = Integer.parseInt( config.getProperty( POLL_INTERVAL,
"-1" ) );
final String name = config.getProperty( CONFIG_NAME, "default" );
listener.setAgentName( name );
listener.info( "Configuring with newInstance=" + newInstance + ", secondsToRefresh="
+ secondsToRefresh);
List provs = new ArrayList();
for ( Iterator iter = config.keySet().iterator(); iter.hasNext(); ) {
String key = (String) iter.next();
PackageProvider prov = getProvider( key,
config );
if ( prov != null ) {
listener.info( "Configuring package provider : " + prov.toString() );
provs.add( prov );
}
}
configure( newInstance, provs,
secondsToRefresh );
}
/**
* Pass in the name and full path to a config file that is on the classpath.
*/
public static RuleAgent newRuleAgent(String propsFileName) {
return newRuleAgent( loadFromProperties( propsFileName ) );
}
/**
* Pass in the name and full path to a config file that is on the classpath.
*/
public static RuleAgent newRuleAgent(String propsFileName, RuleBaseConfiguration ruleBaseConfiguration) {
return newRuleAgent( loadFromProperties( propsFileName ), ruleBaseConfiguration );
}
/**
* This takes in an optional listener. Listener must not be null in this case.
*/
public static RuleAgent newRuleAgent(String propsFileName, AgentEventListener listener) {
return newRuleAgent( loadFromProperties( propsFileName ), listener );
}
/**
* This takes in an optional listener and RuleBaseConfiguration. Listener must not be null in this case.
*/
public static RuleAgent newRuleAgent(String propsFileName, AgentEventListener listener, RuleBaseConfiguration ruleBaseConfiguration) {
return newRuleAgent( loadFromProperties( propsFileName ), listener, ruleBaseConfiguration );
}
static Properties loadFromProperties(String propsFileName) {
InputStream in = RuleAgent.class.getResourceAsStream( propsFileName );
Properties props = new Properties();
try {
props.load( in );
return props;
} catch ( IOException e ) {
throw new RuntimeDroolsException( "Unable to load properties. Needs to be the path and name of a config file on your classpath.",
e );
}
}
/**
* Return a configured provider ready to go.
*/
private PackageProvider getProvider(String key,
Properties config) {
if ( !PACKAGE_PROVIDERS.containsKey( key ) ) {
return null;
}
Class clz = (Class) PACKAGE_PROVIDERS.get( key );
try {
PackageProvider prov = (PackageProvider) clz.newInstance( );
prov.setAgentListener( listener );
prov.configure( config );
return prov;
} catch ( InstantiationException e ) {
throw new RuntimeDroolsException( "Unable to load up a package provider for " + key,
e );
} catch ( IllegalAccessException e ) {
throw new RuntimeDroolsException( "Unable to load up a package provider for " + key,
e );
}
}
synchronized void configure(boolean newInstance,
List provs,
int secondsToRefresh) {
this.newInstance = newInstance;
this.providers = provs;
//run it the first time for each.
refreshRuleBase();
if ( secondsToRefresh != -1 ) {
startPolling( secondsToRefresh );
}
}
public void refreshRuleBase() {
List changedPackages = new ArrayList();
for ( Iterator iter = providers.iterator(); iter.hasNext(); ) {
PackageProvider prov = (PackageProvider) iter.next();
Package[] changes = checkForChanges( prov );
if (changes != null && changes.length > 0) {
changedPackages.addAll( Arrays.asList( changes ) );
}
}
if (changedPackages.size() > 0) {
listener.info( "Applying changes to the rulebase." );
//we have a change
if (this.newInstance) {
listener.info( "Creating a new rulebase as per settings." );
//blow away old
this.ruleBase = RuleBaseFactory.newRuleBase( this.ruleBaseConf );
//need to store ALL packages
for ( Iterator iter = changedPackages.iterator(); iter.hasNext(); ) {
Package element = (Package) iter.next();
this.packages.put( element.getName(), element ); //replace
}
//get packages from full name
PackageProvider.applyChanges( this.ruleBase, false, this.packages.values(), this.listener );
} else {
PackageProvider.applyChanges( this.ruleBase, true, changedPackages, this.listener );
}
}
}
private synchronized Package[] checkForChanges(PackageProvider prov) {
listener.debug( "SCANNING FOR CHANGE " + prov.toString() );
if (this.ruleBase == null) ruleBase = RuleBaseFactory.newRuleBase( this.ruleBaseConf );
Package[] changes = prov.loadPackageChanges();
return changes;
}
/**
* Convert a space seperated list into a List of stuff.
* If a filename or whatnot has a space in it, you can put double quotes around it
* and it will read it in as one token.
*/
static List list(String property) {
if ( property == null ) return Collections.EMPTY_LIST;
char[] cs = property.toCharArray();
boolean inquotes = false;
List items = new ArrayList();
String current = "";
for ( int i = 0; i < cs.length; i++ ) {
char c = cs[i];
switch ( c ) {
case '\"' :
if (inquotes) {
items.add( current );
current = "";
}
inquotes = !inquotes;
break;
default :
if (!inquotes &&
(c == ' ' || c == '\n' || c == '\r' || c == '\t')) {
if (current.trim() != "") {
items.add( current );
current = "";
}
} else {
current = current + c;
}
break;
}
}
if (current.trim() != "") {
items.add( current );
}
return items;
}
/**
* Return a current rulebase.
* Depending on the configuration, this may be a new object each time
* the rules are updated.
*
*/
public synchronized RuleBase getRuleBase() {
return this.ruleBase;
}
RuleAgent(RuleBaseConfiguration ruleBaseConf) {
if ( ruleBaseConf == null ) {
this.ruleBaseConf = new RuleBaseConfiguration();
} else {
this.ruleBaseConf = ruleBaseConf;
}
}
/**
* Stop the polling (if it is happening)
*/
public synchronized void stopPolling() {
if ( this.timer != null ) timer.cancel();
timer = null;
}
/**
* Will start polling. If polling is already running it does nothing.
*
*/
public synchronized void startPolling() {
if ( this.timer == null ) {
startPolling( this.secondsToRefresh );
}
}
/**
* Will start polling. If polling is already happening and of the same interval
* it will do nothing, if the interval is different it will stop the current Timer
* and create a new Timer for the new interval.
* @param secondsToRefresh
*/
public synchronized void startPolling(int secondsToRefresh) {
if ( this.timer != null ) {
if ( this.secondsToRefresh != secondsToRefresh ) {
stopPolling();
} else {
// do nothing.
return;
}
}
this.secondsToRefresh = secondsToRefresh;
int interval = this.secondsToRefresh * 1000;
//now schedule it for polling
timer = new Timer( true );
timer.schedule( new TimerTask() {
public void run() {
try {
listener.debug( "Checking for updates." );
refreshRuleBase();
} catch (Exception e) {
//don't want to stop execution here.
listener.exception( e );
}
}
},
interval,
interval );
}
boolean isNewInstance() {
return newInstance;
}
public synchronized boolean isPolling() {
return this.timer != null;
}
/**
* This should only be used once, on setup.
* @return
*/
private AgentEventListener getDefaultListener() {
return new AgentEventListener() {
private String name;
public String time() {
Date d = new Date();
return d.toString();
}
public void exception(Exception e) {
System.err.println("RuleAgent(" + name + ") EXCEPTION (" + time() + "): " + e.getMessage() + ". Stack trace should follow.");
e.printStackTrace( System.err );
}
public void info(String message) {
System.err.println("RuleAgent(" + name + ") INFO (" + time() + "): " + message);
}
public void warning(String message) {
System.err.println("RuleAgent(" + name + ") WARNING (" + time() + "): " + message);
}
public void debug(String message) {
//do nothing...
}
public void setAgentName(String name) {
this.name = name;
}
};
}
}
|
package org.geomesa.example.fsds;
import org.apache.commons.cli.ParseException;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.Path;
import org.geomesa.example.data.GDELTData;
import org.geomesa.example.data.TutorialData;
import org.geomesa.example.quickstart.GeoMesaQuickStart;
import org.geotools.data.DataStore;
import org.locationtech.geomesa.fs.FileSystemDataStore;
import org.locationtech.geomesa.fs.FileSystemDataStoreFactory;
import org.locationtech.geomesa.fs.storage.api.FileSystemStorage;
import org.locationtech.geomesa.fs.storage.api.PartitionScheme;
import org.locationtech.geomesa.fs.storage.interop.PartitionSchemeUtils;
import org.opengis.feature.simple.SimpleFeatureType;
import java.io.IOException;
import java.util.Collections;
public class FileSystemQuickStart extends GeoMesaQuickStart {
// use gdelt data
public FileSystemQuickStart(String[] args) throws ParseException {
super(args, new FileSystemDataStoreFactory().getParametersInfo(), new GDELTData());
}
@Override
public SimpleFeatureType getSimpleFeatureType(TutorialData data) {
SimpleFeatureType sft = super.getSimpleFeatureType(data);
// For the FSDS we need to modify the SimpleFeatureType to specify the index scheme
PartitionScheme scheme = PartitionSchemeUtils.apply(sft, "daily,z2-2bit", Collections.emptyMap());
PartitionSchemeUtils.addToSft(sft, scheme);
return sft;
}
public static void main(String[] args) {
try {
new FileSystemQuickStart(args).run();
} catch (ParseException e) {
System.exit(1);
} catch (Throwable e) {
e.printStackTrace();
System.exit(2);
}
System.exit(0);
}
@Override
public void cleanup(DataStore datastore, String typeName, boolean cleanup) {
if (datastore != null) {
try {
if (cleanup) {
FileSystemStorage fsStorage = ((FileSystemDataStore) datastore).storage(typeName);
Path fsPath = fsStorage.getMetadata().getRoot();
FileContext fc = fsStorage.getMetadata().getFileContext();
try {
System.out.println("Cleaning up test data");
fc.delete(fsPath, true);
} catch (IOException e) {
System.out.println("Unable to delete '" + fsPath.toString() + "':" + e.toString());
}
}
} catch (Exception e) {
System.out.println("Unable to cleanup datastore: " + e.toString());
} finally {
// make sure that we dispose of the datastore when we're done with it
datastore.dispose();
}
}
}
}
|
package org.eclipse.persistence.testing.tests.jpa21.advanced;
import static javax.persistence.ParameterMode.INOUT;
import static javax.persistence.ParameterMode.OUT;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.Query;
import javax.persistence.StoredProcedureParameter;
import javax.persistence.StoredProcedureQuery;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.jpa.JpaEntityManager;
import org.eclipse.persistence.queries.ResultSetMappingQuery;
import org.eclipse.persistence.queries.SQLCall;
import org.eclipse.persistence.testing.models.jpa21.advanced.Address;
import org.eclipse.persistence.testing.models.jpa21.advanced.AdvancedTableCreator;
import org.eclipse.persistence.testing.models.jpa21.advanced.EmployeeDetails;
import org.eclipse.persistence.testing.models.jpa21.advanced.EmployeePopulator;
import org.eclipse.persistence.testing.models.jpa21.advanced.LargeProject;
import org.eclipse.persistence.testing.models.jpa21.advanced.Project;
import org.eclipse.persistence.testing.models.jpa21.advanced.SmallProject;
import org.eclipse.persistence.testing.models.jpa21.advanced.Employee;
import org.eclipse.persistence.queries.ColumnResult;
import org.eclipse.persistence.queries.ConstructorResult;
import org.eclipse.persistence.queries.EntityResult;
import org.eclipse.persistence.queries.FieldResult;
import org.eclipse.persistence.queries.SQLResultSetMapping;
import org.eclipse.persistence.queries.StoredProcedureCall;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import junit.framework.TestSuite;
import junit.framework.Test;
public class NamedStoredProcedureQueryTestSuite extends JUnitTestCase {
protected boolean m_reset = false;
public NamedStoredProcedureQueryTestSuite() {}
public NamedStoredProcedureQueryTestSuite(String name) {
super(name);
}
public void setUp () {
m_reset = true;
super.setUp();
clearCache();
}
public void tearDown () {
if (m_reset) {
m_reset = false;
}
super.tearDown();
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("NamedStoredProcedureQueryTestSuite");
suite.addTest(new NamedStoredProcedureQueryTestSuite("testSetup"));
// These tests call stored procedures that return a result set.
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithMultipleResultsFromCode"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithMultipleResultsFromAnnotations"));
// These tests call stored procedures that write into OUT parameters.
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithResultClass"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithResultClassNamedFields"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithResultClassNumberedFields"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithResultSetFieldMapping"));
// These tests call stored procedures from EM API
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQueryWithPositionalParameters"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQueryWithAliasedColumns"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQueryWithResultClass"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQueryWithSqlResultSetMapping"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureUpdateQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureExecuteQuery1"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureExecuteQuery2"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testExecuteStoredProcedureQueryWithNamedCursors"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetResultListStoredProcedureQueryWithNamedCursors"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testExecuteStoredProcedureQueryWithUnNamedCursor"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testStoredProcedureQuerySysCursor"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetResultListOnUpdateQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetSingleResultOnUpdateQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetResultListOnDeleteQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetSingleResultOnDeleteQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testExecuteUpdateOnSelectQueryWithResultClass"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testExecuteUpdateOnSelectQueryWithNoResultClass"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testClassCastExceptionOnExecuteWithNoOutputParameters"));
return suite;
}
/**
* The setup is done as a test, both to record its failure, and to allow execution in the server.
*/
public void testSetup() {
new AdvancedTableCreator().replaceTables(JUnitTestCase.getServerSession());
EmployeePopulator employeePopulator = new EmployeePopulator();
employeePopulator.buildExamples();
employeePopulator.persistExample(getServerSession());
clearCache();
}
/**
* Tests a StoredProcedureQuery using only a procedure name though EM API
*/
public void testEMCreateStoredProcedureQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Edmonton");
address1.setPostalCode("T5B 4M9");
address1.setProvince("AB");
address1.setStreet("7424 118 Avenue");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address");
query.registerStoredProcedureParameter("address_id_v", Integer.class, ParameterMode.IN);
List addresses = query.setParameter("address_id_v", address1.getId()).getResultList();
assertTrue("Incorrect number of addresses returned", addresses.size() == 1);
Object[] addressContent = (Object[]) addresses.get(0);
assertTrue("Incorrect data content size", addressContent.length == 6);
assertTrue("Id content incorrect", addressContent[0].equals(new Long(address1.getId())));
assertTrue("Steet content incorrect", addressContent[1].equals(address1.getStreet()));
assertTrue("City content incorrect", addressContent[2].equals(address1.getCity()));
assertTrue("Country content incorrect", addressContent[3].equals(address1.getCountry()));
assertTrue("Province content incorrect", addressContent[4].equals(address1.getProvince()));
assertTrue("Postal Code content incorrect", addressContent[5].equals(address1.getPostalCode()));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-class.
*/
public void testEMCreateStoredProcedureQueryWithPositionalParameters() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K1G 6P3");
address1.setProvince("ON");
address1.setStreet("123 Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Address address2 = (Address) em.createNamedStoredProcedureQuery("ReadAddressMappedNumberedFieldResult").setParameter(1, address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-set-mapping using
* positional parameters (and more than the procedure expects).
*/
public void testEMCreateStoredProcedureQueryWithAliasedColumns() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K2J 0L7");
address1.setProvince("ON");
address1.setStreet("321 Main");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address_Mapped_Numbered", "address-field-result-map-numbered");
query.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN);
List<Address> addresses = query.setParameter(1, address1.getId()).getResultList();
assertTrue("Too many addresses returned", addresses.size() == 1);
Address address2 = addresses.get(0);
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a class though EM API
*/
public void testEMCreateStoredProcedureQueryWithResultClass() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Victoria");
address1.setPostalCode("V9A 6A9");
address1.setProvince("BC");
address1.setStreet("785 Lampson Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address", org.eclipse.persistence.testing.models.jpa21.advanced.Address.class);
query.registerStoredProcedureParameter("address_id_v", Integer.class, ParameterMode.IN);
Address address2 = (Address) query.setParameter("address_id_v", address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a result-set mapping though EM API
*/
public void testEMCreateStoredProcedureQueryWithSqlResultSetMapping() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address = new Address();
address.setCity("Winnipeg");
address.setPostalCode("R3B 1B9");
address.setProvince("MB");
address.setStreet("510 Main Street");
address.setCountry("Canada");
em.persist(address);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address_Mapped_Named", "address-column-result-map");
query.registerStoredProcedureParameter("address_id_v", String.class, ParameterMode.IN);
Object[] values = (Object[]) query.setParameter("address_id_v", address.getId()).getSingleResult();
assertTrue("Address data not found or returned using stored procedure", ((values != null) && (values.length == 6)));
assertNotNull("No results returned from store procedure call", values[1]);
assertTrue("Address not found using stored procedure", address.getStreet().equals(values[1]));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery that does an update though EM API
*/
public void testEMCreateStoredProcedureUpdateQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
String postalCodeTypo = "R3 1B9";
String postalCodeCorrection = "R3B 1B9";
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Winnipeg");
address1.setPostalCode(postalCodeTypo);
address1.setProvince("MB");
address1.setStreet("510 Main Street");
address1.setCountry("Canada");
em.persist(address1);
Address address2 = new Address();
address2.setCity("Winnipeg");
address2.setPostalCode(postalCodeTypo);
address2.setProvince("MB");
address2.setStreet("512 Main Street");
address2.setCountry("Canada");
em.persist(address2);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
beginTransaction(em);
int results = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).executeUpdate();
commitTransaction(em);
assertTrue("Update count incorrect.", results == 2);
// Just because we don't trust anyone ... :-)
Address a1 = em.find(Address.class, address1.getId());
assertTrue("The postal code was not updated for address 1.", a1.getPostalCode().equals(postalCodeCorrection));
Address a2 = em.find(Address.class, address2.getId());
assertTrue("The postal code was not updated for address 2.", a2.getPostalCode().equals(postalCodeCorrection));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery using multiple names cursors.
*/
public void testExecuteStoredProcedureQueryWithNamedCursors() {
if (supportsStoredProcedures() && getPlatform().isOracle() ) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createNamedStoredProcedureQuery("ReadUsingNamedRefCursors");
boolean returnVal = query.execute();
List<Employee> employees = (List<Employee>) query.getOutputParameterValue("CUR1");
assertFalse("No employees were returned", employees.isEmpty());
List<Address> addresses = (List<Address>) query.getOutputParameterValue("CUR2");
assertFalse("No addresses were returned", addresses.isEmpty());
assertFalse("The query had more results", query.hasMoreResults());
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery with an unnamed cursor.
*/
public void testExecuteStoredProcedureQueryWithUnNamedCursor() {
if (supportsStoredProcedures() && getPlatform().isOracle() ) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createNamedStoredProcedureQuery("ReadUsingUnNamedRefCursor");
boolean returnVal = query.execute();
List<Employee> employees = (List<Employee>) query.getOutputParameterValue(1);
assertFalse("No employees were returned", employees.isEmpty());
assertFalse("The query had more results", query.hasMoreResults());
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery on Oracle using named ref cursors.
*/
public void testGetResultListStoredProcedureQueryWithNamedCursors() {
if (supportsStoredProcedures() && getPlatform().isOracle() ) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createNamedStoredProcedureQuery("ReadUsingNamedRefCursors");
// Calling get result list here on an oracle platform will
// will return false for no result set was returned. Users
// should be calling execute and getting results from the out
// parameters.
try {
query.getResultList();
} catch (IllegalStateException ise) {
// We expect the exception here, now check through the output parameters (as expected)
List<Employee> employees = (List<Employee>) query.getOutputParameterValue("CUR1");
assertFalse("No employees were returned", employees.isEmpty());
List<Address> addresses = (List<Address>) query.getOutputParameterValue("CUR2");
assertFalse("No addresses were returned", addresses.isEmpty());
assertFalse("The query had more results", query.hasMoreResults());
return;
}
fail("No IllegalStateException thrown on getResultList() to an Oracle stored procedure using ref cursors");
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a system cursor.
*/
public void testStoredProcedureQuerySysCursor() {
if (supportsStoredProcedures() && getPlatform().isOracle() ) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Using_Sys_Cursor", Employee.class);
query.registerStoredProcedureParameter("p_recordset", void.class, ParameterMode.REF_CURSOR);
boolean execute = query.execute();
assertFalse("Execute should have returned false.", execute);
// TODO: investigate .. the name parameter "p_recordset" can't be looked up here, must use ordinal, why?
List<Employee> employees = (List<Employee>) query.getOutputParameterValue(1);
assertFalse("No employees were returned", employees.isEmpty());
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery that does an update though EM API
*/
public void testEMCreateStoredProcedureExecuteQuery1() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
// Create some data (with errors)
String postalCodeTypo = "K2J 0L8";
String postalCodeCorrection = "K2G 6W2";
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Winnipeg");
address1.setPostalCode(postalCodeTypo);
address1.setProvince("MB");
address1.setStreet("510 Main Street");
address1.setCountry("Canada");
em.persist(address1);
Address address2 = new Address();
address2.setCity("Winnipeg");
address2.setPostalCode(postalCodeTypo);
address2.setProvince("MB");
address2.setStreet("512 Main Street");
address2.setCountry("Canada");
em.persist(address2);
Address address3 = new Address();
address3.setCity("Winnipeg");
address3.setPostalCode(postalCodeCorrection);
address3.setProvince("MB");
address3.setStreet("514 Main Street");
address3.setCountry("Canada");
em.persist(address3);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
// Build the named stored procedure query, execute and test.
StoredProcedureQuery query = em.createStoredProcedureQuery("Result_Set_And_Update_Address", Address.class, Employee.class);
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("employee_count_v", Integer.class, ParameterMode.OUT);
boolean result = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).execute();
assertTrue("Result did not return true for a result set.", result);
List<Address> addressResults = query.getResultList();
assertTrue("The query didn't have any more results.", query.hasMoreResults());
List<Employee> employeeResults = query.getResultList();
int numberOfEmployes = employeeResults.size();
// Should return false (no more results)
assertFalse("The query had more results.", query.hasMoreResults());
// Get the update count.
int updateCount = query.getUpdateCount();
assertTrue("Update count incorrect: " + updateCount, updateCount == 2);
// Update count should return -1 now.
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
// Check output parameters by name.
Object outputParamValueFromName = query.getOutputParameterValue("employee_count_v");
assertNotNull("The output parameter was null.", outputParamValueFromName);
// TODO: to investigate. This little bit is hacky. For some
// reason MySql returns a Long here. By position is ok, that is,
// it returns an Integer (as we registered)
if (outputParamValueFromName instanceof Long) {
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName.equals(new Long(numberOfEmployes)));
} else if (outputParamValueFromName instanceof Byte) {
int value = ((Byte) outputParamValueFromName).intValue();
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + value, value == numberOfEmployes);
} else {
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName.equals(numberOfEmployes));
}
// Do some negative tests ...
try {
query.getOutputParameterValue(null);
fail("No IllegalArgumentException was caught with a null parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("emp_count");
fail("No IllegalArgumentException was caught with invalid parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("new_p_code_v");
fail("No IllegalArgumentException was caught with IN parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Check output parameters by position.
Integer outputParamValueFromPosition = (Integer) query.getOutputParameterValue(3);
assertNotNull("The output parameter was null.", outputParamValueFromPosition);
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromPosition, outputParamValueFromPosition.equals(numberOfEmployes));
// Do some negative tests ...
try {
query.getOutputParameterValue(8);
fail("No IllegalArgumentException was caught with position out of bounds.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue(1);
fail("No IllegalArgumentException was caught with an IN parameter position.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Just because we don't trust anyone ... :-)
Address a1 = em.find(Address.class, address1.getId());
assertTrue("The postal code was not updated for address 1.", a1.getPostalCode().equals(postalCodeCorrection));
Address a2 = em.find(Address.class, address2.getId());
assertTrue("The postal code was not updated for address 2.", a2.getPostalCode().equals(postalCodeCorrection));
Address a3 = em.find(Address.class, address3.getId());
assertTrue("The postal code was not updated for address 3.", a3.getPostalCode().equals(postalCodeCorrection));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
// The open statement/connection will be closed here.
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery that does an update though EM API
* This is the same test as above except different retrieval path.
*/
public void testEMCreateStoredProcedureExecuteQuery2() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
// Create some data (with errors)
String postalCodeTypo = "K2J 0L8";
String postalCodeCorrection = "K2G 6W2";
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Winnipeg");
address1.setPostalCode(postalCodeTypo);
address1.setProvince("MB");
address1.setStreet("510 Main Street");
address1.setCountry("Canada");
em.persist(address1);
Address address2 = new Address();
address2.setCity("Winnipeg");
address2.setPostalCode(postalCodeTypo);
address2.setProvince("MB");
address2.setStreet("512 Main Street");
address2.setCountry("Canada");
em.persist(address2);
Address address3 = new Address();
address3.setCity("Winnipeg");
address3.setPostalCode(postalCodeCorrection);
address3.setProvince("MB");
address3.setStreet("514 Main Street");
address3.setCountry("Canada");
em.persist(address3);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
// Build the named stored procedure query, execute and test.
StoredProcedureQuery query = em.createStoredProcedureQuery("Result_Set_And_Update_Address", Address.class, Employee.class);
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("employee_count_v", Integer.class, ParameterMode.OUT);
boolean result = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).execute();
assertTrue("Result did not return true for a result set.", result);
// This shouldn't affect where we are in the retrieval of the query.
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
List<Address> addressResults = query.getResultList();
// We know there should be more results so ask for them without checking for has more results.
List<Employee> employeeResults = query.getResultList();
int numberOfEmployes = employeeResults.size();
// Should return false (no more results)
assertFalse("The query had more results.", query.hasMoreResults());
assertFalse("The query had more results.", query.hasMoreResults());
assertFalse("The query had more results.", query.hasMoreResults());
assertFalse("The query had more results.", query.hasMoreResults());
assertNull("getResultList after no results did not return null", query.getResultList());
// Get the update count.
int updateCount = query.getUpdateCount();
assertTrue("Update count incorrect: " + updateCount, updateCount == 2);
// Update count should return -1 now.
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
// Check output parameters by name.
Object outputParamValueFromName = query.getOutputParameterValue("employee_count_v");
assertNotNull("The output parameter was null.", outputParamValueFromName);
// TODO: to investigate. This little bit is hacky. For some
// reason MySql returns a Long here. By position is ok, that is,
// it returns an Integer (as we registered)
if (outputParamValueFromName instanceof Long) {
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName.equals(new Long(numberOfEmployes)));
} else if (outputParamValueFromName instanceof Byte) {
int value = ((Byte) outputParamValueFromName).intValue();
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + value, value == numberOfEmployes);
} else {
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName.equals(numberOfEmployes));
}
// Do some negative tests ...
try {
query.getOutputParameterValue(null);
fail("No IllegalArgumentException was caught with a null parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("emp_count");
fail("No IllegalArgumentException was caught with invalid parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("new_p_code_v");
fail("No IllegalArgumentException was caught with IN parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Check output parameters by position.
Integer outputParamValueFromPosition = (Integer) query.getOutputParameterValue(3);
assertNotNull("The output parameter was null.", outputParamValueFromPosition);
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromPosition, outputParamValueFromPosition.equals(numberOfEmployes));
// Do some negative tests ...
try {
query.getOutputParameterValue(8);
fail("No IllegalArgumentException was caught with position out of bounds.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue(1);
fail("No IllegalArgumentException was caught with an IN parameter position.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Just because we don't trust anyone ... :-)
Address a1 = em.find(Address.class, address1.getId());
assertTrue("The postal code was not updated for address 1.", a1.getPostalCode().equals(postalCodeCorrection));
Address a2 = em.find(Address.class, address2.getId());
assertTrue("The postal code was not updated for address 2.", a2.getPostalCode().equals(postalCodeCorrection));
Address a3 = em.find(Address.class, address3.getId());
assertTrue("The postal code was not updated for address 3.", a3.getPostalCode().equals(postalCodeCorrection));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
// The open statement/connection will be closed here.
closeEntityManager(em);
}
}
}
/**
* Test multiple result sets by setting the SQL results set mapping from code.
*/
public void testQueryWithMultipleResultsFromCode() throws Exception {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
// SQL result set mapping for employee.
SQLResultSetMapping employeeResultSetMapping = new SQLResultSetMapping("EmployeeResultSetMapping");
employeeResultSetMapping.addResult(new EntityResult(Employee.class));
// SQL result set mapping for address.
SQLResultSetMapping addressResultSetMapping = new SQLResultSetMapping("AddressResultSetMapping");
addressResultSetMapping.addResult(new EntityResult(Address.class));
// SQL result set mapping for project (using inheritance and more complex result)
SQLResultSetMapping projectResultSetMapping = new SQLResultSetMapping("ProjectResultSetMapping");
EntityResult projectEntityResult = new EntityResult(Project.class);
projectResultSetMapping.addResult(projectEntityResult);
projectEntityResult = new EntityResult(SmallProject.class);
projectEntityResult.addFieldResult(new FieldResult("id", "SMALL_ID"));
projectEntityResult.addFieldResult(new FieldResult("name", "SMALL_NAME"));
projectEntityResult.addFieldResult(new FieldResult("description", "SMALL_DESCRIPTION"));
projectEntityResult.addFieldResult(new FieldResult("teamLeader", "SMALL_TEAMLEAD"));
projectEntityResult.addFieldResult(new FieldResult("version", "SMALL_VERSION"));
projectEntityResult.setDiscriminatorColumn("SMALL_DESCRIM");
projectResultSetMapping.addResult(projectEntityResult);
projectResultSetMapping.addResult(new ColumnResult("BUDGET_SUM"));
// SQL result set mapping for employee using constructor results.
SQLResultSetMapping employeeConstrustorResultSetMapping = new SQLResultSetMapping("EmployeeConstructorResultSetMapping");
ConstructorResult constructorResult = new ConstructorResult(EmployeeDetails.class);
ColumnResult columnResult = new ColumnResult("EMP_ID");
columnResult.getColumn().setType(Integer.class);
constructorResult.addColumnResult(columnResult);
columnResult = new ColumnResult("F_NAME");
columnResult.getColumn().setType(String.class);
constructorResult.addColumnResult(columnResult);
columnResult = new ColumnResult("L_NAME");
columnResult.getColumn().setType(String.class);
constructorResult.addColumnResult(columnResult);
columnResult = new ColumnResult("R_COUNT");
columnResult.getColumn().setType(Integer.class);
constructorResult.addColumnResult(columnResult);
employeeConstrustorResultSetMapping.addResult(constructorResult);
StoredProcedureCall call = new StoredProcedureCall();
call.setProcedureName("Read_Multiple_Result_Sets");
call.setHasMultipleResultSets(true);
call.setReturnMultipleResultSetCollections(true);
ResultSetMappingQuery query = new ResultSetMappingQuery(call);
query.addSQLResultSetMapping(employeeResultSetMapping);
query.addSQLResultSetMapping(addressResultSetMapping);
query.addSQLResultSetMapping(projectResultSetMapping);
query.addSQLResultSetMapping(employeeConstrustorResultSetMapping);
List allResults = (List)getServerSession().executeQuery(query);
assertNotNull("No results returned", allResults);
assertTrue("Incorrect number of results returned", allResults.size() == 4);
// Verify first result set mapping --> Employee
List results0 = (List) allResults.get(0);
assertNotNull("No Employee results returned", results0);
assertTrue("Empty Employee results returned", results0.size() > 0);
// Verify second result set mapping --> Address
List results1 = (List) allResults.get(1);
assertNotNull("No Address results returned", results1);
assertTrue("Empty Address results returned", results1.size() > 0);
// Verify third result set mapping --> Project
List results2 = (List) allResults.get(2);
assertNotNull("No Project results returned", results2);
assertTrue("Empty Project results returned", results2.size() > 0);
for (Object result2 : results2) {
Object[] result2Element = (Object[]) result2;
assertTrue("Failed to Return 3 items", (result2Element.length == 3));
// Using Number as Different db/drivers can return different types
// e.g. Oracle with ijdbc14.jar returns BigDecimal where as Derby
// with derbyclient.jar returns Double. NOTE: the order of checking
// here is valid and as defined by the spec.
assertTrue("Failed to return LargeProject", (result2Element[0] instanceof LargeProject));
assertTrue("Failed To Return SmallProject", (result2Element[1] instanceof SmallProject));
assertTrue("Failed to return column",(result2Element[2] instanceof Number));
assertFalse("Returned same data in both result elements",((SmallProject) result2Element[1]).getName().equals(((LargeProject) result2Element[0]).getName()));
}
// Verify fourth result set mapping --> Employee Constructor Result
List results3 = (List) allResults.get(3);
assertNotNull("No Employee constructor results returned", results3);
assertTrue("Empty Employee constructor results returned", results3.size() > 0);
}
}
/**
* Test multiple result sets by setting the SQL results set mapping from annotation.
*/
public void testQueryWithMultipleResultsFromAnnotations() throws Exception {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
StoredProcedureQuery multipleResultSetQuery = createEntityManager().createNamedStoredProcedureQuery("ReadUsingMultipleResultSetMappings");
// Verify first result set mapping --> Employee
List results = multipleResultSetQuery.getResultList();
assertNotNull("No Employee results returned", results);
assertTrue("Empty Employee results returned", results.size() > 0);
// Verify second result set mapping --> Address
assertTrue("Address results not available", multipleResultSetQuery.hasMoreResults());
results = multipleResultSetQuery.getResultList();
assertNotNull("No Address results returned", results);
assertTrue("Empty Address results returned", results.size() > 0);
// Verify third result set mapping --> Project
assertTrue("Projects results not available", multipleResultSetQuery.hasMoreResults());
results = multipleResultSetQuery.getResultList();
assertNotNull("No Project results returned", results);
assertTrue("Empty Project results returned", results.size() > 0);
for (Object result : results) {
Object[] resultElement = (Object[]) result;
assertTrue("Failed to Return 3 items", (resultElement.length == 3));
// Using Number as Different db/drivers can return different types
// e.g. Oracle with ijdbc14.jar returns BigDecimal where as Derby
// with derbyclient.jar returns Double. NOTE: the order of checking
// here is valid and as defined by the spec.
assertTrue("Failed to return LargeProject", (resultElement[0] instanceof LargeProject) );
assertTrue("Failed To Return SmallProject", (resultElement[1] instanceof SmallProject) );
assertTrue("Failed to return column",(resultElement[2] instanceof Number) );
assertFalse("Returned same data in both result elements",((SmallProject)resultElement[1]).getName().equals(((LargeProject)resultElement[0]).getName()));
}
// Verify fourth result set mapping --> Employee Constructor Result
assertTrue("Employee constructor results not available", multipleResultSetQuery.hasMoreResults());
results = multipleResultSetQuery.getResultList();
assertNotNull("No Employee constructor results returned", results);
assertTrue("Empty Employee constructor results returned", results.size() > 0);
// Verify there as no more results available
assertFalse("More results available", multipleResultSetQuery.hasMoreResults());
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-class.
*/
public void testQueryWithResultClass() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K1G 6P3");
address1.setProvince("ON");
address1.setStreet("123 Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Address address2 = (Address) em.createNamedStoredProcedureQuery("ReadAddressWithResultClass").setParameter("address_id_v", address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-set mapping.
*/
public void testQueryWithResultClassNamedFields() {
// TODO: investigate if this test should work on Oracle as written.
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K1G 6P3");
address1.setProvince("ON");
address1.setStreet("123 Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Address address2 = (Address) em.createNamedStoredProcedureQuery("ReadAddressMappedNamedFieldResult").setParameter("address_id_v", address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address not found using stored procedure", (address1.getId() == address2.getId()));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-class.
*/
public void testQueryWithResultClassNumberedFields() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K1G 6P3");
address1.setProvince("ON");
address1.setStreet("123 Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Address address2 = (Address) em.createNamedStoredProcedureQuery("ReadAddressMappedNumberedFieldResult").setParameter(1, address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery annotation using a result-set mapping.
*/
public void testQueryWithResultSetFieldMapping() {
// TODO: investigate if this test should work on Oracle as written.
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address = new Address();
address.setCity("Ottawa");
address.setPostalCode("K1G 6P3");
address.setProvince("ON");
address.setStreet("123 Street");
address.setCountry("Canada");
em.persist(address);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Object[] values = (Object[]) em.createNamedStoredProcedureQuery("ReadAddressMappedNamedColumnResult").setParameter("address_id_v", address.getId()).getSingleResult();
assertTrue("Address data not found or returned using stored procedure", ((values != null) && (values.length == 6)));
assertNotNull("No results returned from store procedure call", values[1]);
assertTrue("Address not found using stored procedure", address.getStreet().equals(values[1]));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Test an expected exception.
*/
public void testGetSingleResultOnDeleteQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
Object result = em.createStoredProcedureQuery("Delete_All_Responsibilities").getSingleResult();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Test an expected exception.
*/
public void testGetResultListOnDeleteQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
Object result = em.createStoredProcedureQuery("Delete_All_Responsibilities").getResultList();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Test an expected exception.
*/
public void testGetSingleResultOnUpdateQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
String postalCodeTypo = "R3 1B9";
String postalCodeCorrection = "R3B 1B9";
StoredProcedureQuery query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
Object results = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).getSingleResult();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Test an expected exception.
*/
public void testGetResultListOnUpdateQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
String postalCodeTypo = "R3 1B9";
String postalCodeCorrection = "R3B 1B9";
StoredProcedureQuery query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
Object results = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).getResultList();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Tests an execute update on a named stored procedure that does a select.
* NamedStoredProcedure defines a result class.
*/
public void testExecuteUpdateOnSelectQueryWithResultClass() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.createNamedStoredProcedureQuery("ReadAddressWithResultClass").setParameter("ADDRESS_ID", 1).executeUpdate();
commitTransaction(em);
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
return;
} finally {
closeEntityManager(em);
}
fail("Expected Illegal state exception was not thrown.");
}
}
/**
* Tests an execute update on a named stored procedure that does a select.
* NamedStoredProcedure defines a result class.
*/
public void testExecuteUpdateOnSelectQueryWithNoResultClass() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.createNamedStoredProcedureQuery("ReadAllAddressesWithNoResultClass").executeUpdate();
commitTransaction(em);
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
return;
} finally {
closeEntityManager(em);
}
fail("Expected Illegal state exception was not thrown.");
}
}
/**
* Test a class cast exception.
*/
public void testClassCastExceptionOnExecuteWithNoOutputParameters() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_All_Employees");
boolean returnValue = query.execute();
assertTrue("Execute didn't return true", returnValue);
List<Employee> employees = query.getResultList();
assertFalse("No employees were returned", employees.isEmpty());
} catch (ClassCastException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("ClassCastException caught" + e);
} finally {
closeEntityManager(em);
}
}
}
}
|
package cz.hobrasoft.pdfmu.sign;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.security.PdfPKCS7;
import cz.hobrasoft.pdfmu.Operation;
import cz.hobrasoft.pdfmu.OperationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
/**
* Displays signatures of a PDF document
*
* @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a>
*/
public class OperationSignatureDisplay implements Operation {
@Override
public String getCommandName() {
return "display";
}
@Override
public Subparser configureSubparser(Subparser subparser) {
String help = "Display signatures of a PDF document";
String metavarIn = "IN.pdf";
// Configure the subparser
subparser.help(help)
.description(help)
.defaultHelp(true)
.setDefault("command", this.getClass());
// Add arguments to the subparser
// Positional arguments are required by default
subparser.addArgument("in")
.help("input PDF document")
.metavar(metavarIn)
.type(Arguments.fileType().acceptSystemIn().verifyCanRead())
.required(true);
return subparser;
}
@Override
public void execute(Namespace namespace) throws OperationException {
// Input file
File inFile = namespace.get("in");
assert inFile != null; // Required argument
System.err.println(String.format("Input PDF document: %s", inFile));
display(inFile);
}
private static void display(File inFile) throws OperationException {
assert inFile != null;
System.err.println(String.format("Input PDF document: %s", inFile));
// Open the input stream
FileInputStream inStream;
try {
inStream = new FileInputStream(inFile);
} catch (FileNotFoundException ex) {
throw new OperationException("Input file not found.", ex);
}
display(inStream);
// Close the input stream
try {
inStream.close();
} catch (IOException ex) {
throw new OperationException("Could not close the input file.", ex);
}
}
private static void display(InputStream inStream) throws OperationException {
// Open the PDF reader
// PdfReader parses a PDF document.
PdfReader pdfReader;
try {
pdfReader = new PdfReader(inStream);
} catch (IOException ex) {
throw new OperationException("Could not open the input PDF document.", ex);
}
display(pdfReader);
// Close the PDF reader
pdfReader.close();
}
private static void display(PdfReader pdfReader) throws OperationException {
// digitalsignatures20130304.pdf : Code sample 5.1
AcroFields fields = pdfReader.getAcroFields();
display(fields);
}
private static void display(AcroFields fields) throws OperationException {
// digitalsignatures20130304.pdf : Code sample 5.1
ArrayList<String> names = fields.getSignatureNames();
// Print number of signatures
System.err.println(String.format("Number of signatures: %d", names.size()));
System.err.println(String.format("Number of document revisions: %d", fields.getTotalRevisions()));
for (String name : names) {
System.err.println(); // Separate singatures by an empty line
System.err.println(String.format("Signature field name: %s", name));
verifySignature(fields, name);
}
}
private static PdfPKCS7 verifySignature(AcroFields fields, String name) throws OperationException {
// digitalsignatures20130304.pdf : Code sample 5.2
System.err.println(String.format(" Signature covers the whole document: %b", fields.signatureCoversWholeDocument(name)));
System.err.println(String.format(" Document revision: %d of %d", fields.getRevision(name), fields.getTotalRevisions()));
PdfPKCS7 pkcs7 = fields.verifySignature(name);
try {
System.err.println(String.format(" Integrity check OK?: %b", pkcs7.verify()));
} catch (GeneralSecurityException ex) {
throw new OperationException(String.format("Could not verify signature %s.", name), ex);
}
return pkcs7;
}
}
|
package org.perl6.rakudo;
import java.util.*;
import org.perl6.nqp.runtime.*;
import org.perl6.nqp.sixmodel.*;
import org.perl6.nqp.sixmodel.reprs.ContextRefInstance;
import org.perl6.nqp.sixmodel.reprs.P6int;
import org.perl6.nqp.sixmodel.reprs.P6str;
import org.perl6.nqp.sixmodel.reprs.P6num;
import org.perl6.nqp.sixmodel.reprs.P6OpaqueREPRData;
@SuppressWarnings("unused")
public final class Binder {
/* Possible results of binding. */
public static final int BIND_RESULT_OK = 0;
public static final int BIND_RESULT_FAIL = 1;
public static final int BIND_RESULT_JUNCTION = 2;
/* Compile time trial binding result indicators. */
public static final int TRIAL_BIND_NOT_SURE = 0; /* Plausible, but need to check at runtime. */
public static final int TRIAL_BIND_OK = 1; /* Bind will always work out. */
public static final int TRIAL_BIND_NO_WAY = -1; /* Bind could never work out. */
/* Flags. */
private static final int SIG_ELEM_BIND_CAPTURE = 1;
private static final int SIG_ELEM_BIND_PRIVATE_ATTR = 2;
private static final int SIG_ELEM_BIND_PUBLIC_ATTR = 4;
private static final int SIG_ELEM_BIND_ATTRIBUTIVE = (SIG_ELEM_BIND_PRIVATE_ATTR | SIG_ELEM_BIND_PUBLIC_ATTR);
private static final int SIG_ELEM_SLURPY_POS = 8;
private static final int SIG_ELEM_SLURPY_NAMED = 16;
private static final int SIG_ELEM_SLURPY_LOL = 32;
private static final int SIG_ELEM_INVOCANT = 64;
private static final int SIG_ELEM_MULTI_INVOCANT = 128;
private static final int SIG_ELEM_IS_RW = 256;
private static final int SIG_ELEM_IS_COPY = 512;
private static final int SIG_ELEM_IS_RAW = 1024;
private static final int SIG_ELEM_IS_OPTIONAL = 2048;
private static final int SIG_ELEM_ARRAY_SIGIL = 4096;
private static final int SIG_ELEM_HASH_SIGIL = 8192;
private static final int SIG_ELEM_DEFAULT_FROM_OUTER = 16384;
private static final int SIG_ELEM_IS_CAPTURE = 32768;
private static final int SIG_ELEM_UNDEFINED_ONLY = 65536;
private static final int SIG_ELEM_DEFINED_ONLY = 131072;
private static final int SIG_ELEM_DEFINEDNES_CHECK = (SIG_ELEM_UNDEFINED_ONLY | SIG_ELEM_DEFINED_ONLY);
private static final int SIG_ELEM_NOMINAL_GENERIC = 524288;
private static final int SIG_ELEM_DEFAULT_IS_LITERAL = 1048576;
private static final int SIG_ELEM_NATIVE_INT_VALUE = 2097152;
private static final int SIG_ELEM_NATIVE_NUM_VALUE = 4194304;
private static final int SIG_ELEM_NATIVE_STR_VALUE = 8388608;
private static final int SIG_ELEM_NATIVE_VALUE = (SIG_ELEM_NATIVE_INT_VALUE | SIG_ELEM_NATIVE_NUM_VALUE | SIG_ELEM_NATIVE_STR_VALUE);
private static final int SIG_ELEM_SLURPY_ONEARG = 16777216;
private static final int SIG_ELEM_SLURPY = (SIG_ELEM_SLURPY_POS | SIG_ELEM_SLURPY_NAMED | SIG_ELEM_SLURPY_LOL | SIG_ELEM_SLURPY_ONEARG);
/* Hints for Parameter attributes. */
private static final int HINT_variable_name = 0;
private static final int HINT_named_names = 1;
private static final int HINT_type_captures = 2;
private static final int HINT_flags = 3;
private static final int HINT_nominal_type = 4;
private static final int HINT_post_constraints = 5;
private static final int HINT_coerce_type = 6;
private static final int HINT_coerce_method = 7;
private static final int HINT_sub_signature = 8;
private static final int HINT_default_value = 9;
private static final int HINT_container_descriptor = 10;
private static final int HINT_attr_package = 11;
/* Other hints. */
private static final int HINT_ENUMMAP_storage = 0;
private static final int HINT_CAPTURE_list = 0;
private static final int HINT_CAPTURE_hash = 1;
private static final int HINT_LIST_reified = 0;
private static final int HINT_SIG_params = 0;
private static SixModelObject createBox(ThreadContext tc, RakOps.GlobalExt gcx, Object arg, int flag) {
switch (flag) {
case CallSiteDescriptor.ARG_INT:
return Ops.box_i((long)arg, gcx.Int, tc);
case CallSiteDescriptor.ARG_NUM:
return Ops.box_n((double)arg, gcx.Num, tc);
case CallSiteDescriptor.ARG_STR:
return Ops.box_s((String)arg, gcx.Str, tc);
default:
throw new RuntimeException("Impossible case reached in createBox");
}
}
private static String arityFail(ThreadContext tc, RakOps.GlobalExt gcx, SixModelObject params,
int numParams, int numPosArgs, boolean tooMany) {
int arity = 0;
int count = 0;
String fail = tooMany ? "Too many" : "Too few";
/* Work out how many we could have been passed. */
for (int i = 0; i < numParams; i++) {
SixModelObject param = params.at_pos_boxed(tc, i);
param.get_attribute_native(tc, gcx.Parameter, "$!flags", HINT_flags);
int flags = (int)tc.native_i;
SixModelObject namedNames = param.get_attribute_boxed(tc,
gcx.Parameter, "@!named_names", HINT_named_names);
if (namedNames != null)
continue;
if ((flags & SIG_ELEM_SLURPY_NAMED) != 0)
continue;
if ((flags & SIG_ELEM_SLURPY) != 0) {
count = -1000; // cargo-culted from BOOTSTRAP.nqp: "in case a pos can sneak past a slurpy somehow"
}
else if ((flags & SIG_ELEM_IS_OPTIONAL) != 0) {
count++;
}
else {
count++;
arity++;
}
}
/* Now generate decent error. */
if (arity == count)
return String.format(
"%s positionals passed; expected %d arguments but got %d",
fail, arity, numPosArgs);
else if (count <= -1)
return String.format(
"%s positionals passed; expected at least %d arguments but got only %d",
fail, arity, numPosArgs);
else
return String.format(
"%s positionals passed; expected %d %s %d arguments but got %d",
fail, arity, arity + 1 == count ? "or" : "to" , count, numPosArgs);
}
/* Binds any type captures. */
public static void bindTypeCaptures(ThreadContext tc, SixModelObject typeCaps, CallFrame cf, SixModelObject type) {
long elems = typeCaps.elems(tc);
StaticCodeInfo sci = cf.codeRef.staticInfo;
for (long i = 0; i < elems; i++) {
typeCaps.at_pos_native(tc, i);
String name = tc.native_s;
cf.oLex[sci.oTryGetLexicalIdx(name)] = type;
}
}
/* Assigns an attributive parameter to the desired attribute. */
private static int assignAttributive(ThreadContext tc, CallFrame cf, String varName,
int paramFlags, SixModelObject attrPackage, SixModelObject value, Object[] error) {
/* Find self. */
StaticCodeInfo sci = cf.codeRef.staticInfo;
Integer selfIdx = sci.oTryGetLexicalIdx("self");
SixModelObject self = null;
if (selfIdx == null) {
self = Ops.getlexouter("self", tc);
if (self == null) {
if (error != null)
error[0] = String.format(
"Unable to bind attributive parameter '%s' - could not find self",
varName);
return BIND_RESULT_FAIL;
}
}
else {
self = cf.oLex[selfIdx];
}
/* If it's private, just need to fetch the attribute. */
SixModelObject assignee;
if ((paramFlags & SIG_ELEM_BIND_PRIVATE_ATTR) != 0) {
/* If we have a native Attribute we can't get a container for it, and
since *trying* to get a container would throw already, we first check
if the target Attribute is native. */
int hint = -1;
for (HashMap<String, Integer> map : ((P6OpaqueREPRData) (attrPackage.st.REPRData)).nameToHintMap) {
try {
hint = map.get(varName);
}
catch (Exception e) {
continue;
}
}
REPR attrREPR = null;
if (((P6OpaqueREPRData) (attrPackage.st.REPRData)).flattenedSTables[hint] != null) {
/* We sometimes don't have flattenedSTables. I'm not sure that's okay, honestly... */
attrREPR = ((P6OpaqueREPRData) (attrPackage.st.REPRData)).flattenedSTables[hint].REPR;
}
if (attrREPR instanceof P6int) {
Ops.bindattr_i(self, attrPackage, varName, Ops.unbox_i(value, tc), tc);
}
else if (attrREPR instanceof P6num) {
Ops.bindattr_n(self, attrPackage, varName, Ops.unbox_n(value, tc), tc);
}
else if (attrREPR instanceof P6str) {
Ops.bindattr_s(self, attrPackage, varName, Ops.unbox_s(value, tc), tc);
}
else {
/* ...but we'll just assume it's probably some boxed Attribute. */
assignee = self.get_attribute_boxed(tc, attrPackage, varName, STable.NO_HINT);
RakOps.p6store(assignee, value, tc);
}
}
/* Otherwise if it's public, do a method call to get the assignee. */
else {
throw new RuntimeException("$.x parameters NYI");
}
return BIND_RESULT_OK;
}
/* Returns an appropriate failure mode (junction fail or normal fail). */
private static int juncOrFail(ThreadContext tc, RakOps.GlobalExt gcx, SixModelObject value) {
if (value.st.WHAT == gcx.Junction && Ops.isconcrete(value, tc) != 0)
return BIND_RESULT_JUNCTION;
else
return BIND_RESULT_FAIL;
}
/* Binds a single argument into the lexpad, after doing any checks that are
* needed. Also handles any type captures. If there is a sub signature, then
* re-enters the binder. Returns one of the BIND_RESULT_* codes. */
private static final CallSiteDescriptor genIns = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null);
private static final CallSiteDescriptor ACCEPTS_o = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null);
private static final CallSiteDescriptor ACCEPTS_i = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_INT }, null);
private static final CallSiteDescriptor ACCEPTS_n = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_NUM }, null);
private static final CallSiteDescriptor ACCEPTS_s = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_STR }, null);
private static final CallSiteDescriptor bindParamThrower = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ,
CallSiteDescriptor.ARG_STR, CallSiteDescriptor.ARG_OBJ,
CallSiteDescriptor.ARG_INT
}, null);
private static final CallSiteDescriptor bindConcreteThrower = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_STR, CallSiteDescriptor.ARG_STR,
CallSiteDescriptor.ARG_STR, CallSiteDescriptor.ARG_STR,
CallSiteDescriptor.ARG_INT, CallSiteDescriptor.ARG_INT
}, null);
private static final CallSiteDescriptor paramReadWriteThrower = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_STR }, null);
private static int bindOneParam(ThreadContext tc, RakOps.GlobalExt gcx, CallFrame cf, SixModelObject param,
Object origArg, byte origFlag, boolean noNomTypeCheck, boolean isSlurpyNamed, Object[] error) {
/* Get parameter flags and variable name. */
param.get_attribute_native(tc, gcx.Parameter, "$!flags", HINT_flags);
int paramFlags = (int)tc.native_i;
param.get_attribute_native(tc, gcx.Parameter, "$!variable_name", HINT_variable_name);
String varName = tc.native_s;
boolean hasVarName = true;
if (varName == null || varName.isEmpty()) {
varName = "<anon>";
hasVarName = false;
}
if (RakOps.DEBUG_MODE)
System.err.println(varName);
/* We'll put the value to bind into one of the following locals, and
* flag will indicate what type of thing it is. */
int flag;
long arg_i = 0;
double arg_n = 0.0;
String arg_s = null;
SixModelObject arg_o = null;
/* Check if boxed/unboxed expectations are met. */
int desiredNative = paramFlags & SIG_ELEM_NATIVE_VALUE;
boolean is_rw = (paramFlags & SIG_ELEM_IS_RW) != 0;
int gotNative = origFlag & (CallSiteDescriptor.ARG_INT | CallSiteDescriptor.ARG_NUM | CallSiteDescriptor.ARG_STR);
if (is_rw && desiredNative != 0) {
switch (desiredNative) {
case SIG_ELEM_NATIVE_INT_VALUE:
if (gotNative != 0 || Ops.iscont_i((SixModelObject)origArg) == 0) {
if (error != null)
error[0] = String.format(
"Expected a modifiable native int argument for '%s'",
varName);
return BIND_RESULT_FAIL;
}
break;
case SIG_ELEM_NATIVE_NUM_VALUE:
if (gotNative != 0 || Ops.iscont_n((SixModelObject)origArg) == 0) {
if (error != null)
error[0] = String.format(
"Expected a modifiable native num argument for '%s'",
varName);
return BIND_RESULT_FAIL;
}
break;
case SIG_ELEM_NATIVE_STR_VALUE:
if (gotNative != 0 || Ops.iscont_s((SixModelObject)origArg) == 0) {
if (error != null)
error[0] = String.format(
"Expected a modifiable native str argument for '%s'",
varName);
return BIND_RESULT_FAIL;
}
break;
}
flag = CallSiteDescriptor.ARG_OBJ;
arg_o = (SixModelObject)origArg;
}
else if (desiredNative == 0 && gotNative == CallSiteDescriptor.ARG_OBJ) {
flag = gotNative;
arg_o = (SixModelObject)origArg;
}
else if (desiredNative == SIG_ELEM_NATIVE_INT_VALUE && gotNative == CallSiteDescriptor.ARG_INT) {
flag = gotNative;
arg_i = (long)origArg;
}
else if (desiredNative == SIG_ELEM_NATIVE_NUM_VALUE && gotNative == CallSiteDescriptor.ARG_NUM) {
flag = gotNative;
arg_n = (double)origArg;
}
else if (desiredNative == SIG_ELEM_NATIVE_STR_VALUE && gotNative == CallSiteDescriptor.ARG_STR) {
flag = gotNative;
arg_s = (String)origArg;
}
else if (desiredNative == 0) {
/* We need to do a boxing operation. */
flag = CallSiteDescriptor.ARG_OBJ;
arg_o = createBox(tc, gcx, origArg, gotNative);
}
else {
/* We need to do an unboxing opeation. */
SixModelObject decontValue = Ops.decont((SixModelObject)origArg, tc);
StorageSpec spec = decontValue.st.REPR.get_storage_spec(tc, decontValue.st);
switch (desiredNative) {
case SIG_ELEM_NATIVE_INT_VALUE:
if ((spec.can_box & StorageSpec.CAN_BOX_INT) != 0) {
flag = CallSiteDescriptor.ARG_INT;
arg_i = decontValue.get_int(tc);
}
else {
if (error != null)
error[0] = String.format(
"Cannot unbox argument to '%s' as a native int",
varName);
return BIND_RESULT_FAIL;
}
break;
case SIG_ELEM_NATIVE_NUM_VALUE:
if ((spec.can_box & StorageSpec.CAN_BOX_NUM) != 0) {
flag = CallSiteDescriptor.ARG_NUM;
arg_n = decontValue.get_num(tc);
}
else {
if (error != null)
error[0] = String.format(
"Cannot unbox argument to '%s' as a native num",
varName);
return BIND_RESULT_FAIL;
}
break;
case SIG_ELEM_NATIVE_STR_VALUE:
if ((spec.can_box & StorageSpec.CAN_BOX_STR) != 0) {
flag = CallSiteDescriptor.ARG_STR;
arg_s = decontValue.get_str(tc);
}
else {
if (error != null)
error[0] = String.format(
"Cannot unbox argument to '%s' as a native str",
varName);
return BIND_RESULT_FAIL;
}
break;
default:
if (error != null)
error[0] = String.format(
"Cannot unbox argument to '%s' as a native type",
varName);
return BIND_RESULT_FAIL;
}
}
/* By this point, we'll either have an object that we might be able to
* bind if it passes the type check, or a native value that needs no
* further checking. */
SixModelObject decontValue = null;
boolean didHLLTransform = false;
SixModelObject nomType = null;
SixModelObject ContextRef = null;
SixModelObject HOW = null;
if (flag == CallSiteDescriptor.ARG_OBJ && !(is_rw && desiredNative != 0)) {
/* We need to work on the decontainerized value. */
decontValue = Ops.decont(arg_o, tc);
/* HLL map it as needed. */
SixModelObject beforeHLLize = decontValue;
decontValue = Ops.hllize(decontValue, tc);
if (decontValue != beforeHLLize)
didHLLTransform = true;
/* Skip nominal type check if not needed. */
if (!noNomTypeCheck) {
/* Is the nominal type generic and in need of instantiation? (This
* can happen in (::T, T) where we didn't learn about the type until
* during the signature bind). */
nomType = param.get_attribute_boxed(tc, gcx.Parameter,
"$!nominal_type", HINT_nominal_type);
if ((paramFlags & SIG_ELEM_NOMINAL_GENERIC) != 0) {
HOW = nomType.st.HOW;
SixModelObject ig = Ops.findmethod(HOW,
"instantiate_generic", tc);
ContextRef = tc.gc.ContextRef;
SixModelObject cc = ContextRef.st.REPR.allocate(tc, ContextRef.st);
((ContextRefInstance)cc).context = cf;
Ops.invokeDirect(tc, ig, genIns,
new Object[] { HOW, nomType, cc });
nomType = Ops.result_o(tc.curFrame);
}
/* If the expected type is Positional, see if we need to do the
* positional bind failover. */
if (nomType == gcx.Positional) {
if (Ops.istype_nd(arg_o, gcx.PositionalBindFailover, tc) != 0) {
SixModelObject ig = Ops.findmethod(arg_o, "cache", tc);
Ops.invokeDirect(tc, ig, Ops.invocantCallSite, new Object[] { arg_o });
arg_o = Ops.result_o(tc.curFrame);
decontValue = Ops.decont(arg_o, tc);
}
else if (Ops.istype_nd(decontValue, gcx.PositionalBindFailover, tc) != 0) {
SixModelObject ig = Ops.findmethod(decontValue, "cache", tc);
Ops.invokeDirect(tc, ig, Ops.invocantCallSite, new Object[] { decontValue });
decontValue = Ops.result_o(tc.curFrame);
}
}
/* If not, do the check. If the wanted nominal type is Mu, then
* anything goes.
* When binding a slurpy named hash while compiling the setting don't check for Associative.
*/
if (nomType != gcx.Mu && !(isSlurpyNamed && nomType == gcx.Associative) && Ops.istype_nd(decontValue, nomType, tc) == 0) {
/* Type check failed; produce error if needed. */
if (error != null) {
SixModelObject thrower = RakOps.getThrower(tc, "X::TypeCheck::Binding::Parameter");
if (thrower != null) {
error[0] = thrower;
error[1] = bindParamThrower;
error[2] = new Object[] { decontValue, nomType.st.WHAT,
varName, param, (long)0 };
}
else {
error[0] = String.format(
"Nominal type check failed for parameter '%s'",
varName);
}
}
/* Report junction failure mode if it's a junction. */
return juncOrFail(tc, gcx, decontValue);
}
/* Also enforce definedness check */
if ( (paramFlags & SIG_ELEM_DEFINEDNES_CHECK) != 0) {
/* Don't check decontValue for concreteness though, but arg_o,
seeing as we don't have a isconcrete_nodecont */
Boolean shouldBeConcrete = (paramFlags & SIG_ELEM_DEFINED_ONLY) != 0 && Ops.isconcrete(arg_o, tc) != 1;
if (shouldBeConcrete || ((paramFlags & SIG_ELEM_UNDEFINED_ONLY) != 0 && Ops.isconcrete(arg_o, tc) == 1)) {
if (error != null) {
String typeName = Ops.typeName(param.get_attribute_boxed(tc,
gcx.Parameter, "$!nominal_type", HINT_nominal_type), tc);
String argName = Ops.typeName(arg_o, tc);
String methodName = cf.codeRef.name;
SixModelObject thrower = RakOps.getThrower(tc, "X::Parameter::InvalidConcreteness");
if (thrower != null) {
error[0] = thrower;
error[1] = bindConcreteThrower;
error[2] = new Object[] { typeName, argName, methodName,
varName, (long)(shouldBeConcrete ? 1 : 0),
(long)(paramFlags & SIG_ELEM_INVOCANT) };
}
else {
if (methodName == null || methodName.isEmpty())
methodName = "<anon>";
error[0] = ((paramFlags & SIG_ELEM_INVOCANT) != 0)
? shouldBeConcrete
? String.format(
"Invocant of method '%s' must be an object instance of type '%s', not a type object of type '%s'. Did you forget a '.new'?",
methodName, typeName, argName)
: String.format(
"Invocant of method '%s' must be a type object of type '%s', not an object instance of type '%s'. Did you forget a 'multi'?",
methodName, typeName, argName)
: shouldBeConcrete
? String.format(
"Parameter '%s' of routine '%s' must be an object instance of type '%s', not a type object of type '%s'. Did you forget a '.new'?",
varName, methodName, typeName, argName)
: String.format(
"Parameter '%s' of routine '%s' must be a type object of type '%s', not an object instance of type '%s'. Did you forget a 'multi'?",
varName, methodName, typeName, argName);
}
}
return juncOrFail(tc, gcx, decontValue);
}
}
}
}
/* Type captures. */
SixModelObject typeCaps = param.get_attribute_boxed(tc, gcx.Parameter,
"@!type_captures", HINT_type_captures);
if (typeCaps != null)
bindTypeCaptures(tc, typeCaps, cf, decontValue.st.WHAT);
/* Do a coercion, if one is needed. */
SixModelObject coerceType = param.get_attribute_boxed(tc, gcx.Parameter,
"$!coerce_type", HINT_coerce_type);
if (coerceType != null) {
/* Coercing natives not possible - nothing to call a method on. */
if (flag != CallSiteDescriptor.ARG_OBJ) {
if (error != null)
error[0] = String.format(
"Unable to coerce natively typed parameter '%s'",
varName);
return BIND_RESULT_FAIL;
}
/* Is the coercion target generic and in need of instantiation?
* (This can happen in (::T, T) where we didn't learn about the
* type until during the signature bind.) */
param.get_attribute_native(tc, gcx.Parameter, "$!coerce_method", HINT_coerce_method);
String methName = tc.native_s;
HOW = coerceType.st.HOW;
SixModelObject archetypesMeth = Ops.findmethod(HOW, "archetypes", tc);
Ops.invokeDirect(tc, archetypesMeth, Ops.invocantCallSite, new Object[] { HOW });
SixModelObject Archetypes = Ops.result_o(tc.curFrame);
SixModelObject genericMeth = Ops.findmethod(Archetypes, "generic", tc);
Ops.invokeDirect(tc, genericMeth, Ops.invocantCallSite, new Object[] { Archetypes });
if (Ops.istrue(Ops.result_o(tc.curFrame), tc) == 1) {
ContextRef = tc.gc.ContextRef;
SixModelObject ctcc = ContextRef.st.REPR.allocate(tc, ContextRef.st);
((ContextRefInstance)ctcc).context = cf;
SixModelObject ctig = Ops.findmethod(HOW, "instantiate_generic", tc);
Ops.invokeDirect(tc, ctig, genIns, new Object[] { HOW, coerceType, ctcc });
coerceType = Ops.result_o(tc.curFrame);
methName = Ops.typeName(coerceType, tc);
}
/* Only coerce if we don't already have the correct type. */
if (Ops.istype(decontValue, coerceType, tc) == 0) {
SixModelObject coerceMeth = Ops.findmethodNonFatal(decontValue, methName, tc);
if (coerceMeth != null) {
Ops.invokeDirect(tc, coerceMeth,
Ops.invocantCallSite,
new Object[] { decontValue });
arg_o = Ops.result_o(tc.curFrame);
decontValue = Ops.decont(arg_o, tc);
}
else {
if (error != null)
error[0] = String.format(
"Unable to coerce value for '%s' to %s; no coercion method defined",
varName, methName);
return BIND_RESULT_FAIL;
}
}
}
/* If it's not got attributive binding, we'll go about binding it into the
* lex pad. */
StaticCodeInfo sci = cf.codeRef.staticInfo;
if ((paramFlags & SIG_ELEM_BIND_ATTRIBUTIVE) == 0) {
/* Is it native? If so, just go ahead and bind it. */
if (flag != CallSiteDescriptor.ARG_OBJ) {
if (hasVarName) {
switch (flag) {
case CallSiteDescriptor.ARG_INT:
cf.iLex[sci.iTryGetLexicalIdx(varName)] = arg_i;
break;
case CallSiteDescriptor.ARG_NUM:
cf.nLex[sci.nTryGetLexicalIdx(varName)] = arg_n;
break;
case CallSiteDescriptor.ARG_STR:
cf.sLex[sci.sTryGetLexicalIdx(varName)] = arg_s;
break;
}
}
}
/* Otherwise it's some objecty case. */
else if (is_rw) {
if (Ops.isrwcont(arg_o, tc) == 1) {
if (hasVarName)
cf.oLex[sci.oTryGetLexicalIdx(varName)] = arg_o;
} else {
SixModelObject thrower = RakOps.getThrower(tc, "X::Parameter::RW");
if (thrower == null) {
error[0] = "Parameter expected a writable container";
} else {
error[0] = thrower;
error[1] = paramReadWriteThrower;
error[2] = new Object[] { decontValue, varName};
}
return BIND_RESULT_FAIL;
}
}
else if (hasVarName) {
if ((paramFlags & SIG_ELEM_IS_RAW) != 0) {
/* Just bind the thing as is into the lexpad. */
cf.oLex[sci.oTryGetLexicalIdx(varName)] = didHLLTransform ? decontValue : arg_o;
}
else {
/* If it's an array, copy means make a new one and store,
* and a normal bind is a straightforward binding plus
* adding a constraint. */
if ((paramFlags & SIG_ELEM_ARRAY_SIGIL) != 0) {
SixModelObject bindee = decontValue;
if ((paramFlags & SIG_ELEM_IS_COPY) != 0) {
SixModelObject BOOTArray = tc.gc.BOOTArray;
bindee = gcx.Array.st.REPR.allocate(tc, gcx.Array.st);
bindee.bind_attribute_boxed(tc, gcx.List, "$!reified",
HINT_LIST_reified, BOOTArray.st.REPR.allocate(tc, BOOTArray.st));
RakOps.p6store(bindee, decontValue, tc);
}
cf.oLex[sci.oTryGetLexicalIdx(varName)] = bindee;
}
/* If it's a hash, similar approach to array. */
else if ((paramFlags & SIG_ELEM_HASH_SIGIL) != 0) {
SixModelObject bindee = decontValue;
if ((paramFlags & SIG_ELEM_IS_COPY) != 0) {
SixModelObject BOOTHash = tc.gc.BOOTHash;
bindee = gcx.Hash.st.REPR.allocate(tc, gcx.Hash.st);
bindee.bind_attribute_boxed(tc, gcx.Map, "$!storage",
HINT_ENUMMAP_storage, BOOTHash.st.REPR.allocate(tc, BOOTHash.st));
RakOps.p6store(bindee, decontValue, tc);
}
cf.oLex[sci.oTryGetLexicalIdx(varName)] = bindee;
}
/* If it's a scalar, we always need to wrap it into a new
* container and store it, for copy or ro case (the rw bit
* in the container descriptor takes care of the rest). */
else {
boolean wrap = (paramFlags & SIG_ELEM_IS_COPY) != 0;
if (!wrap && nomType != null && gcx.Iterable != null) {
wrap = Ops.istype(gcx.Iterable, nomType, tc) != 0
|| Ops.istype(nomType, gcx.Iterable, tc) != 0;
}
if (wrap || varName.equals("$_")) {
STable stScalar = gcx.Scalar.st;
SixModelObject new_cont = stScalar.REPR.allocate(tc, stScalar);
SixModelObject desc = param.get_attribute_boxed(tc, gcx.Parameter,
"$!container_descriptor", HINT_container_descriptor);
new_cont.bind_attribute_boxed(tc, gcx.Scalar, "$!descriptor",
RakudoContainerSpec.HINT_descriptor, desc);
new_cont.bind_attribute_boxed(tc, gcx.Scalar, "$!value",
RakudoContainerSpec.HINT_value, decontValue);
cf.oLex[sci.oTryGetLexicalIdx(varName)] = new_cont;
}
else {
cf.oLex[sci.oTryGetLexicalIdx(varName)] = decontValue;
}
}
}
}
}
/* Is it the invocant? If so, also have to bind to self lexical. */
if ((paramFlags & SIG_ELEM_INVOCANT) != 0)
cf.oLex[sci.oTryGetLexicalIdx("self")] = decontValue;
/* Handle any constraint types (note that they may refer to the parameter by
* name, so we need to have bound it already). */
SixModelObject postConstraints = param.get_attribute_boxed(tc, gcx.Parameter,
"$!post_contraints", HINT_post_constraints);
if (postConstraints != null) {
long numConstraints = postConstraints.elems(tc);
for (long i = 0; i < numConstraints; i++) {
/* Check we meet the constraint. */
SixModelObject consType = postConstraints.at_pos_boxed(tc, i);
SixModelObject acceptsMeth = Ops.findmethod(consType, "ACCEPTS", tc);
if (Ops.isconcrete(consType, tc) == 1 && Ops.istype(consType, gcx.Code, tc) != 0)
RakOps.p6capturelex(consType, tc);
switch (flag) {
case CallSiteDescriptor.ARG_INT:
Ops.invokeDirect(tc, acceptsMeth,
ACCEPTS_i, new Object[] { consType, arg_i });
break;
case CallSiteDescriptor.ARG_NUM:
Ops.invokeDirect(tc, acceptsMeth,
ACCEPTS_n, new Object[] { consType, arg_n });
break;
case CallSiteDescriptor.ARG_STR:
Ops.invokeDirect(tc, acceptsMeth,
ACCEPTS_s, new Object[] { consType, arg_s });
break;
default:
Ops.invokeDirect(tc, acceptsMeth,
ACCEPTS_o, new Object[] { consType, arg_o });
break;
}
if (Ops.istrue(Ops.result_o(tc.curFrame), tc) == 0) {
/* Constraint type check failed; produce error if needed. */
if (error != null) {
SixModelObject thrower = RakOps.getThrower(tc, "X::TypeCheck::Binding::Parameter");
if (thrower != null) {
error[0] = thrower;
error[1] = bindParamThrower;
error[2] = new Object[] { (SixModelObject)origArg,
consType.st.WHAT, varName, param, (long)1 };
}
else {
error[0] = String.format(
"Constraint type check failed for parameter '%s'",
varName);
}
}
return BIND_RESULT_FAIL;
}
}
}
/* TODO: attributives. */
if ((paramFlags & SIG_ELEM_BIND_ATTRIBUTIVE) != 0) {
if (flag != CallSiteDescriptor.ARG_OBJ) {
if (error != null)
error[0] = "Native attributive binding not yet implemented";
return BIND_RESULT_FAIL;
}
int result = assignAttributive(tc, cf, varName, paramFlags,
param.get_attribute_boxed(tc, gcx.Parameter, "$!attr_package", HINT_attr_package),
decontValue, error);
if (result != BIND_RESULT_OK)
return result;
}
/* If it has a sub-signature, bind that. */
SixModelObject subSignature = param.get_attribute_boxed(tc, gcx.Parameter,
"$!sub_signature", HINT_sub_signature);
if (subSignature != null && flag == CallSiteDescriptor.ARG_OBJ) {
/* Turn value into a capture, unless we already have one. */
SixModelObject capture = null;
int result;
if ((paramFlags & SIG_ELEM_IS_CAPTURE) != 0) {
capture = decontValue;
}
else {
SixModelObject meth = Ops.findmethodNonFatal(decontValue, "Capture", tc);
if (meth == null) {
if (error != null)
error[0] = "Could not turn argument into capture";
return BIND_RESULT_FAIL;
}
Ops.invokeDirect(tc, meth, Ops.invocantCallSite, new Object[] { decontValue });
capture = Ops.result_o(tc.curFrame);
}
SixModelObject subParams = subSignature
.get_attribute_boxed(tc, gcx.Signature, "@!params", HINT_SIG_params);
/* Recurse into signature binder. */
CallSiteDescriptor subCsd = explodeCapture(tc, gcx, capture);
result = bind(tc, gcx, cf, subParams, subCsd, tc.flatArgs, noNomTypeCheck, error);
if (result != BIND_RESULT_OK)
{
if (error != null) {
/* Note in the error message that we're in a sub-signature. */
error[0] += " in sub-signature";
/* Have we a variable name? */
if (varName != null) {
error[0] += " of parameter " + varName;
}
}
return result;
}
}
if (RakOps.DEBUG_MODE)
System.err.println("bindOneParam NYFI");
return BIND_RESULT_OK;
}
private static final CallSiteDescriptor exploder = new CallSiteDescriptor(new byte[] {
CallSiteDescriptor.ARG_OBJ | CallSiteDescriptor.ARG_FLAT,
CallSiteDescriptor.ARG_OBJ | CallSiteDescriptor.ARG_FLAT | CallSiteDescriptor.ARG_NAMED
}, null);
public static CallSiteDescriptor explodeCapture(ThreadContext tc, RakOps.GlobalExt gcx, SixModelObject capture) {
capture = Ops.decont(capture, tc);
SixModelObject capType = gcx.Capture;
SixModelObject list = capture.get_attribute_boxed(tc, capType, "@!list", HINT_CAPTURE_list);
SixModelObject hash = capture.get_attribute_boxed(tc, capType, "%!hash", HINT_CAPTURE_hash);
if (list == null)
list = gcx.EMPTYARR;
if (hash == null)
hash = gcx.EMPTYHASH;
return exploder.explodeFlattening(tc.curFrame, new Object[] { list, hash });
}
/* This takes a signature element and either runs the closure to get a default
* value if there is one, or creates an appropriate undefined-ish thingy. */
private static SixModelObject handleOptional(ThreadContext tc, RakOps.GlobalExt gcx, int flags, SixModelObject param, CallFrame cf) {
/* Is the "get default from outer" flag set? */
if ((flags & SIG_ELEM_DEFAULT_FROM_OUTER) != 0) {
param.get_attribute_native(tc, gcx.Parameter, "$!variable_name", HINT_variable_name);
String varName = tc.native_s;
CallFrame curOuter = cf.outer;
while (curOuter != null) {
Integer idx = curOuter.codeRef.staticInfo.oTryGetLexicalIdx(varName);
if (idx != null)
return curOuter.oLex[idx];
curOuter = curOuter.outer;
}
return null;
}
/* Do we have a default value or value closure? */
SixModelObject defaultValue = param.get_attribute_boxed(tc, gcx.Parameter,
"$!default_value", HINT_default_value);
if (defaultValue != null) {
if ((flags & SIG_ELEM_DEFAULT_IS_LITERAL) != 0) {
return defaultValue;
}
else {
/* Thunk; run it to get a value. */
Ops.invokeArgless(tc, defaultValue);
return Ops.result_o(tc.curFrame);
}
}
/* Otherwise, go by sigil to pick the correct default type of value. */
else {
if ((flags & SIG_ELEM_ARRAY_SIGIL) != 0) {
SixModelObject res = gcx.Array.st.REPR.allocate(tc, gcx.Array.st);
return res;
}
else if ((flags & SIG_ELEM_HASH_SIGIL) != 0) {
SixModelObject res = gcx.Hash.st.REPR.allocate(tc, gcx.Hash.st);
return res;
}
else {
return param.get_attribute_boxed(tc, gcx.Parameter, "$!nominal_type", HINT_nominal_type);
}
}
}
/* Takes a signature along with positional and named arguments and binds them
* into the provided callframe. Returns BIND_RESULT_OK if binding works out,
* BIND_RESULT_FAIL if there is a failure and BIND_RESULT_JUNCTION if the
* failure was because of a Junction being passed (meaning we need to auto-thread). */
private static final CallSiteDescriptor slurpyFromArgs = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null);
public static int bind(ThreadContext tc, RakOps.GlobalExt gcx, CallFrame cf, SixModelObject params,
CallSiteDescriptor csd, Object[] args,
boolean noNomTypeCheck, Object[] error) {
int bindFail = BIND_RESULT_OK;
int curPosArg = 0;
/* If we have a |$foo that's followed by slurpies, then we can suppress
* any future arity checks. */
boolean suppressArityFail = false;
/* If we do have some named args, we want to make a clone of the hash
* to work on. We'll delete stuff from it as we bind, and what we have
* left over can become the slurpy hash or - if we aren't meant to be
* taking one - tell us we have a problem. */
HashMap<String, Integer> namedArgsCopy = csd.nameMap == null
? null
: new HashMap<String, Integer>(csd.nameMap);
/* Now we'll walk through the signature and go about binding things. */
int numPosArgs = csd.numPositionals;
long numParams = params.elems(tc);
for (long i = 0; i < numParams; i++) {
/* Get parameter, its flags and any named names. */
SixModelObject param = params.at_pos_boxed(tc, i);
param.get_attribute_native(tc, gcx.Parameter, "$!flags", HINT_flags);
int flags = (int)tc.native_i;
SixModelObject namedNames = param.get_attribute_boxed(tc,
gcx.Parameter, "@!named_names", HINT_named_names);
/* Is it looking for us to bind a capture here? */
if ((flags & SIG_ELEM_IS_CAPTURE) != 0) {
/* Capture the arguments from this point forwards into a Capture.
* Of course, if there's no variable name we can (cheaply) do pretty
* much nothing. */
param.get_attribute_native(tc, gcx.Parameter, "$!variable_name", HINT_variable_name);
if (tc.native_s == null) {
bindFail = BIND_RESULT_OK;
}
else {
SixModelObject posArgs = gcx.EMPTYARR.clone(tc);
for (int k = curPosArg; k < numPosArgs; k++) {
switch (csd.argFlags[k]) {
case CallSiteDescriptor.ARG_OBJ:
posArgs.push_boxed(tc, (SixModelObject)args[k]);
break;
case CallSiteDescriptor.ARG_INT:
posArgs.push_boxed(tc, RakOps.p6box_i((long)args[k], tc));
break;
case CallSiteDescriptor.ARG_NUM:
posArgs.push_boxed(tc, RakOps.p6box_n((double)args[k], tc));
break;
case CallSiteDescriptor.ARG_STR:
posArgs.push_boxed(tc, RakOps.p6box_s((String)args[k], tc));
break;
}
}
SixModelObject namedArgs = vmHashOfRemainingNameds(tc, gcx, namedArgsCopy, args);
SixModelObject capType = gcx.Capture;
SixModelObject capSnap = capType.st.REPR.allocate(tc, capType.st);
capSnap.bind_attribute_boxed(tc, capType, "@!list", HINT_CAPTURE_list, posArgs);
capSnap.bind_attribute_boxed(tc, capType, "%!hash", HINT_CAPTURE_hash, namedArgs);
bindFail = bindOneParam(tc, gcx, cf, param, capSnap, CallSiteDescriptor.ARG_OBJ,
noNomTypeCheck, false, error);
}
if (bindFail != 0) {
return bindFail;
}
else if (i + 1 == numParams) {
/* Since a capture acts as "the ultimate slurpy" in a sense, if
* this is the last parameter in the signature we can return
* success right off the bat. */
return BIND_RESULT_OK;
}
else {
SixModelObject nextParam = params.at_pos_boxed(tc, i + 1);
nextParam.get_attribute_native(tc, gcx.Parameter, "$!flags", HINT_flags);
if (((int)tc.native_i & (SIG_ELEM_SLURPY_POS | SIG_ELEM_SLURPY_NAMED)) != 0)
suppressArityFail = true;
}
}
/* Could it be a named slurpy? */
else if ((flags & SIG_ELEM_SLURPY_NAMED) != 0) {
SixModelObject slurpy = vmHashOfRemainingNameds(tc, gcx, namedArgsCopy, args);
SixModelObject bindee = gcx.Hash.st.REPR.allocate(tc, gcx.Hash.st);
bindee.bind_attribute_boxed(tc, gcx.Map, "$!storage",
HINT_ENUMMAP_storage, slurpy);
bindFail = bindOneParam(tc, gcx, cf, param, bindee, CallSiteDescriptor.ARG_OBJ,
noNomTypeCheck, true, error);
if (bindFail != 0)
return bindFail;
/* Nullify named arguments hash now we've consumed it, to mark all
* is well. */
namedArgsCopy = null;
}
/* Otherwise, maybe it's a positional of some kind. */
else if (namedNames == null) {
/* Slurpy or LoL-slurpy? */
if ((flags & (SIG_ELEM_SLURPY_POS | SIG_ELEM_SLURPY_LOL | SIG_ELEM_SLURPY_ONEARG)) != 0) {
/* Create Perl 6 array, create VM array of all remaining things,
* then store it. */
SixModelObject slurpy = gcx.EMPTYARR.clone(tc);
while (curPosArg < numPosArgs) {
switch (csd.argFlags[curPosArg]) {
case CallSiteDescriptor.ARG_OBJ:
slurpy.push_boxed(tc, (SixModelObject)args[curPosArg]);
break;
case CallSiteDescriptor.ARG_INT:
slurpy.push_boxed(tc, RakOps.p6box_i((long)args[curPosArg], tc));
break;
case CallSiteDescriptor.ARG_NUM:
slurpy.push_boxed(tc, RakOps.p6box_n((double)args[curPosArg], tc));
break;
case CallSiteDescriptor.ARG_STR:
slurpy.push_boxed(tc, RakOps.p6box_s((String)args[curPosArg], tc));
break;
}
curPosArg++;
}
SixModelObject slurpyType = (flags & SIG_ELEM_IS_RAW) != 0 ? gcx.List : gcx.Array;
SixModelObject sm = Ops.findmethod(slurpyType,
(flags & SIG_ELEM_SLURPY_ONEARG) != 0 ? "from-slurpy-onearg" :
(flags & SIG_ELEM_SLURPY_POS) != 0 ? "from-slurpy-flat" : "from-slurpy",
tc);
Ops.invokeDirect(tc, sm, slurpyFromArgs, new Object[] { slurpyType, slurpy });
SixModelObject bindee = Ops.result_o(tc.curFrame);
bindFail = bindOneParam(tc, gcx, cf, param, bindee, CallSiteDescriptor.ARG_OBJ,
noNomTypeCheck, false, error);
if (bindFail != 0)
return bindFail;
}
/* Otherwise, a positional. */
else {
/* Do we have a value?. */
if (curPosArg < numPosArgs) {
/* Easy - just bind that. */
bindFail = bindOneParam(tc, gcx, cf, param, args[curPosArg],
csd.argFlags[curPosArg], noNomTypeCheck, false, error);
if (bindFail != 0)
return bindFail;
curPosArg++;
}
else {
/* No value. If it's optional, fetch a default and bind that;
* if not, we're screwed. Note that we never nominal type check
* an optional with no value passed. */
if ((flags & SIG_ELEM_IS_OPTIONAL) != 0) {
bindFail = bindOneParam(tc, gcx, cf, param,
handleOptional(tc, gcx, flags, param, cf),
CallSiteDescriptor.ARG_OBJ, false, false, error);
if (bindFail != 0)
return bindFail;
}
else {
if (error != null)
error[0] = arityFail(tc, gcx, params, (int)numParams, numPosArgs, false);
return BIND_RESULT_FAIL;
}
}
}
}
/* Else, it's a non-slurpy named. */
else {
/* Try and get hold of value. */
Integer lookup = null;
if (namedArgsCopy != null) {
long numNames = namedNames.elems(tc);
for (long j = 0; j < numNames; j++) {
namedNames.at_pos_native(tc, j);
String name = tc.native_s;
lookup = namedArgsCopy.remove(name);
if (lookup != null)
break;
}
}
/* Did we get one? */
if (lookup == null) {
/* Nope. We'd better hope this param was optional... */
if ((flags & SIG_ELEM_IS_OPTIONAL) != 0) {
bindFail = bindOneParam(tc, gcx, cf, param,
handleOptional(tc, gcx, flags, param, cf),
CallSiteDescriptor.ARG_OBJ, false, false, error);
}
else if (!suppressArityFail) {
if (error != null) {
namedNames.at_pos_native(tc, 0);
error[0] = "Required named argument '" +
tc.native_s +
"' not passed";
}
return BIND_RESULT_FAIL;
}
}
else {
bindFail = bindOneParam(tc, gcx, cf, param, args[lookup >> 3],
(byte)(lookup & 7), noNomTypeCheck, false, error);
}
/* If we got a binding failure, return it. */
if (bindFail != 0)
return bindFail;
}
}
/* Do we have any left-over args? */
if (curPosArg < numPosArgs && !suppressArityFail) {
/* Oh noes, too many positionals passed. */
if (error != null)
error[0] = arityFail(tc, gcx, params, (int)numParams, numPosArgs, true);
return BIND_RESULT_FAIL;
}
if (namedArgsCopy != null && namedArgsCopy.size() > 0) {
/* Oh noes, unexpected named args. */
if (error != null) {
int numExtra = namedArgsCopy.size();
if (numExtra == 1) {
for (String name : namedArgsCopy.keySet())
error[0] = "Unexpected named argument '" + name + "' passed";
}
else {
boolean first = true;
error[0] = numExtra + " unexpected named arguments passed (";
for (String name : namedArgsCopy.keySet()) {
if (!first)
error[0] += ", ";
else
first = false;
error[0] += name;
}
error[0] += ")";
}
}
return BIND_RESULT_FAIL;
}
/* If we get here, we're done. */
return BIND_RESULT_OK;
}
/* Takes any nameds we didn't capture yet and makes a VM Hash of them. */
private static SixModelObject vmHashOfRemainingNameds(ThreadContext tc, RakOps.GlobalExt gcx, HashMap<String, Integer> namedArgsCopy, Object[] args) {
SixModelObject slurpy = gcx.Mu;
if (namedArgsCopy != null) {
SixModelObject BOOTHash = tc.gc.BOOTHash;
slurpy = BOOTHash.st.REPR.allocate(tc, BOOTHash.st);
for (String name : namedArgsCopy.keySet()) {
int lookup = namedArgsCopy.get(name);
switch (lookup & 7) {
case CallSiteDescriptor.ARG_OBJ:
slurpy.bind_key_boxed(tc, name, (SixModelObject)args[lookup >> 3]);
break;
case CallSiteDescriptor.ARG_INT:
slurpy.bind_key_boxed(tc, name, RakOps.p6box_i((long)args[lookup >> 3], tc));
break;
case CallSiteDescriptor.ARG_NUM:
slurpy.bind_key_boxed(tc, name, RakOps.p6box_n((double)args[lookup >> 3], tc));
break;
case CallSiteDescriptor.ARG_STR:
slurpy.bind_key_boxed(tc, name, RakOps.p6box_s((String)args[lookup >> 3], tc));
break;
}
}
}
return slurpy;
}
}
|
package org.gluu.persist.impl;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.codec.binary.Base64;
import org.gluu.persist.PersistenceEntryManager;
import org.gluu.persist.annotation.AttributeEnum;
import org.gluu.persist.annotation.AttributeName;
import org.gluu.persist.annotation.AttributesList;
import org.gluu.persist.annotation.CustomObjectClass;
import org.gluu.persist.annotation.DN;
import org.gluu.persist.annotation.DataEntry;
import org.gluu.persist.annotation.JsonObject;
import org.gluu.persist.annotation.ObjectClass;
import org.gluu.persist.annotation.SchemaEntry;
import org.gluu.persist.exception.EntryPersistenceException;
import org.gluu.persist.exception.InvalidArgumentException;
import org.gluu.persist.exception.MappingException;
import org.gluu.persist.model.AttributeData;
import org.gluu.persist.model.AttributeDataModification;
import org.gluu.persist.model.AttributeDataModification.AttributeModificationType;
import org.gluu.persist.model.SearchScope;
import org.gluu.persist.reflect.property.Getter;
import org.gluu.persist.reflect.property.PropertyAnnotation;
import org.gluu.persist.reflect.property.Setter;
import org.gluu.persist.reflect.util.ReflectHelper;
import org.gluu.search.filter.Filter;
import org.gluu.util.ArrayHelper;
import org.gluu.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class BaseEntryManager implements PersistenceEntryManager {
private static final Logger LOG = LoggerFactory.getLogger(BaseEntryManager.class);
private static final Class<?>[] LDAP_ENTRY_TYPE_ANNOTATIONS = { DataEntry.class, SchemaEntry.class,
ObjectClass.class };
private static final Class<?>[] LDAP_ENTRY_PROPERTY_ANNOTATIONS = { AttributeName.class, AttributesList.class,
JsonObject.class };
private static final Class<?>[] LDAP_CUSTOM_OBJECT_CLASS_PROPERTY_ANNOTATION = { CustomObjectClass.class };
private static final Class<?>[] LDAP_DN_PROPERTY_ANNOTATION = { DN.class };
public static final String OBJECT_CLASS = "objectClass";
public static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final Class<?>[] GROUP_BY_ALLOWED_DATA_TYPES = { String.class, Date.class, Integer.class,
AttributeEnum.class };
private static final Class<?>[] SUM_BY_ALLOWED_DATA_TYPES = { int.class, Integer.class, float.class, Float.class,
double.class, Double.class };
private final Map<String, List<PropertyAnnotation>> classAnnotations = new HashMap<String, List<PropertyAnnotation>>();
private final Map<String, Getter> classGetters = new HashMap<String, Getter>();
private final Map<String, Setter> classSetters = new HashMap<String, Setter>();
private static Object CLASS_ANNOTATIONS_LOCK = new Object();
private static Object CLASS_SETTERS_LOCK = new Object();
private static Object CLASS_GETTERS_LOCK = new Object();
private static final ObjectMapper JSON_OBJECT_MAPPER = new ObjectMapper();
protected static final String[] NO_STRINGS = new String[0];
protected static final Object[] NO_OBJECTS = new Object[0];
protected static final Comparator<String> LINE_LENGHT_COMPARATOR = new LineLenghtComparator<String>(false);
protected static final int DEFAULT_PAGINATION_SIZE = 100;
@Override
public void persist(Object entry) {
if (entry == null) {
throw new MappingException("Entry to persist is null");
}
// Check entry class
Class<?> entryClass = entry.getClass();
checkEntryClass(entryClass, false);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
// Add object classes
String[] objectClasses = getObjectClasses(entry, entryClass);
attributes.add(new AttributeData(OBJECT_CLASS, objectClasses, true));
LOG.debug(String.format("LDAP attributes for persist: %s", attributes));
persist(dnValue.toString(), attributes);
}
protected abstract void persist(String dn, List<AttributeData> attributes);
@Override
@SuppressWarnings("unchecked")
public <T> List<T> findEntries(Object entry, int count) {
if (entry == null) {
throw new MappingException("Entry to find is null");
}
// Check entry class
Class<T> entryClass = (Class<T>) entry.getClass();
checkEntryClass(entryClass, false);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
Filter searchFilter = createFilterByEntry(entry, entryClass, attributes);
return findEntries(dnValue.toString(), entryClass, searchFilter, SearchScope.SUB, null, 0, count,
DEFAULT_PAGINATION_SIZE);
}
@Override
public <T> List<T> findEntries(Object entry) {
return findEntries(entry, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter) {
return findEntries(baseDN, entryClass, filter, SearchScope.SUB, null, null, 0, 0, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter, int count) {
return findEntries(baseDN, entryClass, filter, SearchScope.SUB, null, null, 0, count, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter, String[] ldapReturnAttributes) {
return findEntries(baseDN, entryClass, filter, SearchScope.SUB, ldapReturnAttributes, null, 0, 0, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter, String[] ldapReturnAttributes,
int count) {
return findEntries(baseDN, entryClass, filter, SearchScope.SUB, ldapReturnAttributes, null, 0, count, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter, SearchScope scope,
String[] ldapReturnAttributes, int start, int count, int chunkSize) {
return findEntries(baseDN, entryClass, filter, scope, ldapReturnAttributes, null, start, count, chunkSize);
}
@SuppressWarnings("unchecked")
public <T> int countEntries(Object entry) {
if (entry == null) {
throw new MappingException("Entry to count is null");
}
// Check entry class
Class<T> entryClass = (Class<T>) entry.getClass();
checkEntryClass(entryClass, false);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
Filter searchFilter = createFilterByEntry(entry, entryClass, attributes);
return countEntries(dnValue.toString(), entryClass, searchFilter);
}
@SuppressWarnings("unchecked")
protected <T> T merge(T entry, boolean isSchemaUpdate, AttributeModificationType schemaModificationType) {
if (entry == null) {
throw new MappingException("Entry to persist is null");
}
Class<?> entryClass = entry.getClass();
checkEntryClass(entryClass, isSchemaUpdate);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Map<String, PropertyAnnotation> propertiesAnnotationsMap = prepareEntryPropertiesTypes(entryClass, propertiesAnnotations);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributesToPersist = getAttributesListForPersist(entry, propertiesAnnotations);
Map<String, AttributeData> attributesToPersistMap = getAttributesMap(attributesToPersist);
// Load entry
List<AttributeData> attributesFromLdap;
if (isSchemaUpdate) {
// If it's schema modification request we don't need to load
// attributes from LDAP
attributesFromLdap = new ArrayList<AttributeData>();
} else {
List<String> currentLdapReturnAttributesList = getAttributesList(entry, propertiesAnnotations, false);
currentLdapReturnAttributesList.add("objectClass");
attributesFromLdap = find(dnValue.toString(), propertiesAnnotationsMap, currentLdapReturnAttributesList.toArray(EMPTY_STRING_ARRAY));
}
Map<String, AttributeData> attributesFromLdapMap = getAttributesMap(attributesFromLdap);
// Prepare list of modifications
// Process properties with Attribute annotation
List<AttributeDataModification> attributeDataModifications = collectAttributeModifications(
propertiesAnnotations, attributesToPersistMap, attributesFromLdapMap, isSchemaUpdate,
schemaModificationType);
updateMergeChanges(dnValue.toString(), entry, isSchemaUpdate, entryClass, attributesFromLdapMap, attributeDataModifications);
LOG.debug(String.format("LDAP attributes for merge: %s", attributeDataModifications));
merge(dnValue.toString(), attributeDataModifications);
return (T) find(entryClass, dnValue.toString(), null, propertiesAnnotations, propertiesAnnotationsMap);
}
protected abstract <T> void updateMergeChanges(String baseDn, T entry, boolean isSchemaUpdate, Class<?> entryClass,
Map<String, AttributeData> attributesFromLdapMap,
List<AttributeDataModification> attributeDataModifications);
protected List<AttributeDataModification> collectAttributeModifications(
List<PropertyAnnotation> propertiesAnnotations, Map<String, AttributeData> attributesToPersistMap,
Map<String, AttributeData> attributesFromLdapMap, boolean isSchemaUpdate,
AttributeModificationType schemaModificationType) {
List<AttributeDataModification> attributeDataModifications = new ArrayList<AttributeDataModification>();
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute != null) {
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertyName;
}
ldapAttributeName = ldapAttributeName.toLowerCase();
AttributeData attributeToPersist = attributesToPersistMap.get(ldapAttributeName);
AttributeData attributeFromLdap = attributesFromLdapMap.get(ldapAttributeName);
// Remove processed attributes
attributesToPersistMap.remove(ldapAttributeName);
attributesFromLdapMap.remove(ldapAttributeName);
AttributeName ldapAttributeAnnotation = (AttributeName) ldapAttribute;
if (ldapAttributeAnnotation.ignoreDuringUpdate()) {
continue;
}
if (attributeFromLdap != null && attributeToPersist != null) {
// Modify DN entry attribute in DS
if (!attributeFromLdap.equals(attributeToPersist)) {
if (isEmptyAttributeValues(attributeToPersist) && !ldapAttributeAnnotation.updateOnly()) {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REMOVE, null, attributeFromLdap));
} else {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REPLACE, attributeToPersist, attributeFromLdap));
}
}
} else if ((attributeFromLdap == null) && (attributeToPersist != null)) {
// Add entry attribute or change schema
if (isSchemaUpdate && (attributeToPersist.getValue() == null
&& Arrays.equals(attributeToPersist.getValues(), new Object[] {}))) {
continue;
}
AttributeModificationType modType = isSchemaUpdate ? schemaModificationType
: AttributeModificationType.ADD;
if (AttributeModificationType.ADD.equals(modType)) {
if (!isEmptyAttributeValues(attributeToPersist)) {
attributeDataModifications.add(
new AttributeDataModification(AttributeModificationType.ADD, attributeToPersist));
}
} else {
attributeDataModifications.add(new AttributeDataModification(AttributeModificationType.REMOVE,
null, attributeToPersist));
}
} else if ((attributeFromLdap != null) && (attributeToPersist == null)) {
// Remove if attribute not marked as ignoreDuringRead = true
// or updateOnly = true
if (!ldapAttributeAnnotation.ignoreDuringRead() && !ldapAttributeAnnotation.updateOnly()) {
attributeDataModifications.add(new AttributeDataModification(AttributeModificationType.REMOVE,
null, attributeFromLdap));
}
}
}
}
// Process properties with @AttributesList annotation
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
Annotation ldapAttribute;
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributesList.class);
if (ldapAttribute != null) {
Map<String, AttributeName> ldapAttributesConfiguration = new HashMap<String, AttributeName>();
for (AttributeName ldapAttributeConfiguration : ((AttributesList) ldapAttribute)
.attributesConfiguration()) {
ldapAttributesConfiguration.put(ldapAttributeConfiguration.name(), ldapAttributeConfiguration);
}
// Prepare attributes for removal
for (AttributeData attributeFromLdap : attributesFromLdapMap.values()) {
String attributeName = attributeFromLdap.getName();
if (OBJECT_CLASS.equalsIgnoreCase(attributeName)) {
continue;
}
AttributeName ldapAttributeConfiguration = ldapAttributesConfiguration.get(attributeName);
if ((ldapAttributeConfiguration != null) && ldapAttributeConfiguration.ignoreDuringUpdate()) {
continue;
}
if (!attributesToPersistMap.containsKey(attributeName.toLowerCase())) {
// Remove if attribute not marked as ignoreDuringRead =
// true
if ((ldapAttributeConfiguration == null) || ((ldapAttributeConfiguration != null)
&& !ldapAttributeConfiguration.ignoreDuringRead())) {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REMOVE, null, attributeFromLdap));
}
}
}
// Prepare attributes for adding and replace
for (AttributeData attributeToPersist : attributesToPersistMap.values()) {
String attributeName = attributeToPersist.getName();
AttributeName ldapAttributeConfiguration = ldapAttributesConfiguration.get(attributeName);
if ((ldapAttributeConfiguration != null) && ldapAttributeConfiguration.ignoreDuringUpdate()) {
continue;
}
AttributeData attributeFromLdap = attributesFromLdapMap.get(attributeName.toLowerCase());
if (attributeFromLdap == null) {
// Add entry attribute or change schema
AttributeModificationType modType = isSchemaUpdate ? schemaModificationType
: AttributeModificationType.ADD;
if (AttributeModificationType.ADD.equals(modType)) {
if (!isEmptyAttributeValues(attributeToPersist)) {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.ADD, attributeToPersist));
}
} else {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REMOVE, null, attributeToPersist));
}
} else if ((attributeFromLdap != null)
&& (Arrays.equals(attributeToPersist.getValues(), new String[] {}))) {
attributeDataModifications.add(new AttributeDataModification(AttributeModificationType.REMOVE,
null, attributeFromLdap));
} else {
if (!attributeFromLdap.equals(attributeToPersist)) {
if (isEmptyAttributeValues(attributeToPersist)
&& !ldapAttributeConfiguration.updateOnly()) {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REMOVE, null, attributeFromLdap));
} else {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REPLACE, attributeToPersist, attributeFromLdap));
}
}
}
}
}
}
return attributeDataModifications;
}
protected boolean isEmptyAttributeValues(AttributeData attributeData) {
Object[] attributeToPersistValues = attributeData.getValues();
return ArrayHelper.isEmpty(attributeToPersistValues)
|| ((attributeToPersistValues.length == 1) && StringHelper.isEmpty(String.valueOf(attributeToPersistValues[0])));
}
protected abstract void merge(String dn, List<AttributeDataModification> attributeDataModifications);
public abstract void remove(String dn);
@Override
public boolean contains(Object entry) {
if (entry == null) {
throw new MappingException("Entry to persist is null");
}
// Check entry class
Class<?> entryClass = entry.getClass();
checkEntryClass(entryClass, false);
String[] objectClasses = getObjectClasses(entry, entryClass);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
String[] ldapReturnAttributes = getAttributes(null, propertiesAnnotations, false);
return contains(dnValue.toString(), entryClass, propertiesAnnotations, attributes, objectClasses, ldapReturnAttributes);
}
protected <T> boolean contains(Class<T> entryClass, String primaryKey, String[] ldapReturnAttributes) {
if (StringHelper.isEmptyString(primaryKey)) {
throw new MappingException("DN to find entry is null");
}
checkEntryClass(entryClass, true);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Map<String, PropertyAnnotation> propertiesAnnotationsMap = prepareEntryPropertiesTypes(entryClass, propertiesAnnotations);
try {
List<AttributeData> results = find(primaryKey, propertiesAnnotationsMap, ldapReturnAttributes);
return (results != null) && (results.size() > 0);
} catch (EntryPersistenceException ex) {
return false;
}
}
@Override
public <T> boolean contains(String baseDN, Class<T> entryClass, Filter filter) {
// Check entry class
checkEntryClass(entryClass, false);
String[] objectClasses = getTypeObjectClasses(entryClass);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
String[] ldapReturnAttributes = getAttributes(null, propertiesAnnotations, false);
return contains(baseDN, entryClass, propertiesAnnotations, filter, objectClasses, ldapReturnAttributes);
}
protected <T> boolean contains(String baseDN, Class<T> entryClass, List<PropertyAnnotation> propertiesAnnotations, List<AttributeData> attributes, String[] objectClasses,
String... ldapReturnAttributes) {
Filter[] attributesFilters = createAttributesFilter(attributes);
Filter attributesFilter = null;
if (attributesFilters != null) {
attributesFilter = Filter.createANDFilter(attributesFilters);
}
return contains(baseDN, entryClass, propertiesAnnotations, attributesFilter, objectClasses, ldapReturnAttributes);
}
protected abstract <T> boolean contains(String baseDN, Class<T> entryClass, List<PropertyAnnotation> propertiesAnnotations,
Filter filter, String[] objectClasses, String[] ldapReturnAttributes);
@Override
public <T> boolean contains(String primaryKey, Class<T> entryClass) {
return contains(entryClass, primaryKey, (String[]) null);
}
@Override
public <T> T find(Class<T> entryClass, Object primaryKey) {
return find(primaryKey, entryClass, null);
}
@Override
public <T> T find(Object primaryKey, Class<T> entryClass, String[] ldapReturnAttributes) {
if (StringHelper.isEmptyString(primaryKey)) {
throw new MappingException("DN to find entry is null");
}
checkEntryClass(entryClass, true);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Map<String, PropertyAnnotation> propertiesAnnotationsMap = prepareEntryPropertiesTypes(entryClass, propertiesAnnotations);
return find(entryClass, primaryKey, ldapReturnAttributes, propertiesAnnotations, propertiesAnnotationsMap);
}
protected <T> String[] getAttributes(T entry, List<PropertyAnnotation> propertiesAnnotations,
boolean isIgnoreAttributesList) {
List<String> attributes = getAttributesList(entry, propertiesAnnotations, isIgnoreAttributesList);
if (attributes == null) {
return null;
}
return attributes.toArray(new String[0]);
}
protected <T> String[] getAttributes(Map<String, PropertyAnnotation> attributesMap) {
if (attributesMap == null) {
return null;
}
return attributesMap.keySet().toArray(new String[0]);
}
protected <T> List<String> getAttributesList(T entry, List<PropertyAnnotation> propertiesAnnotations,
boolean isIgnoreAttributesList) {
Map<String, PropertyAnnotation> attributesMap = getAttributesMap(entry, propertiesAnnotations, isIgnoreAttributesList);
if (attributesMap == null) {
return null;
}
return new ArrayList<String>(attributesMap.keySet());
}
protected <T> Map<String, PropertyAnnotation> getAttributesMap(T entry, List<PropertyAnnotation> propertiesAnnotations,
boolean isIgnoreAttributesList) {
Map<String, PropertyAnnotation> attributes = new HashMap<String, PropertyAnnotation>();
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
if (!isIgnoreAttributesList) {
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributesList.class);
if (ldapAttribute != null) {
if (entry == null) {
return null;
} else {
List<AttributeData> attributesList = getAttributesFromAttributesList(entry,
ldapAttribute, propertyName);
for (AttributeData attributeData : attributesList) {
String ldapAttributeName = attributeData.getName();
if (!attributes.containsKey(ldapAttributeName)) {
attributes.put(ldapAttributeName, propertiesAnnotation);
}
}
}
}
}
// Process properties with AttributeName annotation
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute != null) {
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertyName;
}
if (!attributes.containsKey(ldapAttributeName)) {
attributes.put(ldapAttributeName, propertiesAnnotation);
}
}
}
if (attributes.size() == 0) {
return null;
}
return attributes;
}
protected <T> Map<String, PropertyAnnotation> prepareEntryPropertiesTypes(Class<T> entryClass, List<PropertyAnnotation> propertiesAnnotations) {
Map<String, PropertyAnnotation> propertiesAnnotationsMap = getAttributesMap(null, propertiesAnnotations, true);
if (propertiesAnnotationsMap== null) {
return new HashMap<String, PropertyAnnotation>(0);
}
preparePropertyAnnotationTypes(entryClass, propertiesAnnotationsMap);
return propertiesAnnotationsMap;
}
protected <T> void preparePropertyAnnotationTypes(Class<T> entry, Map<String, PropertyAnnotation> propertiesAnnotationsMap) {
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotationsMap.values()) {
String propertyName = propertiesAnnotation.getPropertyName();
Class<?> parameterType = getSetterPropertyType(entry, propertyName);
propertiesAnnotation.setParameterType(parameterType);
}
}
private <T> Class<?> getSetterPropertyType(Class<T> entry, String propertyName) {
Setter propertyValueSetter = getSetter(entry, propertyName);
if (propertyValueSetter == null) {
throw new MappingException("Entry should has setter for property " + propertyName);
}
Class<?> parameterType = ReflectHelper.getSetterType(propertyValueSetter);
return parameterType;
}
private <T> T find(Class<T> entryClass, Object primaryKey, String[] ldapReturnAttributes,
List<PropertyAnnotation> propertiesAnnotations, Map<String, PropertyAnnotation> propertiesAnnotationsMap) {
Map<String, List<AttributeData>> entriesAttributes = new HashMap<String, List<AttributeData>>();
String[] currentLdapReturnAttributes = ldapReturnAttributes;
if (ArrayHelper.isEmpty(currentLdapReturnAttributes)) {
currentLdapReturnAttributes = getAttributes(null, propertiesAnnotations, false);
}
List<AttributeData> ldapAttributes = find(primaryKey.toString(), propertiesAnnotationsMap, currentLdapReturnAttributes);
entriesAttributes.put(String.valueOf(primaryKey), ldapAttributes);
List<T> results = createEntities(entryClass, propertiesAnnotations, entriesAttributes);
return results.get(0);
}
protected abstract List<AttributeData> find(String dn, Map<String, PropertyAnnotation> propertiesAnnotationsMap, String... attributes);
protected boolean checkEntryClass(Class<?> entryClass, boolean isAllowSchemaEntry) {
if (entryClass == null) {
throw new MappingException("Entry class is null");
}
// Check if entry is LDAP Entry
List<Annotation> entryAnnotations = ReflectHelper.getClassAnnotations(entryClass, LDAP_ENTRY_TYPE_ANNOTATIONS);
Annotation ldapSchemaEntry = ReflectHelper.getAnnotationByType(entryAnnotations, SchemaEntry.class);
Annotation ldapEntry = ReflectHelper.getAnnotationByType(entryAnnotations, DataEntry.class);
if (isAllowSchemaEntry) {
if ((ldapSchemaEntry == null) && (ldapEntry == null)) {
throw new MappingException("Entry should has DataEntry or SchemaEntry annotation");
}
} else {
if (ldapEntry == null) {
throw new MappingException("Entry should has DataEntry annotation");
}
}
return true;
}
protected boolean isSchemaEntry(Class<?> entryClass) {
if (entryClass == null) {
throw new MappingException("Entry class is null");
}
// Check if entry is LDAP Entry
List<Annotation> entryAnnotations = ReflectHelper.getClassAnnotations(entryClass, LDAP_ENTRY_TYPE_ANNOTATIONS);
return ReflectHelper.getAnnotationByType(entryAnnotations, SchemaEntry.class) != null;
}
protected String[] getEntrySortBy(Class<?> entryClass) {
if (entryClass == null) {
throw new MappingException("Entry class is null");
}
// Check if entry is LDAP Entry
List<Annotation> entryAnnotations = ReflectHelper.getClassAnnotations(entryClass, LDAP_ENTRY_TYPE_ANNOTATIONS);
Annotation annotation = ReflectHelper.getAnnotationByType(entryAnnotations, DataEntry.class);
if (annotation == null) {
return null;
}
return ((DataEntry) annotation).sortBy();
}
@Override
public String[] getObjectClasses(Object entry, Class<?> entryClass) {
String[] typeObjectClasses = getTypeObjectClasses(entryClass);
String[] customObjectClasses = getCustomObjectClasses(entry, entryClass);
if (ArrayHelper.isEmpty(typeObjectClasses)) {
return customObjectClasses;
}
String[] mergedArray = ArrayHelper.arrayMerge(typeObjectClasses, customObjectClasses);
Set<String> objecClassSet = new HashSet<String>();
objecClassSet.addAll(Arrays.asList(mergedArray));
return objecClassSet.toArray(new String[0]);
}
protected String[] getTypeObjectClasses(Class<?> entryClass) {
// Check if entry is LDAP Entry
List<Annotation> entryAnnotations = ReflectHelper.getClassAnnotations(entryClass, LDAP_ENTRY_TYPE_ANNOTATIONS);
// Get object classes
Annotation ldapObjectClass = ReflectHelper.getAnnotationByType(entryAnnotations, ObjectClass.class);
if (ldapObjectClass == null) {
return EMPTY_STRING_ARRAY;
}
if (StringHelper.isEmpty(((ObjectClass) ldapObjectClass).value())) {
return EMPTY_STRING_ARRAY;
}
return new String[] { ((ObjectClass) ldapObjectClass).value() };
}
protected String[] getCustomObjectClasses(Object entry, Class<?> entryClass) {
List<String> result = new ArrayList<String>();
List<PropertyAnnotation> customObjectAnnotations = getEntryCustomObjectClassAnnotations(entryClass);
for (PropertyAnnotation propertiesAnnotation : customObjectAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Getter getter = getGetter(entryClass, propertyName);
if (getter == null) {
throw new MappingException("Entry should has getter for property " + propertyName);
}
Class<?> parameterType = getSetterPropertyType(entryClass, propertyName);
boolean multiValued = isMultiValued(parameterType);
AttributeData attribute = getAttributeData(propertyName, propertyName, getter, entry, multiValued, false);
if (attribute != null) {
for (String objectClass : attribute.getStringValues()) {
if (objectClass != null) {
result.add(objectClass);
}
}
}
break;
}
return result.toArray(new String[0]);
}
protected void setCustomObjectClasses(Object entry, Class<?> entryClass, String[] objectClasses) {
List<PropertyAnnotation> customObjectAnnotations = getEntryCustomObjectClassAnnotations(entryClass);
for (PropertyAnnotation propertiesAnnotation : customObjectAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Setter setter = getSetter(entryClass, propertyName);
if (setter == null) {
throw new MappingException("Entry should has setter for property " + propertyName);
}
AttributeData attribute = new AttributeData(propertyName, objectClasses);
setPropertyValue(propertyName, setter, entry, attribute, false);
break;
}
}
protected String getDNPropertyName(Class<?> entryClass) {
List<PropertyAnnotation> propertiesAnnotations = getEntryDnAnnotations(entryClass);
if (propertiesAnnotations.size() == 0) {
throw new MappingException("Entry should has property with annotation LdapDN");
}
if (propertiesAnnotations.size() > 1) {
throw new MappingException("Entry should has only one property with annotation LdapDN");
}
return propertiesAnnotations.get(0).getPropertyName();
}
protected <T> List<T> createEntities(Class<T> entryClass, List<PropertyAnnotation> propertiesAnnotations,
Map<String, List<AttributeData>> entriesAttributes) {
return createEntities(entryClass, propertiesAnnotations, entriesAttributes, true);
}
protected <T> List<T> createEntities(Class<T> entryClass, List<PropertyAnnotation> propertiesAnnotations,
Map<String, List<AttributeData>> entriesAttributes, boolean doSort) {
// Check if entry has DN property
String dnProperty = getDNPropertyName(entryClass);
// Get DN value
Setter dnSetter = getSetter(entryClass, dnProperty);
if (dnSetter == null) {
throw new MappingException("Entry should has getter for property " + dnProperty);
}
// Type object classes
String[] typeObjectClasses = getTypeObjectClasses(entryClass);
Arrays.sort(typeObjectClasses);
List<T> results = new ArrayList<T>(entriesAttributes.size());
for (Entry<String, List<AttributeData>> entryAttributes : entriesAttributes.entrySet()) {
String dn = entryAttributes.getKey();
List<AttributeData> attributes = entryAttributes.getValue();
Map<String, AttributeData> attributesMap = getAttributesMap(attributes);
T entry;
List<String> customObjectClasses = null;
try {
entry = ReflectHelper.createObjectByDefaultConstructor(entryClass);
} catch (Exception ex) {
throw new MappingException(String.format("Entry %s should has default constructor", entryClass));
}
results.add(entry);
dnSetter.set(entry, dn);
// Remove processed DN attribute
attributesMap.remove(dnProperty);
// Set loaded properties to entry
// Process properties with AttributeName annotation
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute != null) {
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertyName;
}
ldapAttributeName = ldapAttributeName.toLowerCase();
AttributeData attributeData = attributesMap.get(ldapAttributeName);
// Remove processed attributes
attributesMap.remove(ldapAttributeName);
if (((AttributeName) ldapAttribute).ignoreDuringRead()) {
continue;
}
Setter setter = getSetter(entryClass, propertyName);
if (setter == null) {
throw new MappingException("Entry should has setter for property " + propertyName);
}
Annotation ldapJsonObject = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
JsonObject.class);
boolean jsonObject = ldapJsonObject != null;
setPropertyValue(propertyName, setter, entry, attributeData, jsonObject);
}
}
// Process properties with @AttributesList annotation
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributesList.class);
if (ldapAttribute != null) {
Map<String, AttributeName> ldapAttributesConfiguration = new HashMap<String, AttributeName>();
for (AttributeName ldapAttributeConfiguration : ((AttributesList) ldapAttribute)
.attributesConfiguration()) {
ldapAttributesConfiguration.put(ldapAttributeConfiguration.name(), ldapAttributeConfiguration);
}
Setter setter = getSetter(entryClass, propertyName);
if (setter == null) {
throw new MappingException("Entry should has setter for property " + propertyName);
}
List<Object> propertyValue = new ArrayList<Object>();
setter.set(entry, propertyValue);
Class<?> entryItemType = ReflectHelper.getListType(setter);
if (entryItemType == null) {
throw new MappingException(
"Entry property " + propertyName + " should has setter with specified element type");
}
String entryPropertyName = ((AttributesList) ldapAttribute).name();
Setter entryPropertyNameSetter = getSetter(entryItemType, entryPropertyName);
if (entryPropertyNameSetter == null) {
throw new MappingException(
"Entry should has setter for property " + propertyName + "." + entryPropertyName);
}
String entryPropertyValue = ((AttributesList) ldapAttribute).value();
Setter entryPropertyValueSetter = getSetter(entryItemType, entryPropertyValue);
if (entryPropertyValueSetter == null) {
throw new MappingException(
"Entry should has getter for property " + propertyName + "." + entryPropertyValue);
}
for (AttributeData entryAttribute : attributesMap.values()) {
if (OBJECT_CLASS.equalsIgnoreCase(entryAttribute.getName())) {
String[] objectClasses = entryAttribute.getStringValues();
if (ArrayHelper.isEmpty(objectClasses)) {
continue;
}
if (customObjectClasses == null) {
customObjectClasses = new ArrayList<String>();
}
for (String objectClass : objectClasses) {
int idx = Arrays.binarySearch(typeObjectClasses, objectClass, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.toLowerCase().compareTo(o2.toLowerCase());
}
});
if (idx < 0) {
customObjectClasses.add(objectClass);
}
}
continue;
}
AttributeName ldapAttributeConfiguration = ldapAttributesConfiguration
.get(entryAttribute.getName());
if ((ldapAttributeConfiguration != null) && ldapAttributeConfiguration.ignoreDuringRead()) {
continue;
}
String entryPropertyMultivalued = ((AttributesList) ldapAttribute).multiValued();
Setter entryPropertyMultivaluedSetter = null;
if (StringHelper.isNotEmpty(entryPropertyMultivalued)) {
entryPropertyMultivaluedSetter = getSetter(entryItemType, entryPropertyMultivalued);
}
if (entryPropertyMultivaluedSetter != null) {
Class<?> parameterType = ReflectHelper.getSetterType(entryPropertyMultivaluedSetter);
if (!parameterType.equals(Boolean.TYPE)) {
throw new MappingException(
"Entry should has getter for property " + propertyName + "." + entryPropertyMultivalued + " with boolean type");
}
}
Object listItem = getListItem(propertyName, entryPropertyNameSetter, entryPropertyValueSetter,
entryPropertyMultivaluedSetter, entryItemType, entryAttribute);
if (listItem != null) {
propertyValue.add(listItem);
}
}
if (doSort) {
sortAttributesListIfNeeded((AttributesList) ldapAttribute, entryItemType,
propertyValue);
}
}
}
if ((customObjectClasses != null) && (customObjectClasses.size() > 0)) {
setCustomObjectClasses(entry, entryClass, customObjectClasses.toArray(new String[0]));
}
}
return results;
}
@Override
public <T> List<T> createEntities(Class<T> entryClass, Map<String, List<AttributeData>> entriesAttributes) {
checkEntryClass(entryClass, true);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
return createEntities(entryClass, propertiesAnnotations, entriesAttributes);
}
@SuppressWarnings("unchecked")
private <T> void sortAttributesListIfNeeded(AttributesList ldapAttribute, Class<T> entryItemType,
List<?> list) {
if (!ldapAttribute.sortByName()) {
return;
}
sortListByProperties(entryItemType, (List<T>) list, ldapAttribute.name());
}
protected <T> void sortEntriesIfNeeded(Class<T> entryClass, List<T> entries) {
String[] sortByProperties = getEntrySortBy(entryClass);
if (ArrayHelper.isEmpty(sortByProperties)) {
return;
}
sortListByProperties(entryClass, entries, sortByProperties);
}
@Override
public <T> void sortListByProperties(Class<T> entryClass, List<T> entries, boolean caseSensetive,
String... sortByProperties) {
// Check input parameters
if (entries == null) {
throw new MappingException("Entries list to sort is null");
}
if (entries.size() == 0) {
return;
}
if ((sortByProperties == null) || (sortByProperties.length == 0)) {
throw new InvalidArgumentException(
"Invalid list of sortBy properties " + Arrays.toString(sortByProperties));
}
// Get getters for all properties
Getter[][] propertyGetters = new Getter[sortByProperties.length][];
for (int i = 0; i < sortByProperties.length; i++) {
String[] tmpProperties = sortByProperties[i].split("\\.");
propertyGetters[i] = new Getter[tmpProperties.length];
Class<?> currentEntryClass = entryClass;
for (int j = 0; j < tmpProperties.length; j++) {
if (j > 0) {
currentEntryClass = propertyGetters[i][j - 1].getReturnType();
}
propertyGetters[i][j] = getGetter(currentEntryClass, tmpProperties[j]);
}
if (propertyGetters[i][tmpProperties.length - 1] == null) {
throw new MappingException("Entry should has getteres for all properties " + sortByProperties[i]);
}
Class<?> propertyType = propertyGetters[i][tmpProperties.length - 1].getReturnType();
if (!((propertyType == String.class) || (propertyType == Date.class) || (propertyType == Integer.class)
|| (propertyType == Integer.TYPE))) {
throw new MappingException("Entry properties should has String, Date or Integer type. Property: '"
+ tmpProperties[tmpProperties.length - 1] + "'");
}
}
PropertyComparator<T> comparator = new PropertyComparator<T>(propertyGetters, caseSensetive);
Collections.sort(entries, comparator);
}
protected <T> void sortListByProperties(Class<T> entryClass, List<T> entries, String... sortByProperties) {
sortListByProperties(entryClass, entries, false, sortByProperties);
}
@Override
public <T> Map<T, List<T>> groupListByProperties(Class<T> entryClass, List<T> entries, boolean caseSensetive,
String groupByProperties, String sumByProperties) {
// Check input parameters
if (entries == null) {
throw new MappingException("Entries list to group is null");
}
if (entries.size() == 0) {
return new HashMap<T, List<T>>(0);
}
if (StringHelper.isEmpty(groupByProperties)) {
throw new InvalidArgumentException("List of groupBy properties is null");
}
// Get getters for all properties
Getter[] groupPropertyGetters = getEntryPropertyGetters(entryClass, groupByProperties,
GROUP_BY_ALLOWED_DATA_TYPES);
Setter[] groupPropertySetters = getEntryPropertySetters(entryClass, groupByProperties,
GROUP_BY_ALLOWED_DATA_TYPES);
Getter[] sumPropertyGetters = getEntryPropertyGetters(entryClass, sumByProperties, SUM_BY_ALLOWED_DATA_TYPES);
Setter[] sumPropertySetter = getEntryPropertySetters(entryClass, sumByProperties, SUM_BY_ALLOWED_DATA_TYPES);
return groupListByPropertiesImpl(entryClass, entries, caseSensetive, groupPropertyGetters, groupPropertySetters,
sumPropertyGetters, sumPropertySetter);
}
private <T> Getter[] getEntryPropertyGetters(Class<T> entryClass, String properties, Class<?>[] allowedTypes) {
if (StringHelper.isEmpty(properties)) {
return null;
}
String[] tmpProperties = properties.split("\\,");
Getter[] propertyGetters = new Getter[tmpProperties.length];
for (int i = 0; i < tmpProperties.length; i++) {
propertyGetters[i] = getGetter(entryClass, tmpProperties[i].trim());
if (propertyGetters[i] == null) {
throw new MappingException("Entry should has getter for property " + tmpProperties[i]);
}
Class<?> returnType = propertyGetters[i].getReturnType();
boolean found = false;
for (Class<?> clazz : allowedTypes) {
if (ReflectHelper.assignableFrom(returnType, clazz)) {
found = true;
break;
}
}
if (!found) {
throw new MappingException(
"Entry property getter should has next data types " + Arrays.toString(allowedTypes));
}
}
return propertyGetters;
}
private <T> Setter[] getEntryPropertySetters(Class<T> entryClass, String properties, Class<?>[] allowedTypes) {
if (StringHelper.isEmpty(properties)) {
return null;
}
String[] tmpProperties = properties.split("\\,");
Setter[] propertySetters = new Setter[tmpProperties.length];
for (int i = 0; i < tmpProperties.length; i++) {
propertySetters[i] = getSetter(entryClass, tmpProperties[i].trim());
if (propertySetters[i] == null) {
throw new MappingException("Entry should has setter for property " + tmpProperties[i]);
}
Class<?> paramType = ReflectHelper.getSetterType(propertySetters[i]);
boolean found = false;
for (Class<?> clazz : allowedTypes) {
if (ReflectHelper.assignableFrom(paramType, clazz)) {
found = true;
break;
}
}
if (!found) {
throw new MappingException(
"Entry property setter should has next data types " + Arrays.toString(allowedTypes));
}
}
return propertySetters;
}
protected <T> Map<T, List<T>> groupListByProperties(Class<T> entryClass, List<T> entries, String groupByProperties,
String sumByProperties) {
return groupListByProperties(entryClass, entries, false, groupByProperties, sumByProperties);
}
private <T> Map<T, List<T>> groupListByPropertiesImpl(Class<T> entryClass, List<T> entries, boolean caseSensetive,
Getter[] groupPropertyGetters, Setter[] groupPropertySetters, Getter[] sumProperyGetters,
Setter[] sumPropertySetter) {
Map<String, T> keys = new HashMap<String, T>();
Map<T, List<T>> groups = new IdentityHashMap<T, List<T>>();
for (T entry : entries) {
String key = getEntryKey(entry, caseSensetive, groupPropertyGetters);
T entryKey = keys.get(key);
if (entryKey == null) {
try {
entryKey = ReflectHelper.createObjectByDefaultConstructor(entryClass);
} catch (Exception ex) {
throw new MappingException(String.format("Entry %s should has default constructor", entryClass),
ex);
}
try {
ReflectHelper.copyObjectPropertyValues(entry, entryKey, groupPropertyGetters, groupPropertySetters);
} catch (Exception ex) {
throw new MappingException("Failed to set values in group Entry", ex);
}
keys.put(key, entryKey);
}
List<T> groupValues = groups.get(entryKey);
if (groupValues == null) {
groupValues = new ArrayList<T>();
groups.put(entryKey, groupValues);
}
try {
if (sumProperyGetters != null) {
ReflectHelper.sumObjectPropertyValues(entryKey, entry, sumProperyGetters, sumPropertySetter);
}
} catch (Exception ex) {
throw new MappingException("Failed to sum values in group Entry", ex);
}
groupValues.add(entry);
}
return groups;
}
private Map<String, AttributeData> getAttributesMap(List<AttributeData> attributes) {
Map<String, AttributeData> attributesMap = new HashMap<String, AttributeData>(attributes.size());
for (AttributeData attribute : attributes) {
attributesMap.put(attribute.getName().toLowerCase(), attribute);
}
return attributesMap;
}
private AttributeData getAttributeData(String propertyName, String ldapAttributeName, Getter propertyValueGetter,
Object entry, boolean multiValued, boolean jsonObject) {
Object propertyValue = propertyValueGetter.get(entry);
if (propertyValue == null) {
return null;
}
Object[] attributeValues = getAttributeValues(propertyName, jsonObject, propertyValue);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Property: %s, LdapProperty: %s, PropertyValue: %s", propertyName,
ldapAttributeName, Arrays.toString(attributeValues)));
}
if (attributeValues.length == 0) {
attributeValues = new String[] {};
} else if ((attributeValues.length == 1) && (attributeValues[0] == null)) {
return null;
}
return new AttributeData(ldapAttributeName, attributeValues, multiValued);
}
private Object[] getAttributeValues(String propertyName, boolean jsonObject, Object propertyValue) {
Object[] attributeValues = new Object[1];
boolean nativeType = getNativeAttributeValue(propertyValue, attributeValues);
if (nativeType) {
// We do conversion in getNativeAttributeValue method already
} else if (propertyValue instanceof AttributeEnum) {
attributeValues[0] = ((AttributeEnum) propertyValue).getValue();
} else if (propertyValue instanceof AttributeEnum[]) {
AttributeEnum[] propertyValues = (AttributeEnum[]) propertyValue;
attributeValues = new String[propertyValues.length];
for (int i = 0; i < propertyValues.length; i++) {
attributeValues[i] = (propertyValues[i] == null) ? null : propertyValues[i].getValue();
}
} else if (propertyValue instanceof String[]) {
attributeValues = (String[]) propertyValue;
} else if (propertyValue instanceof Object[]) {
attributeValues = (Object[]) propertyValue;
} else if (propertyValue instanceof List<?>) {
attributeValues = new Object[((List<?>) propertyValue).size()];
int index = 0;
Object nativeAttributeValue[] = new Object[1];
for (Object tmpPropertyValue : (List<?>) propertyValue) {
if (jsonObject) {
attributeValues[index++] = convertValueToJson(tmpPropertyValue);
} else {
if (getNativeAttributeValue(tmpPropertyValue, nativeAttributeValue)) {
attributeValues[index++] = nativeAttributeValue[0];
} else {
attributeValues[index++] = StringHelper.toString(tmpPropertyValue);
}
}
}
} else if (jsonObject) {
attributeValues[0] = convertValueToJson(propertyValue);
} else {
throw new MappingException("Entry property '" + propertyName
+ "' should has getter with String, String[], Boolean, Integer, Long, Date, List<String>, AttributeEnum or AttributeEnum[]"
+ " return type or has annotation JsonObject");
}
return attributeValues;
}
/*
* This method doesn't produces new object to avoid extra garbage creation
*/
private boolean getNativeAttributeValue(Object propertyValue, Object[] resultValue) {
// Clean result
resultValue[0] = null;
if (propertyValue instanceof String) {
resultValue[0] = StringHelper.toString(propertyValue);
} else if (propertyValue instanceof Boolean) {
resultValue[0] = propertyValue;
} else if (propertyValue instanceof Integer) {
resultValue[0] = propertyValue;
} else if (propertyValue instanceof Long) {
resultValue[0] = propertyValue;
} else if (propertyValue instanceof Date) {
resultValue[0] = encodeTime((Date) propertyValue);
} else {
return false;
}
return true;
}
protected boolean isAttributeMultivalued(Object[] values) {
if (values.length > 1) {
return true;
}
return false;
}
protected Object convertValueToJson(Object propertyValue) {
try {
String value = JSON_OBJECT_MAPPER.writeValueAsString(propertyValue);
return value;
} catch (Exception ex) {
LOG.error("Failed to convert '{}' to json value:", propertyValue, ex);
throw new MappingException(String.format("Failed to convert '%s' to json value", propertyValue));
}
}
protected List<AttributeData> getAttributesListForPersist(Object entry,
List<PropertyAnnotation> propertiesAnnotations) {
// Prepare list of properties to persist
List<AttributeData> attributes = new ArrayList<AttributeData>();
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
// Process properties with AttributeName annotation
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute != null) {
AttributeData attribute = getAttributeDataFromAttribute(entry, ldapAttribute, propertiesAnnotation,
propertyName);
if (attribute != null) {
attributes.add(attribute);
}
continue;
}
// Process properties with @AttributesList annotation
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributesList.class);
if (ldapAttribute != null) {
List<AttributeData> listAttributes = getAttributesFromAttributesList(entry, ldapAttribute,
propertyName);
if (listAttributes != null) {
attributes.addAll(listAttributes);
}
continue;
}
}
return attributes;
}
private AttributeData getAttributeDataFromAttribute(Object entry, Annotation ldapAttribute,
PropertyAnnotation propertiesAnnotation, String propertyName) {
Class<?> entryClass = entry.getClass();
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertyName;
}
Getter getter = getGetter(entryClass, propertyName);
if (getter == null) {
throw new MappingException("Entry should has getter for property " + propertyName);
}
Class<?> parameterType = getSetterPropertyType(entryClass, propertyName);
boolean multiValued = isMultiValued(parameterType);
Annotation ldapJsonObject = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
JsonObject.class);
boolean jsonObject = ldapJsonObject != null;
AttributeData attribute = getAttributeData(propertyName, ldapAttributeName, getter, entry, multiValued, jsonObject);
return attribute;
}
private List<AttributeData> getAttributesFromAttributesList(Object entry, Annotation ldapAttribute,
String propertyName) {
Class<?> entryClass = entry.getClass();
List<AttributeData> listAttributes = new ArrayList<AttributeData>();
Getter getter = getGetter(entryClass, propertyName);
if (getter == null) {
throw new MappingException("Entry should has getter for property " + propertyName);
}
Object propertyValue = getter.get(entry);
if (propertyValue == null) {
return null;
}
if (!(propertyValue instanceof List<?>)) {
throw new MappingException("Entry property should has List base type");
}
Class<?> elementType = ReflectHelper.getListType(getter);
String entryPropertyName = ((AttributesList) ldapAttribute).name();
Getter entryPropertyNameGetter = getGetter(elementType, entryPropertyName);
if (entryPropertyNameGetter == null) {
throw new MappingException(
"Entry should has getter for property " + propertyName + "." + entryPropertyName);
}
String entryPropertyValue = ((AttributesList) ldapAttribute).value();
Getter entryPropertyValueGetter = getGetter(elementType, entryPropertyValue);
if (entryPropertyValueGetter == null) {
throw new MappingException(
"Entry should has getter for property " + propertyName + "." + entryPropertyValue);
}
String entryPropertyMultivalued = ((AttributesList) ldapAttribute).multiValued();
Getter entryPropertyMultivaluedGetter = null;
if (StringHelper.isNotEmpty(entryPropertyMultivalued)) {
entryPropertyMultivaluedGetter = getGetter(elementType, entryPropertyMultivalued);
}
if (entryPropertyMultivaluedGetter != null) {
Class<?> propertyType = entryPropertyMultivaluedGetter.getReturnType();
if (!propertyType.equals(Boolean.TYPE)) {
throw new MappingException(
"Entry should has getter for property " + propertyName + "." + entryPropertyMultivalued + " with boolean type");
}
}
for (Object entryAttribute : (List<?>) propertyValue) {
AttributeData attribute = getAttributeData(propertyName, entryPropertyNameGetter, entryPropertyValueGetter,
entryAttribute, false);
if (attribute != null) {
if (entryPropertyMultivaluedGetter != null) {
boolean multiValued = (boolean) entryPropertyMultivaluedGetter.get(entryAttribute);
attribute.setMultiValued(multiValued);
} else {
// Detect if attribute has more than one value
boolean multiValued = attribute.getValues().length > 1;
attribute.setMultiValued(multiValued);
}
listAttributes.add(attribute);
}
}
return listAttributes;
}
protected <T> List<PropertyAnnotation> getEntryPropertyAnnotations(Class<T> entryClass) {
final List<PropertyAnnotation> annotations = getEntryClassAnnotations(entryClass, "property_", LDAP_ENTRY_PROPERTY_ANNOTATIONS);
// KeyShortcuter.initIfNeeded(entryClass, annotations);
return annotations;
}
protected <T> List<PropertyAnnotation> getEntryDnAnnotations(Class<T> entryClass) {
return getEntryClassAnnotations(entryClass, "dn_", LDAP_DN_PROPERTY_ANNOTATION);
}
protected <T> List<PropertyAnnotation> getEntryCustomObjectClassAnnotations(Class<T> entryClass) {
return getEntryClassAnnotations(entryClass, "custom_", LDAP_CUSTOM_OBJECT_CLASS_PROPERTY_ANNOTATION);
}
protected <T> List<PropertyAnnotation> getEntryClassAnnotations(Class<T> entryClass, String keyCategory,
Class<?>[] annotationTypes) {
String key = keyCategory + entryClass.getName();
List<PropertyAnnotation> annotations = classAnnotations.get(key);
if (annotations == null) {
synchronized (CLASS_ANNOTATIONS_LOCK) {
annotations = classAnnotations.get(key);
if (annotations == null) {
Map<String, List<Annotation>> annotationsMap = ReflectHelper.getPropertiesAnnotations(entryClass,
annotationTypes);
annotations = convertToPropertyAnnotationList(annotationsMap);
classAnnotations.put(key, annotations);
}
}
}
return annotations;
}
private List<PropertyAnnotation> convertToPropertyAnnotationList(Map<String, List<Annotation>> annotations) {
List<PropertyAnnotation> result = new ArrayList<PropertyAnnotation>(annotations.size());
for (Entry<String, List<Annotation>> entry : annotations.entrySet()) {
result.add(new PropertyAnnotation(entry.getKey(), entry.getValue()));
}
Collections.sort(result);
return result;
}
protected <T> Getter getGetter(Class<T> entryClass, String propertyName) {
String key = entryClass.getName() + "." + propertyName;
Getter getter = classGetters.get(key);
if (getter == null) {
synchronized (CLASS_GETTERS_LOCK) {
getter = classGetters.get(key);
if (getter == null) {
getter = ReflectHelper.getGetter(entryClass, propertyName);
classGetters.put(key, getter);
}
}
}
return getter;
}
protected <T> Setter getSetter(Class<T> entryClass, String propertyName) {
String key = entryClass.getName() + "." + propertyName;
Setter setter = classSetters.get(key);
if (setter == null) {
synchronized (CLASS_SETTERS_LOCK) {
setter = classSetters.get(key);
if (setter == null) {
setter = ReflectHelper.getSetter(entryClass, propertyName);
classSetters.put(key, setter);
}
}
}
return setter;
}
private AttributeData getAttributeData(String propertyName, Getter propertyNameGetter, Getter propertyValueGetter,
Object entry, boolean jsonObject) {
Object ldapAttributeName = propertyNameGetter.get(entry);
if (ldapAttributeName == null) {
return null;
}
return getAttributeData(propertyName, ldapAttributeName.toString(), propertyValueGetter, entry, false, jsonObject);
}
private void setPropertyValue(String propertyName, Setter propertyValueSetter, Object entry,
AttributeData attribute, boolean jsonObject) {
if (attribute == null) {
return;
}
LOG.debug(String.format("LdapProperty: %s, AttributeName: %s, AttributeValue: %s", propertyName,
attribute.getName(), Arrays.toString(attribute.getValues())));
Class<?> parameterType = ReflectHelper.getSetterType(propertyValueSetter);
if (parameterType.equals(String.class)) {
Object value = attribute.getValue();
if (value instanceof Date) {
value = encodeTime((Date) value);
}
propertyValueSetter.set(entry, String.valueOf(value));
} else if (parameterType.equals(Boolean.class) || parameterType.equals(Boolean.TYPE)) {
propertyValueSetter.set(entry, toBooleanValue(attribute));
} else if (parameterType.equals(Integer.class) || parameterType.equals(Integer.TYPE)) {
propertyValueSetter.set(entry, toIntegerValue(attribute));
} else if (parameterType.equals(Long.class) || parameterType.equals(Long.TYPE)) {
propertyValueSetter.set(entry, toLongValue(attribute));
} else if (parameterType.equals(Date.class)) {
propertyValueSetter.set(entry, attribute.getValue() instanceof Date ? (Date) attribute.getValue() : decodeTime(String.valueOf(attribute.getValue())));
} else if (parameterType.equals(String[].class)) {
propertyValueSetter.set(entry, attribute.getStringValues());
} else if (ReflectHelper.assignableFrom(parameterType, List.class)) {
if (jsonObject) {
Object[] values = attribute.getValues();
List<Object> jsonValues = new ArrayList<Object>(values.length);
for (Object value : values) {
Object jsonValue = convertJsonToValue(ReflectHelper.getListType(propertyValueSetter), value);
jsonValues.add(jsonValue);
}
propertyValueSetter.set(entry, jsonValues);
} else {
List<?> resultValues = attributeToTypedList(ReflectHelper.getListType(propertyValueSetter), attribute);
propertyValueSetter.set(entry, resultValues);
}
} else if (ReflectHelper.assignableFrom(parameterType, AttributeEnum.class)) {
try {
propertyValueSetter.set(entry, parameterType.getMethod("resolveByValue", String.class)
.invoke(parameterType.getEnumConstants()[0], attribute.getValue()));
} catch (Exception ex) {
throw new MappingException("Failed to resolve Enum '" + parameterType + "' by value '" + attribute.getValue() + "'", ex);
}
} else if (ReflectHelper.assignableFrom(parameterType, AttributeEnum[].class)) {
Class<?> itemType = parameterType.getComponentType();
Method enumResolveByValue;
try {
enumResolveByValue = itemType.getMethod("resolveByValue", String.class);
} catch (Exception ex) {
throw new MappingException("Failed to resolve Enum '" + parameterType + "' by value '" + Arrays.toString(attribute.getValues()) + "'",
ex);
}
Object[] attributeValues = attribute.getValues();
AttributeEnum[] ldapEnums = (AttributeEnum[]) ReflectHelper.createArray(itemType, attributeValues.length);
for (int i = 0; i < attributeValues.length; i++) {
try {
ldapEnums[i] = (AttributeEnum) enumResolveByValue.invoke(itemType.getEnumConstants()[0],
attributeValues[i]);
} catch (Exception ex) {
throw new MappingException(
"Failed to resolve Enum '" + parameterType + "' by value '" + Arrays.toString(attribute.getValues()) + "'", ex);
}
}
propertyValueSetter.set(entry, ldapEnums);
} else if (jsonObject) {
Object stringValue = attribute.getValue();
Object jsonValue = convertJsonToValue(parameterType, stringValue);
propertyValueSetter.set(entry, jsonValue);
} else {
throw new MappingException("Entry property '" + propertyName
+ "' should has setter with String, Boolean, Integer, Long, Date, String[], List<String>, AttributeEnum or AttributeEnum[]"
+ " parameter type or has annotation JsonObject");
}
}
private List<?> attributeToTypedList(Class<?> listType, AttributeData attributeData) {
if (listType.equals(String.class)) {
ArrayList<String> result = new ArrayList<String>();
for (Object value : attributeData.getValues()) {
String resultValue;
if (value instanceof Date) {
resultValue = encodeTime((Date) value);
} else {
resultValue = String.valueOf(value);
}
result.add(resultValue);
}
return result;
}
return Arrays.asList(attributeData.getValues());
}
private Boolean toBooleanValue(AttributeData attribute) {
Boolean propertyValue = null;
Object propertyValueObject = attribute.getValue();
if (propertyValueObject != null) {
if (propertyValueObject instanceof Boolean) {
propertyValue = (Boolean) propertyValueObject;
} else {
propertyValue = Boolean.valueOf(String.valueOf(propertyValueObject));
}
}
return propertyValue;
}
private Integer toIntegerValue(AttributeData attribute) {
Integer propertyValue = null;
Object propertyValueObject = attribute.getValue();
if (propertyValueObject != null) {
if (propertyValueObject instanceof Long) {
propertyValue = (Integer) propertyValueObject;
} else {
propertyValue = Integer.valueOf(String.valueOf(propertyValueObject));
}
}
return propertyValue;
}
private Long toLongValue(AttributeData attribute) {
Long propertyValue = null;
Object propertyValueObject = attribute.getValue();
if (propertyValueObject != null) {
if (propertyValueObject instanceof Long) {
propertyValue = (Long) propertyValueObject;
} else {
propertyValue = Long.valueOf(String.valueOf(propertyValueObject));
}
}
return propertyValue;
}
protected Object convertJsonToValue(Class<?> parameterType, Object propertyValue) {
try {
Object jsonValue = JSON_OBJECT_MAPPER.readValue(String.valueOf(propertyValue), parameterType);
return jsonValue;
} catch (Exception ex) {
LOG.error("Failed to convert json value '{}' to object `{}`", propertyValue, parameterType, ex);
throw new MappingException(String.format("Failed to convert json value '%s' to object of type %s",
propertyValue, parameterType));
}
}
private Object getListItem(String propertyName, Setter propertyNameSetter, Setter propertyValueSetter,
Setter entryPropertyMultivaluedSetter, Class<?> classType, AttributeData attribute) {
if (attribute == null) {
return null;
}
Object result;
try {
result = ReflectHelper.createObjectByDefaultConstructor(classType);
} catch (Exception ex) {
throw new MappingException(String.format("Entry %s should has default constructor", classType));
}
propertyNameSetter.set(result, attribute.getName());
setPropertyValue(propertyName, propertyValueSetter, result, attribute, false);
if ((entryPropertyMultivaluedSetter != null) && (attribute.getMultiValued() != null)) {
entryPropertyMultivaluedSetter.set(result, attribute.getMultiValued());
}
return result;
}
protected <T> Object getDNValue(Object entry) {
Class<?> entryClass = entry.getClass();
return getDNValue(entry, entryClass);
}
protected <T> Object getDNValue(Object entry, Class<T> entryClass) {
// Check if entry has DN property
String dnProperty = getDNPropertyName(entryClass);
// Get DN value
Getter dnGetter = getGetter(entryClass, dnProperty);
if (dnGetter == null) {
throw new MappingException("Entry should has getter for property " + dnProperty);
}
Object dnValue = dnGetter.get(entry);
if (StringHelper.isEmptyString(dnValue)) {
throw new MappingException("Entry should has not null base DN property value");
}
return dnValue;
}
private <T> String getEntryKey(T entry, boolean caseSensetive, Getter[] propertyGetters) {
StringBuilder sb = new StringBuilder("key");
for (Getter getter : propertyGetters) {
sb.append("__").append(getter.get(entry));
}
if (caseSensetive) {
return sb.toString();
} else {
return sb.toString().toLowerCase();
}
}
private Map<String, AttributeData> getAttributesDataMap(List<AttributeData> attributesData) {
Map<String, AttributeData> result = new HashMap<String, AttributeData>();
for (AttributeData attributeData : attributesData) {
result.put(attributeData.getName(), attributeData);
}
return result;
}
private String getEntryKey(Object dnValue, boolean caseSensetive, List<PropertyAnnotation> propertiesAnnotations,
List<AttributeData> attributesData) {
StringBuilder sb = new StringBuilder("_HASH__").append((String.valueOf(dnValue)).toLowerCase()).append("__");
List<String> processedProperties = new ArrayList<String>();
Map<String, AttributeData> attributesDataMap = getAttributesDataMap(attributesData);
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
Annotation ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute == null) {
continue;
}
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertiesAnnotation.getPropertyName();
}
processedProperties.add(ldapAttributeName);
String[] values = null;
AttributeData attributeData = attributesDataMap.get(ldapAttributeName);
if ((attributeData != null) && (attributeData.getValues() != null)) {
values = attributeData.getStringValues();
Arrays.sort(values);
}
addPropertyWithValuesToKey(sb, ldapAttributeName, values);
}
for (AttributeData attributeData : attributesData) {
if (processedProperties.contains(attributeData.getName())) {
continue;
}
addPropertyWithValuesToKey(sb, attributeData.getName(), attributeData.getStringValues());
}
if (caseSensetive) {
return sb.toString();
} else {
return sb.toString().toLowerCase();
}
}
private void addPropertyWithValuesToKey(StringBuilder sb, String propertyName, String[] values) {
sb.append(':').append(propertyName).append('=');
if (values == null) {
sb.append("null");
} else {
if (values.length == 1) {
sb.append(values[0]);
} else {
String[] tmpValues = values.clone();
Arrays.sort(tmpValues);
for (int i = 0; i < tmpValues.length; i++) {
sb.append(tmpValues[i]);
if (i < tmpValues.length - 1) {
sb.append(';');
}
}
}
}
}
@Override
public int getHashCode(Object entry) {
if (entry == null) {
throw new MappingException("Entry to persist is null");
}
// Check entry class
Class<?> entryClass = entry.getClass();
checkEntryClass(entryClass, false);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
String key = getEntryKey(dnValue, false, propertiesAnnotations, attributes);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Entry key HashCode is: %s", key.hashCode()));
}
return key.hashCode();
}
protected byte[][] toBinaryValues(String[] attributeValues) {
byte[][] binaryValues = new byte[attributeValues.length][];
for (int i = 0; i < attributeValues.length; i++) {
binaryValues[i] = Base64.decodeBase64(attributeValues[i]);
}
return binaryValues;
}
protected <T> Filter createFilterByEntry(Object entry, Class<T> entryClass, List<AttributeData> attributes) {
Filter[] attributesFilters = createAttributesFilter(attributes);
Filter attributesFilter = null;
if (attributesFilters != null) {
attributesFilter = Filter.createANDFilter(attributesFilters);
}
String[] objectClasses = getObjectClasses(entry, entryClass);
return addObjectClassFilter(attributesFilter, objectClasses);
}
protected Filter[] createAttributesFilter(List<AttributeData> attributes) {
if ((attributes == null) || (attributes.size() == 0)) {
return null;
}
List<Filter> results = new ArrayList<Filter>(attributes.size());
for (AttributeData attribute : attributes) {
String attributeName = attribute.getName();
for (Object value : attribute.getValues()) {
Filter filter = Filter.createEqualityFilter(attributeName, value);
if ((attribute.getMultiValued() != null) && attribute.getMultiValued()) {
filter.multiValued();
}
results.add(filter);
}
}
return results.toArray(new Filter[results.size()]);
}
protected Filter addObjectClassFilter(Filter filter, String[] objectClasses) {
if (objectClasses.length == 0) {
return filter;
}
Filter[] objectClassFilter = new Filter[objectClasses.length];
for (int i = 0; i < objectClasses.length; i++) {
objectClassFilter[i] = Filter.createEqualityFilter(OBJECT_CLASS, objectClasses[i]).multiValued();
}
Filter searchFilter = Filter.createANDFilter(objectClassFilter);
if (filter != null) {
searchFilter = Filter.createANDFilter(Filter.createANDFilter(objectClassFilter), filter);
}
return searchFilter;
}
protected boolean isMultiValued(Class<?> parameterType) {
if (parameterType == null) {
return false;
}
boolean isMultiValued = parameterType.equals(String[].class) || ReflectHelper.assignableFrom(parameterType, List.class) || ReflectHelper.assignableFrom(parameterType, AttributeEnum[].class);
return isMultiValued;
}
protected abstract Date decodeTime(String date);
protected abstract String encodeTime(Date date);
protected static final class PropertyComparator<T> implements Comparator<T>, Serializable {
private static final long serialVersionUID = 574848841116711467L;
private Getter[][] propertyGetters;
private boolean caseSensetive;
private PropertyComparator(Getter[][] propertyGetters, boolean caseSensetive) {
this.propertyGetters = propertyGetters;
this.caseSensetive = caseSensetive;
}
@Override
public int compare(T entry1, T entry2) {
if ((entry1 == null) && (entry2 == null)) {
return 0;
}
if ((entry1 == null) && (entry2 != null)) {
return -1;
} else if ((entry1 != null) && (entry2 == null)) {
return 1;
}
int result = 0;
for (Getter[] curPropertyGetters : propertyGetters) {
result = compare(entry1, entry2, curPropertyGetters);
if (result != 0) {
break;
}
}
return result;
}
public int compare(T entry1, T entry2, Getter[] propertyGetters) {
Object value1 = ReflectHelper.getPropertyValue(entry1, propertyGetters);
Object value2 = ReflectHelper.getPropertyValue(entry2, propertyGetters);
if ((value1 == null) && (value2 == null)) {
return 0;
}
if ((value1 == null) && (value2 != null)) {
return -1;
} else if ((value1 != null) && (value2 == null)) {
return 1;
}
if (value1 instanceof Date) {
return ((Date) value1).compareTo((Date) value2);
} else if (value1 instanceof Integer) {
return ((Integer) value1).compareTo((Integer) value2);
} else if (value1 instanceof String && value2 instanceof String) {
if (caseSensetive) {
return ((String) value1).compareTo((String) value2);
} else {
return ((String) value1).toLowerCase().compareTo(((String) value2).toLowerCase());
}
}
return 0;
}
}
protected static final class LineLenghtComparator<T> implements Comparator<T>, Serializable {
private static final long serialVersionUID = 575848841116711467L;
private boolean ascending;
public LineLenghtComparator(boolean ascending) {
this.ascending = ascending;
}
@Override
public int compare(T entry1, T entry2) {
if ((entry1 == null) && (entry2 == null)) {
return 0;
}
if ((entry1 == null) && (entry2 != null)) {
return -1;
} else if ((entry1 != null) && (entry2 == null)) {
return 1;
}
int result = entry1.toString().length() - entry2.toString().length();
if (ascending) {
return result;
} else {
return -result;
}
}
}
}
|
package plugins.ShareWiki.webui;
import java.io.IOException;
import java.net.URI;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.BufferedReader;
import java.io.StringReader;
import plugins.ShareWiki.Freesite;
import plugins.ShareWiki.Plugin;
import freenet.clients.http.InfoboxNode;
import freenet.clients.http.PageMaker;
import freenet.clients.http.PageNode;
import freenet.clients.http.Toadlet;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.l10n.BaseL10n;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
public class EditToadlet extends Toadlet {
private PluginRespirator pr;
private PageMaker pageMaker;
private BaseL10n l10n;
protected EditToadlet() {
super(null);
pr = Plugin.instance.pluginRespirator;
pageMaker = pr.getPageMaker();
l10n = Plugin.instance.l10n;
}
@Override
public String path() {
return "/ShareWiki/Edit/";
}
// Gets called by the freenet node
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
// Get freesite, or return to the menu
String[] split = uri.getPath().split("/");
int siteId = -1;
try {
siteId = Integer.parseInt(split[3]);
} catch (Exception e) {
}
Freesite c = Plugin.instance.database.getFreesiteWithUniqueKey(siteId);
if (c == null) {
writeTemporaryRedirect(ctx, "Redirecting...", "/ShareWiki/");
return;
}
PageNode pageNode = pageMaker.getPageNode(l10n.getString("ShareWiki.Menu.Name"), ctx);
HTMLNode editForm = pr.addFormChild(pageNode.content,"/ShareWiki/Edit/" + siteId, "editForm");
addNodes(editForm,c.getName(),c.getDescription(),c.getText(),c.getCSS(), c.getRequestSSK(),c.getInsertSSK());
String ret = pageNode.outer.generate();
writeHTMLReply(ctx, 200, "OK", ret);
}
private void addNodes( HTMLNode form, String name, String desc, String text, String css, String rkey, String ikey) {
String[] attrs;
String[] vals;
InfoboxNode editBox = pageMaker.getInfobox(l10n.getString("ShareWiki.Edit.Header"));
form.addChild(editBox.outer);
// Menu link
HTMLNode quickLinks = editBox.content.addChild("p");
quickLinks.addChild("a", "href", "/ShareWiki/", l10n.getString("ShareWiki.Edit.MenuLink"));
// Buttons above
HTMLNode topBtnDiv = editBox.content.addChild("p");
attrs = new String[] { "type", "name", "value" };
vals = new String[] { "submit", "saveBtn",l10n.getString("ShareWiki.Edit.SaveBtn") };
topBtnDiv.addChild("input", attrs, vals);
attrs = new String[] { "type", "name", "value" };
vals = new String[] { "submit", "previewBtn", l10n.getString("ShareWiki.Edit.PreviewBtn") };
topBtnDiv.addChild("input", attrs, vals);
attrs = new String[] { "type", "name", "value" };
vals = new String[] { "submit", "preprocessBtn",l10n.getString("ShareWiki.Edit.PreprocessBtn") };
topBtnDiv.addChild("input", attrs, vals);
// Edit boxes
HTMLNode nameDiv = editBox.content.addChild("p");
HTMLNode nameSpan = nameDiv.addChild("span");
nameSpan.addChild("span",l10n.getString("ShareWiki.Edit.Name"));
nameSpan.addChild("br");
attrs = new String[] { "type", "size", "name", "value" };
vals = new String[] { "text", "80", "nameInput", name };
nameDiv.addChild("input", attrs, vals);
HTMLNode descDiv = editBox.content.addChild("p");
HTMLNode descSpan = descDiv.addChild("span");
descSpan.addChild("span",
l10n.getString("ShareWiki.Edit.Description"));
descSpan.addChild("br");
attrs = new String[] { "name", "rows", "cols", "style" };
vals = new String[] { "descInput", "3", "80", "font-size: medium;" };
descDiv.addChild("textarea", attrs, vals, desc);
HTMLNode textDiv = editBox.content.addChild("p");
HTMLNode textSpan = textDiv.addChild("span");
textSpan.addChild("span",l10n.getString("ShareWiki.Edit.Text"));
textSpan.addChild("br");
attrs = new String[] { "name", "rows", "cols", "style" };
vals = new String[] { "textInput", "20", "80", "font-size: medium;" };
textDiv.addChild("textarea", attrs, vals, text);
// Syntax
HTMLNode syntaxHelpNode = editBox.content.addChild("p",l10n.getString("ShareWiki.Edit.TextSyntax"));
HTMLNode syntaxTable = syntaxHelpNode.addChild("table");
HTMLNode syntaxHelp = syntaxTable.addChild("tr");
HTMLNode syntaxHelpTextile = syntaxHelp.addChild("td", "h2. headline");
HTMLNode syntaxHelpHtml = syntaxHelp.addChild("td");
HTMLNode syntaxHelpHtmlContent = syntaxHelpHtml.addChild("h2", "headline");
syntaxHelp = syntaxTable.addChild("tr");
syntaxHelpTextile = syntaxHelp.addChild("td", "[\"linkname\":/USK@key/name/N/filepath]");
syntaxHelpHtml = syntaxHelp.addChild("td");
syntaxHelpHtmlContent = syntaxHelpHtml.addChild("a", "href", "/USK@key/name/N/filepath", "linkname");
syntaxHelp = syntaxTable.addChild("tr");
syntaxHelpTextile = syntaxHelp.addChild("td", "- list item");
syntaxHelpHtml = syntaxHelp.addChild("td");
syntaxHelpHtmlContent = syntaxHelpHtml.addChild("ul");
HTMLNode syntaxHelpHtmlContentInner = syntaxHelpHtml.addChild("li", "list item");
syntaxHelp = syntaxTable.addChild("tr");
syntaxHelpTextile = syntaxHelp.addChild("td", "{toc}");
syntaxHelpHtml = syntaxHelp.addChild("td", "(inserts table of contents)");
syntaxHelp = syntaxTable.addChild("tr");
syntaxHelpTextile = syntaxHelp.addChild("td", "_emphasized_");
syntaxHelpHtml = syntaxHelp.addChild("td");
syntaxHelpHtmlContent = syntaxHelpHtml.addChild("em", "emphasized");
syntaxHelp = syntaxTable.addChild("tr");
syntaxHelpTextile = syntaxHelp.addChild("td", "@code@");
syntaxHelpHtml = syntaxHelp.addChild("td");
syntaxHelpHtmlContent = syntaxHelpHtml.addChild("code", "code");
syntaxHelp = syntaxTable.addChild("tr");
syntaxHelpTextile = syntaxHelp.addChild("td").addChild("pre", "bc. code block\ncontinuing");
syntaxHelpHtml = syntaxHelp.addChild("td");
syntaxHelpHtmlContent = syntaxHelpHtml.addChild("pre").addChild("code", "code block\ncontinuing");
syntaxHelp = syntaxTable.addChild("tr");
syntaxHelpTextile = syntaxHelp.addChild("td").addChild("pre", "bq. quote\ncontinued");
syntaxHelpHtml = syntaxHelp.addChild("td");
syntaxHelpHtmlContent = syntaxHelpHtml.addChild("blockquote", "quote\ncontinued");
HTMLNode cssDiv = editBox.content.addChild("p");
HTMLNode cssSpan = cssDiv.addChild("span");
cssSpan.addChild("span", l10n.getString("ShareWiki.Edit.CSS"));
cssSpan.addChild("br");
attrs = new String[] { "name", "rows", "cols", "style" };
vals = new String[] { "cssInput", "15", "80", "font-size: medium;" };
try {
cssDiv.addChild("textarea", attrs, vals, css);
} catch (Exception e) {
cssDiv.addChild("textarea", attrs, vals, "");
}
// Buttons below
HTMLNode bottomBtnDiv = editBox.content.addChild("p");
attrs = new String[] { "type", "name", "value" };
vals = new String[] { "submit", "saveBtn",
l10n.getString("ShareWiki.Edit.SaveBtn")
};
bottomBtnDiv.addChild("input", attrs, vals);
attrs = new String[] { "type", "name", "value" };
vals = new String[] { "submit", "previewBtn",
l10n.getString("ShareWiki.Edit.PreviewBtn")
};
bottomBtnDiv.addChild("input", attrs, vals);
// Insert Key
InfoboxNode advBox = pageMaker.getInfobox(l10n.getString("ShareWiki.Edit.Advanced"));
form.addChild(advBox.outer);
HTMLNode backup = advBox.content.addChild("p");
backup.addChild("span",l10n.getString("ShareWiki.Edit.InsertKey"));
backup.addChild("br");
attrs = new String[] { "type", "size", "name", "value" };
vals = new String[] { "text", "100", "insertKeyInput", ikey };
backup.addChild("input", attrs, vals);
// Request Key
backup.addChild("br");
backup.addChild("span",l10n.getString("ShareWiki.Edit.RequestKey"));
backup.addChild("br");
attrs = new String[] { "type", "size", "name", "value" };
vals = new String[] { "text", "100", "requestKeyInput", rkey };
backup.addChild("input", attrs, vals);
}
// Gets called by the freenet node
public void handleMethodPOST(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
// Get freesite, or display an error message
String[] split = uri.getPath().split("/");
int siteId = -1;
try {
siteId = Integer.parseInt(split[3]);
} catch (Exception e) {
}
Freesite c = Plugin.instance.database.getFreesiteWithUniqueKey(siteId);
if (c == null) {
writeTemporaryRedirect(ctx, "Redirecting...", "/ShareWiki/Error/");
return;
}
// Perform action
if (req.isPartSet("saveBtn") || req.isPartSet("previewBtn")||req.isPartSet("preprocessBtn")) {
String name = req.getPartAsStringFailsafe("nameInput", 1000).trim(); // 1kB
String desc = req.getPartAsStringFailsafe("descInput", 10000).trim(); // 10kB
String text = req.getPartAsStringFailsafe("textInput", 1000000000).trim(); // 1GB
String css = req.getPartAsStringFailsafe("cssInput", 1000000000).trim(); // 1GB
String ikey= req.getPartAsStringFailsafe("insertKeyInput", 1000).trim();
String rkey= req.getPartAsStringFailsafe("requestKeyInput", 1000).trim();
Plugin.instance.logger.putstr("POST values:");
Plugin.instance.logger.putstr(" name=\""+name+"\"");
Plugin.instance.logger.putstr(" desc=\""+desc+"\"");
//Plugin.instance.logger.putstr(" text=\""+text+"\"");
//Plugin.instance.logger.putstr(" css=\""+css+"\"");
Plugin.instance.logger.putstr(" ikey=\""+ikey+"\"");
Plugin.instance.logger.putstr(" rkey=\""+rkey+"\"");
boolean changed = false;
// new keys
if(! ikey.equals(c.getInsertSSK()) || rkey.equals(c.getRequestSSK()) ) {
c.setInsertSSK(ikey);
c.setRequestSSK(rkey);
changed= true;
}
// Update name, text, etc
if (name != null && name.length() > 0 && !name.equals(c.getName())) {
c.setName(name);
changed = true;
}
if (desc != null && !desc.equals(c.getDescription())) {
c.setDescription(desc);
changed = true;
}
if (text != null && text.length() > 0 && !text.equals(c.getText()) ) {
c.setText(text);
Plugin.instance.logger.putstr("Source changed!");
changed=true;
}
if (text != null && text.length() > 0 && req.isPartSet("preprocessBtn") ) {
String pstr=preprocess(text);
if(!c.getText().equals(pstr)) {
c.setText(pstr);
changed=true;
}
}
if (css!= null && !css.equals(c.getCSS())) {
c.setCSS(css);
changed = true;
}
if (changed) {
c.setL10nStatus("Status.Modified");
Plugin.instance.database.save();
}
}
if (req.isPartSet("previewBtn")) {
writeTemporaryRedirect(ctx, "Redirecting...", "/ShareWiki/Preview/" + siteId + "/index.html");
}
writeTemporaryRedirect(ctx, "Redirecting...", "/ShareWiki/Edit/" + siteId);
}
private String preprocess(String text) {
BufferedReader br=new BufferedReader(new StringReader(text));
StringBuffer builder=new StringBuffer();
try {
int lcount=1;
String line="";
while((line=br.readLine())!= null) {
Plugin.instance.logger.putstr(lcount +"\t"+line);
// Highlight Frost sender
Pattern frostheader= Pattern.compile("^[-]{5}(.*)[-]{5}(.*)[-]{5}$");
Matcher m5=frostheader.matcher(line);
line=m5.replaceAll("p(from). \u2013\u2013\u2013\u2013\u2013 $1 \u2013\u2013\u2013\u2013\u2013 $2 \u2013\u2013\u2013\u2013\u2013");
// Only one key per line allowed. Everything until the end of line is seen as part of the Freenet key
Pattern imgpat = Pattern.compile("^(CHK|USK|SSK|KSK)@([^/]*)/(.*\\.)(jpg|JPG|jpeg|JPEG|gif|GIF|png|PNG)$");
Pattern linkpat = Pattern.compile("^(CHK|USK|SSK|KSK)@([^/]*)/(.*)$");
// Image
Matcher m1=imgpat.matcher(line);
line=m1.replaceAll("!(preview)/$1@$2/$3$4!");
// Link
Matcher m2=linkpat.matcher(line);
line=m2.replaceAll("\"$3\":/$1@$2/$3" );
/*
* All keys should have been replaced by "<name>":/<key> or !(preview)/<key>! now
*/
// Remove %20 from file names
Pattern linkdesc = Pattern.compile("(\".*\")(?=:/..K@)");
Matcher m3=linkdesc.matcher(line);
if(m3.find()) {
String desc=m3.group();
//Plugin.instance.logger.putstr("Unescaping String "+ desc);
line=m3.replaceFirst(desc.replaceAll("%20"," "));
}
// Add %20 to key paths. Otherwise Textile will end the link at the first whitespace
Pattern keypath = Pattern.compile("((?<=--8/)(.*))|((?<=CAAE/)(.*))");
Matcher m4=keypath.matcher(line);
if(m4.find()) {
String esckey=m4.group();
//Plugin.instance.logger.putstr("Escaping String "+ esckey);
line=m4.replaceFirst(esckey.replaceAll("\\ ", "%20"));
}
line=line.replaceAll("%28","(");
line=line.replaceAll("%29",")");
line=line.replaceAll("%5b","[");
line=line.replaceAll("%5d","]");
line=line.replaceAll("http://[^/]+:8888/","");
builder.append(line + "\n");
//Plugin.instance.logger.putstr(lcount +"->\t"+line);
lcount++;
}
} catch (IOException e) {
Plugin.instance.logger.putstr(e.getMessage());
}
return builder.toString();
}
}
|
package org.gluu.persist.impl;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.codec.binary.Base64;
import org.codehaus.jackson.map.ObjectMapper;
import org.gluu.persist.PersistenceEntryManager;
import org.gluu.persist.exception.EntryPersistenceException;
import org.gluu.persist.exception.InvalidArgumentException;
import org.gluu.persist.exception.MappingException;
import org.gluu.persist.model.AttributeData;
import org.gluu.persist.model.AttributeDataModification;
import org.gluu.persist.model.AttributeDataModification.AttributeModificationType;
import org.gluu.persist.model.SearchScope;
import org.gluu.persist.reflect.property.Getter;
import org.gluu.persist.reflect.property.PropertyAnnotation;
import org.gluu.persist.reflect.property.Setter;
import org.gluu.persist.reflect.util.ReflectHelper;
import org.gluu.search.filter.Filter;
import org.gluu.persist.annotation.AttributeName;
import org.gluu.persist.annotation.AttributesList;
import org.gluu.persist.annotation.CustomObjectClass;
import org.gluu.persist.annotation.DN;
import org.gluu.persist.annotation.DataEntry;
import org.gluu.persist.annotation.AttributeEnum;
import org.gluu.persist.annotation.JsonObject;
import org.gluu.persist.annotation.ObjectClass;
import org.gluu.persist.annotation.SchemaEntry;
import org.gluu.util.ArrayHelper;
import org.gluu.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class BaseEntryManager implements PersistenceEntryManager {
private static final Logger LOG = LoggerFactory.getLogger(BaseEntryManager.class);
private static final Class<?>[] LDAP_ENTRY_TYPE_ANNOTATIONS = { DataEntry.class, SchemaEntry.class,
ObjectClass.class };
private static final Class<?>[] LDAP_ENTRY_PROPERTY_ANNOTATIONS = { AttributeName.class, AttributesList.class,
JsonObject.class };
private static final Class<?>[] LDAP_CUSTOM_OBJECT_CLASS_PROPERTY_ANNOTATION = { CustomObjectClass.class };
private static final Class<?>[] LDAP_DN_PROPERTY_ANNOTATION = { DN.class };
public static final String OBJECT_CLASS = "objectClass";
public static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final Class<?>[] GROUP_BY_ALLOWED_DATA_TYPES = { String.class, Date.class, Integer.class,
AttributeEnum.class };
private static final Class<?>[] SUM_BY_ALLOWED_DATA_TYPES = { int.class, Integer.class, float.class, Float.class,
double.class, Double.class };
private final Map<String, List<PropertyAnnotation>> classAnnotations = new HashMap<String, List<PropertyAnnotation>>();
private final Map<String, Getter> classGetters = new HashMap<String, Getter>();
private final Map<String, Setter> classSetters = new HashMap<String, Setter>();
private static Object CLASS_ANNOTATIONS_LOCK = new Object();
private static Object CLASS_SETTERS_LOCK = new Object();
private static Object CLASS_GETTERS_LOCK = new Object();
private static final ObjectMapper JSON_OBJECT_MAPPER = new ObjectMapper();
protected static final String[] NO_STRINGS = new String[0];
protected static final Object[] NO_OBJECTS = new Object[0];
protected static final Comparator<String> LINE_LENGHT_COMPARATOR = new LineLenghtComparator<String>(false);
protected static final int DEFAULT_PAGINATION_SIZE = 100;
@Override
public void persist(Object entry) {
if (entry == null) {
throw new MappingException("Entry to persist is null");
}
// Check entry class
Class<?> entryClass = entry.getClass();
checkEntryClass(entryClass, false);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
// Add object classes
String[] objectClasses = getObjectClasses(entry, entryClass);
attributes.add(new AttributeData(OBJECT_CLASS, objectClasses));
LOG.debug(String.format("LDAP attributes for persist: %s", attributes));
persist(dnValue.toString(), attributes);
}
protected abstract void persist(String dn, List<AttributeData> attributes);
@Override
@SuppressWarnings("unchecked")
public <T> List<T> findEntries(Object entry, int count) {
if (entry == null) {
throw new MappingException("Entry to find is null");
}
// Check entry class
Class<T> entryClass = (Class<T>) entry.getClass();
checkEntryClass(entryClass, false);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
Filter searchFilter = createFilterByEntry(entry, entryClass, attributes);
return findEntries(dnValue.toString(), entryClass, searchFilter, SearchScope.SUB, null, 0, count,
DEFAULT_PAGINATION_SIZE);
}
@Override
public <T> List<T> findEntries(Object entry) {
return findEntries(entry, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter) {
return findEntries(baseDN, entryClass, filter, SearchScope.SUB, null, null, 0, 0, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter, int count) {
return findEntries(baseDN, entryClass, filter, SearchScope.SUB, null, null, 0, count, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter, String[] ldapReturnAttributes) {
return findEntries(baseDN, entryClass, filter, SearchScope.SUB, ldapReturnAttributes, null, 0, 0, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter, String[] ldapReturnAttributes,
int count) {
return findEntries(baseDN, entryClass, filter, SearchScope.SUB, ldapReturnAttributes, null, 0, count, 0);
}
@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter, SearchScope scope,
String[] ldapReturnAttributes, int start, int count, int chunkSize) {
return findEntries(baseDN, entryClass, filter, scope, ldapReturnAttributes, null, start, count, chunkSize);
}
@SuppressWarnings("unchecked")
public <T> int countEntries(Object entry) {
if (entry == null) {
throw new MappingException("Entry to count is null");
}
// Check entry class
Class<T> entryClass = (Class<T>) entry.getClass();
checkEntryClass(entryClass, false);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
Filter searchFilter = createFilterByEntry(entry, entryClass, attributes);
return countEntries(dnValue.toString(), entryClass, searchFilter);
}
@SuppressWarnings("unchecked")
protected <T> T merge(T entry, boolean isSchemaUpdate, AttributeModificationType schemaModificationType) {
if (entry == null) {
throw new MappingException("Entry to persist is null");
}
Class<?> entryClass = entry.getClass();
checkEntryClass(entryClass, isSchemaUpdate);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributesToPersist = getAttributesListForPersist(entry, propertiesAnnotations);
Map<String, AttributeData> attributesToPersistMap = getAttributesMap(attributesToPersist);
// Load entry
List<AttributeData> attributesFromLdap;
if (isSchemaUpdate) {
// If it's schema modification request we don't need to load
// attributes from LDAP
attributesFromLdap = new ArrayList<AttributeData>();
} else {
List<String> currentLdapReturnAttributesList = getAttributesList(entry, propertiesAnnotations, false);
currentLdapReturnAttributesList.add("objectClass");
attributesFromLdap = find(dnValue.toString(), currentLdapReturnAttributesList.toArray(EMPTY_STRING_ARRAY));
}
Map<String, AttributeData> attributesFromLdapMap = getAttributesMap(attributesFromLdap);
// Prepare list of modifications
// Process properties with Attribute annotation
List<AttributeDataModification> attributeDataModifications = collectAttributeModifications(
propertiesAnnotations, attributesToPersistMap, attributesFromLdapMap, isSchemaUpdate,
schemaModificationType);
updateMergeChanges(entry, isSchemaUpdate, entryClass, attributesFromLdapMap, attributeDataModifications);
LOG.debug(String.format("LDAP attributes for merge: %s", attributeDataModifications));
merge(dnValue.toString(), attributeDataModifications);
return (T) find(entryClass, dnValue.toString(), null, propertiesAnnotations);
}
protected abstract <T> void updateMergeChanges(T entry, boolean isSchemaUpdate, Class<?> entryClass,
Map<String, AttributeData> attributesFromLdapMap,
List<AttributeDataModification> attributeDataModifications);
protected List<AttributeDataModification> collectAttributeModifications(
List<PropertyAnnotation> propertiesAnnotations, Map<String, AttributeData> attributesToPersistMap,
Map<String, AttributeData> attributesFromLdapMap, boolean isSchemaUpdate,
AttributeModificationType schemaModificationType) {
List<AttributeDataModification> attributeDataModifications = new ArrayList<AttributeDataModification>();
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute != null) {
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertyName;
}
ldapAttributeName = ldapAttributeName.toLowerCase();
AttributeData attributeToPersist = attributesToPersistMap.get(ldapAttributeName);
AttributeData attributeFromLdap = attributesFromLdapMap.get(ldapAttributeName);
// Remove processed attributes
attributesToPersistMap.remove(ldapAttributeName);
attributesFromLdapMap.remove(ldapAttributeName);
AttributeName ldapAttributeAnnotation = (AttributeName) ldapAttribute;
if (ldapAttributeAnnotation.ignoreDuringUpdate()) {
continue;
}
if (attributeFromLdap != null && attributeToPersist != null) {
// Modify DN entry attribute in DS
if (!attributeFromLdap.equals(attributeToPersist)) {
if (isEmptyAttributeValues(attributeToPersist) && !ldapAttributeAnnotation.updateOnly()) {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REMOVE, null, attributeFromLdap));
} else {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REPLACE, attributeToPersist, attributeFromLdap));
}
}
} else if ((attributeFromLdap == null) && (attributeToPersist != null)) {
// Add entry attribute or change schema
if (isSchemaUpdate && (attributeToPersist.getValue() == null
&& Arrays.equals(attributeToPersist.getValues(), new Object[] {}))) {
continue;
}
AttributeModificationType modType = isSchemaUpdate ? schemaModificationType
: AttributeModificationType.ADD;
if (AttributeModificationType.ADD.equals(modType)) {
if (!isEmptyAttributeValues(attributeToPersist)) {
attributeDataModifications.add(
new AttributeDataModification(AttributeModificationType.ADD, attributeToPersist));
}
} else {
attributeDataModifications.add(new AttributeDataModification(AttributeModificationType.REMOVE,
null, attributeToPersist));
}
} else if ((attributeFromLdap != null) && (attributeToPersist == null)) {
// Remove if attribute not marked as ignoreDuringRead = true
// or updateOnly = true
if (!ldapAttributeAnnotation.ignoreDuringRead() && !ldapAttributeAnnotation.updateOnly()) {
attributeDataModifications.add(new AttributeDataModification(AttributeModificationType.REMOVE,
null, attributeFromLdap));
}
}
}
}
// Process properties with @AttributesList annotation
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
Annotation ldapAttribute;
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributesList.class);
if (ldapAttribute != null) {
Map<String, AttributeName> ldapAttributesConfiguration = new HashMap<String, AttributeName>();
for (AttributeName ldapAttributeConfiguration : ((AttributesList) ldapAttribute)
.attributesConfiguration()) {
ldapAttributesConfiguration.put(ldapAttributeConfiguration.name(), ldapAttributeConfiguration);
}
// Prepare attributes for removal
for (AttributeData attributeFromLdap : attributesFromLdapMap.values()) {
String attributeName = attributeFromLdap.getName();
if (OBJECT_CLASS.equalsIgnoreCase(attributeName)) {
continue;
}
AttributeName ldapAttributeConfiguration = ldapAttributesConfiguration.get(attributeName);
if ((ldapAttributeConfiguration != null) && ldapAttributeConfiguration.ignoreDuringUpdate()) {
continue;
}
if (!attributesToPersistMap.containsKey(attributeName.toLowerCase())) {
// Remove if attribute not marked as ignoreDuringRead =
// true
if ((ldapAttributeConfiguration == null) || ((ldapAttributeConfiguration != null)
&& !ldapAttributeConfiguration.ignoreDuringRead())) {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REMOVE, null, attributeFromLdap));
}
}
}
// Prepare attributes for adding and replace
for (AttributeData attributeToPersist : attributesToPersistMap.values()) {
String attributeName = attributeToPersist.getName();
AttributeName ldapAttributeConfiguration = ldapAttributesConfiguration.get(attributeName);
if ((ldapAttributeConfiguration != null) && ldapAttributeConfiguration.ignoreDuringUpdate()) {
continue;
}
AttributeData attributeFromLdap = attributesFromLdapMap.get(attributeName.toLowerCase());
if (attributeFromLdap == null) {
// Add entry attribute or change schema
AttributeModificationType modType = isSchemaUpdate ? schemaModificationType
: AttributeModificationType.ADD;
if (AttributeModificationType.ADD.equals(modType)) {
if (!isEmptyAttributeValues(attributeToPersist)) {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.ADD, attributeToPersist));
}
} else {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REMOVE, null, attributeToPersist));
}
} else if ((attributeFromLdap != null)
&& (Arrays.equals(attributeToPersist.getValues(), new String[] {}))) {
attributeDataModifications.add(new AttributeDataModification(AttributeModificationType.REMOVE,
null, attributeFromLdap));
} else {
if (!attributeFromLdap.equals(attributeToPersist)) {
if (isEmptyAttributeValues(attributeToPersist)
&& !ldapAttributeConfiguration.updateOnly()) {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REMOVE, null, attributeFromLdap));
} else {
attributeDataModifications.add(new AttributeDataModification(
AttributeModificationType.REPLACE, attributeToPersist, attributeFromLdap));
}
}
}
}
}
}
return attributeDataModifications;
}
protected boolean isEmptyAttributeValues(AttributeData attributeData) {
Object[] attributeToPersistValues = attributeData.getValues();
return ArrayHelper.isEmpty(attributeToPersistValues)
|| ((attributeToPersistValues.length == 1) && StringHelper.isEmpty(String.valueOf(attributeToPersistValues[0])));
}
protected abstract void merge(String dn, List<AttributeDataModification> attributeDataModifications);
protected abstract void remove(String dn);
@Override
public boolean contains(Object entry) {
if (entry == null) {
throw new MappingException("Entry to persist is null");
}
// Check entry class
Class<?> entryClass = entry.getClass();
checkEntryClass(entryClass, false);
String[] objectClasses = getObjectClasses(entry, entryClass);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
String[] ldapReturnAttributes = getAttributes(null, propertiesAnnotations, false);
return contains(dnValue.toString(), attributes, objectClasses, ldapReturnAttributes);
}
protected <T> boolean contains(Class<T> entryClass, String primaryKey, String[] ldapReturnAttributes) {
if (StringHelper.isEmptyString(primaryKey)) {
throw new MappingException("DN to find entry is null");
}
checkEntryClass(entryClass, true);
try {
List<AttributeData> results = find(primaryKey, ldapReturnAttributes);
return (results != null) && (results.size() > 0);
} catch (EntryPersistenceException ex) {
return false;
}
}
@Override
public <T> boolean contains(String baseDN, Class<T> entryClass, Filter filter) {
// Check entry class
checkEntryClass(entryClass, false);
String[] objectClasses = getTypeObjectClasses(entryClass);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
String[] ldapReturnAttributes = getAttributes(null, propertiesAnnotations, false);
return contains(baseDN, filter, objectClasses, ldapReturnAttributes);
}
protected boolean contains(String baseDN, List<AttributeData> attributes, String[] objectClasses,
String... ldapReturnAttributes) {
Filter[] attributesFilters = createAttributesFilter(attributes);
Filter attributesFilter = null;
if (attributesFilters != null) {
attributesFilter = Filter.createANDFilter(attributesFilters);
}
return contains(baseDN, attributesFilter, objectClasses, ldapReturnAttributes);
}
protected abstract boolean contains(String baseDN, Filter filter, String[] objectClasses,
String[] ldapReturnAttributes);
@Override
public <T> boolean contains(String primaryKey, Class<T> entryClass) {
return contains(entryClass, primaryKey, (String[]) null);
}
@Override
public <T> T find(Class<T> entryClass, Object primaryKey) {
return find(entryClass, primaryKey, null);
}
@Override
public <T> T find(Class<T> entryClass, Object primaryKey, String[] ldapReturnAttributes) {
if (StringHelper.isEmptyString(primaryKey)) {
throw new MappingException("DN to find entry is null");
}
checkEntryClass(entryClass, true);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
return find(entryClass, primaryKey, ldapReturnAttributes, propertiesAnnotations);
}
protected <T> String[] getAttributes(T entry, List<PropertyAnnotation> propertiesAnnotations,
boolean isIgnoreAttributesList) {
List<String> attributes = getAttributesList(entry, propertiesAnnotations, isIgnoreAttributesList);
if (attributes == null) {
return null;
}
return attributes.toArray(new String[0]);
}
private <T> List<String> getAttributesList(T entry, List<PropertyAnnotation> propertiesAnnotations,
boolean isIgnoreAttributesList) {
List<String> attributes = new ArrayList<String>();
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
if (!isIgnoreAttributesList) {
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributesList.class);
if (ldapAttribute != null) {
if (entry == null) {
return null;
} else {
List<AttributeData> attributesList = getAttributesFromAttributesList(entry,
ldapAttribute, propertyName);
for (AttributeData attributeData : attributesList) {
String ldapAttributeName = attributeData.getName();
if (!attributes.contains(ldapAttributeName)) {
attributes.add(ldapAttributeName);
}
}
}
}
}
// Process properties with AttributeName annotation
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute != null) {
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertyName;
}
if (!attributes.contains(ldapAttributeName)) {
attributes.add(ldapAttributeName);
}
}
}
if (attributes.size() == 0) {
return null;
}
return attributes;
}
private <T> T find(Class<T> entryClass, Object primaryKey, String[] ldapReturnAttributes,
List<PropertyAnnotation> propertiesAnnotations) {
Map<String, List<AttributeData>> entriesAttributes = new HashMap<String, List<AttributeData>>();
String[] currentLdapReturnAttributes = ldapReturnAttributes;
if (ArrayHelper.isEmpty(currentLdapReturnAttributes)) {
currentLdapReturnAttributes = getAttributes(null, propertiesAnnotations, false);
}
List<AttributeData> ldapAttributes = find(primaryKey.toString(), currentLdapReturnAttributes);
entriesAttributes.put(primaryKey.toString(), ldapAttributes);
List<T> results = createEntities(entryClass, propertiesAnnotations, entriesAttributes);
return results.get(0);
}
protected abstract List<AttributeData> find(String dn, String... attributes);
protected boolean checkEntryClass(Class<?> entryClass, boolean isAllowSchemaEntry) {
if (entryClass == null) {
throw new MappingException("Entry class is null");
}
// Check if entry is LDAP Entry
List<Annotation> entryAnnotations = ReflectHelper.getClassAnnotations(entryClass, LDAP_ENTRY_TYPE_ANNOTATIONS);
Annotation ldapSchemaEntry = ReflectHelper.getAnnotationByType(entryAnnotations, SchemaEntry.class);
Annotation ldapEntry = ReflectHelper.getAnnotationByType(entryAnnotations, DataEntry.class);
if (isAllowSchemaEntry) {
if ((ldapSchemaEntry == null) && (ldapEntry == null)) {
throw new MappingException("Entry should has DataEntry or SchemaEntry annotation");
}
} else {
if (ldapEntry == null) {
throw new MappingException("Entry should has DataEntry annotation");
}
}
return true;
}
protected boolean isSchemaEntry(Class<?> entryClass) {
if (entryClass == null) {
throw new MappingException("Entry class is null");
}
// Check if entry is LDAP Entry
List<Annotation> entryAnnotations = ReflectHelper.getClassAnnotations(entryClass, LDAP_ENTRY_TYPE_ANNOTATIONS);
return ReflectHelper.getAnnotationByType(entryAnnotations, SchemaEntry.class) != null;
}
protected String[] getEntrySortBy(Class<?> entryClass) {
if (entryClass == null) {
throw new MappingException("Entry class is null");
}
// Check if entry is LDAP Entry
List<Annotation> entryAnnotations = ReflectHelper.getClassAnnotations(entryClass, LDAP_ENTRY_TYPE_ANNOTATIONS);
Annotation annotation = ReflectHelper.getAnnotationByType(entryAnnotations, DataEntry.class);
if (annotation == null) {
return null;
}
return ((DataEntry) annotation).sortBy();
}
@Override
public String[] getObjectClasses(Object entry, Class<?> entryClass) {
String[] typeObjectClasses = getTypeObjectClasses(entryClass);
String[] customObjectClasses = getCustomObjectClasses(entry, entryClass);
if (ArrayHelper.isEmpty(typeObjectClasses)) {
return customObjectClasses;
}
String[] mergedArray = ArrayHelper.arrayMerge(typeObjectClasses, customObjectClasses);
Set<String> objecClassSet = new HashSet<String>();
objecClassSet.addAll(Arrays.asList(mergedArray));
return objecClassSet.toArray(new String[0]);
}
protected String[] getTypeObjectClasses(Class<?> entryClass) {
// Check if entry is LDAP Entry
List<Annotation> entryAnnotations = ReflectHelper.getClassAnnotations(entryClass, LDAP_ENTRY_TYPE_ANNOTATIONS);
// Get object classes
Annotation ldapObjectClass = ReflectHelper.getAnnotationByType(entryAnnotations, ObjectClass.class);
if (ldapObjectClass == null) {
return EMPTY_STRING_ARRAY;
}
return ((ObjectClass) ldapObjectClass).values();
}
protected String[] getCustomObjectClasses(Object entry, Class<?> entryClass) {
List<String> result = new ArrayList<String>();
List<PropertyAnnotation> customObjectAnnotations = getEntryCustomObjectClassAnnotations(entryClass);
for (PropertyAnnotation propertiesAnnotation : customObjectAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Getter getter = getGetter(entryClass, propertyName);
if (getter == null) {
throw new MappingException("Entry should has getter for property " + propertyName);
}
AttributeData attribute = getAttributeData(propertyName, propertyName, getter, entry, false);
if (attribute != null) {
for (String objectClass : attribute.getStringValues()) {
if (objectClass != null) {
result.add(objectClass);
}
}
}
break;
}
return result.toArray(new String[0]);
}
protected void setCustomObjectClasses(Object entry, Class<?> entryClass, String[] objectClasses) {
List<PropertyAnnotation> customObjectAnnotations = getEntryCustomObjectClassAnnotations(entryClass);
for (PropertyAnnotation propertiesAnnotation : customObjectAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Setter setter = getSetter(entryClass, propertyName);
if (setter == null) {
throw new MappingException("Entry should has setter for property " + propertyName);
}
AttributeData attribute = new AttributeData(propertyName, objectClasses);
setPropertyValue(propertyName, setter, entry, attribute, false);
break;
}
}
protected String getDNPropertyName(Class<?> entryClass) {
List<PropertyAnnotation> propertiesAnnotations = getEntryDnAnnotations(entryClass);
if (propertiesAnnotations.size() == 0) {
throw new MappingException("Entry should has property with annotation LdapDN");
}
if (propertiesAnnotations.size() > 1) {
throw new MappingException("Entry should has only one property with annotation LdapDN");
}
return propertiesAnnotations.get(0).getPropertyName();
}
protected <T> List<T> createEntities(Class<T> entryClass, List<PropertyAnnotation> propertiesAnnotations,
Map<String, List<AttributeData>> entriesAttributes) {
return createEntities(entryClass, propertiesAnnotations, entriesAttributes, true);
}
protected <T> List<T> createEntities(Class<T> entryClass, List<PropertyAnnotation> propertiesAnnotations,
Map<String, List<AttributeData>> entriesAttributes, boolean doSort) {
// Check if entry has DN property
String dnProperty = getDNPropertyName(entryClass);
// Get DN value
Setter dnSetter = getSetter(entryClass, dnProperty);
if (dnSetter == null) {
throw new MappingException("Entry should has getter for property " + dnProperty);
}
// Type object classes
String[] typeObjectClasses = getTypeObjectClasses(entryClass);
Arrays.sort(typeObjectClasses);
List<T> results = new ArrayList<T>(entriesAttributes.size());
for (Entry<String, List<AttributeData>> entryAttributes : entriesAttributes.entrySet()) {
String dn = entryAttributes.getKey();
List<AttributeData> attributes = entryAttributes.getValue();
Map<String, AttributeData> attributesMap = getAttributesMap(attributes);
T entry;
List<String> customObjectClasses = null;
try {
entry = ReflectHelper.createObjectByDefaultConstructor(entryClass);
} catch (Exception ex) {
throw new MappingException(String.format("Entry %s should has default constructor", entryClass));
}
results.add(entry);
dnSetter.set(entry, dn);
// Set loaded properties to entry
// Process properties with AttributeName annotation
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute != null) {
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertyName;
}
ldapAttributeName = ldapAttributeName.toLowerCase();
AttributeData attributeData = attributesMap.get(ldapAttributeName);
// Remove processed attributes
attributesMap.remove(ldapAttributeName);
if (((AttributeName) ldapAttribute).ignoreDuringRead()) {
continue;
}
Setter setter = getSetter(entryClass, propertyName);
if (setter == null) {
throw new MappingException("Entry should has setter for property " + propertyName);
}
Annotation ldapJsonObject = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
JsonObject.class);
boolean jsonObject = ldapJsonObject != null;
setPropertyValue(propertyName, setter, entry, attributeData, jsonObject);
}
}
// Process properties with @AttributesList annotation
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributesList.class);
if (ldapAttribute != null) {
Map<String, AttributeName> ldapAttributesConfiguration = new HashMap<String, AttributeName>();
for (AttributeName ldapAttributeConfiguration : ((AttributesList) ldapAttribute)
.attributesConfiguration()) {
ldapAttributesConfiguration.put(ldapAttributeConfiguration.name(), ldapAttributeConfiguration);
}
Setter setter = getSetter(entryClass, propertyName);
if (setter == null) {
throw new MappingException("Entry should has setter for property " + propertyName);
}
List<Object> propertyValue = new ArrayList<Object>();
setter.set(entry, propertyValue);
Class<?> entryItemType = ReflectHelper.getListType(setter);
if (entryItemType == null) {
throw new MappingException(
"Entry property " + propertyName + " should has setter with specified element type");
}
String entryPropertyName = ((AttributesList) ldapAttribute).name();
Setter entryPropertyNameSetter = getSetter(entryItemType, entryPropertyName);
if (entryPropertyNameSetter == null) {
throw new MappingException(
"Entry should has setter for property " + propertyName + "." + entryPropertyName);
}
String entryPropertyValue = ((AttributesList) ldapAttribute).value();
Setter entryPropertyValueSetter = getSetter(entryItemType, entryPropertyValue);
if (entryPropertyValueSetter == null) {
throw new MappingException(
"Entry should has getter for property " + propertyName + "." + entryPropertyValue);
}
for (AttributeData entryAttribute : attributesMap.values()) {
if (OBJECT_CLASS.equalsIgnoreCase(entryAttribute.getName())) {
String[] objectClasses = entryAttribute.getStringValues();
if (ArrayHelper.isEmpty(objectClasses)) {
continue;
}
if (customObjectClasses == null) {
customObjectClasses = new ArrayList<String>();
}
for (String objectClass : objectClasses) {
int idx = Arrays.binarySearch(typeObjectClasses, objectClass, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.toLowerCase().compareTo(o2.toLowerCase());
}
});
if (idx < 0) {
customObjectClasses.add(objectClass);
}
}
continue;
}
AttributeName ldapAttributeConfiguration = ldapAttributesConfiguration
.get(entryAttribute.getName());
if ((ldapAttributeConfiguration != null) && ldapAttributeConfiguration.ignoreDuringRead()) {
continue;
}
Object listItem = getListItem(propertyName, entryPropertyNameSetter, entryPropertyValueSetter,
entryItemType, entryAttribute);
if (listItem != null) {
propertyValue.add(listItem);
}
}
if (doSort) {
sortAttributesListIfNeeded((AttributesList) ldapAttribute, entryItemType,
propertyValue);
}
}
}
if ((customObjectClasses != null) && (customObjectClasses.size() > 0)) {
setCustomObjectClasses(entry, entryClass, customObjectClasses.toArray(new String[0]));
}
}
return results;
}
@Override
public <T> List<T> createEntities(Class<T> entryClass, Map<String, List<AttributeData>> entriesAttributes) {
checkEntryClass(entryClass, true);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
return createEntities(entryClass, propertiesAnnotations, entriesAttributes);
}
@SuppressWarnings("unchecked")
private <T> void sortAttributesListIfNeeded(AttributesList ldapAttribute, Class<T> entryItemType,
List<?> list) {
if (!ldapAttribute.sortByName()) {
return;
}
sortListByProperties(entryItemType, (List<T>) list, ldapAttribute.name());
}
protected <T> void sortEntriesIfNeeded(Class<T> entryClass, List<T> entries) {
String[] sortByProperties = getEntrySortBy(entryClass);
if (ArrayHelper.isEmpty(sortByProperties)) {
return;
}
sortListByProperties(entryClass, entries, sortByProperties);
}
@Override
public <T> void sortListByProperties(Class<T> entryClass, List<T> entries, boolean caseSensetive,
String... sortByProperties) {
// Check input parameters
if (entries == null) {
throw new MappingException("Entries list to sort is null");
}
if (entries.size() == 0) {
return;
}
if ((sortByProperties == null) || (sortByProperties.length == 0)) {
throw new InvalidArgumentException(
"Invalid list of sortBy properties " + Arrays.toString(sortByProperties));
}
// Get getters for all properties
Getter[][] propertyGetters = new Getter[sortByProperties.length][];
for (int i = 0; i < sortByProperties.length; i++) {
String[] tmpProperties = sortByProperties[i].split("\\.");
propertyGetters[i] = new Getter[tmpProperties.length];
Class<?> currentEntryClass = entryClass;
for (int j = 0; j < tmpProperties.length; j++) {
if (j > 0) {
currentEntryClass = propertyGetters[i][j - 1].getReturnType();
}
propertyGetters[i][j] = getGetter(currentEntryClass, tmpProperties[j]);
}
if (propertyGetters[i][tmpProperties.length - 1] == null) {
throw new MappingException("Entry should has getteres for all properties " + sortByProperties[i]);
}
Class<?> propertyType = propertyGetters[i][tmpProperties.length - 1].getReturnType();
if (!((propertyType == String.class) || (propertyType == Date.class) || (propertyType == Integer.class)
|| (propertyType == Integer.TYPE))) {
throw new MappingException("Entry properties should has String, Date or Integer type. Property: '"
+ tmpProperties[tmpProperties.length - 1] + "'");
}
}
PropertyComparator<T> comparator = new PropertyComparator<T>(propertyGetters, caseSensetive);
Collections.sort(entries, comparator);
}
protected <T> void sortListByProperties(Class<T> entryClass, List<T> entries, String... sortByProperties) {
sortListByProperties(entryClass, entries, false, sortByProperties);
}
@Override
public <T> Map<T, List<T>> groupListByProperties(Class<T> entryClass, List<T> entries, boolean caseSensetive,
String groupByProperties, String sumByProperties) {
// Check input parameters
if (entries == null) {
throw new MappingException("Entries list to group is null");
}
if (entries.size() == 0) {
return new HashMap<T, List<T>>(0);
}
if (StringHelper.isEmpty(groupByProperties)) {
throw new InvalidArgumentException("List of groupBy properties is null");
}
// Get getters for all properties
Getter[] groupPropertyGetters = getEntryPropertyGetters(entryClass, groupByProperties,
GROUP_BY_ALLOWED_DATA_TYPES);
Setter[] groupPropertySetters = getEntryPropertySetters(entryClass, groupByProperties,
GROUP_BY_ALLOWED_DATA_TYPES);
Getter[] sumPropertyGetters = getEntryPropertyGetters(entryClass, sumByProperties, SUM_BY_ALLOWED_DATA_TYPES);
Setter[] sumPropertySetter = getEntryPropertySetters(entryClass, sumByProperties, SUM_BY_ALLOWED_DATA_TYPES);
return groupListByPropertiesImpl(entryClass, entries, caseSensetive, groupPropertyGetters, groupPropertySetters,
sumPropertyGetters, sumPropertySetter);
}
private <T> Getter[] getEntryPropertyGetters(Class<T> entryClass, String properties, Class<?>[] allowedTypes) {
if (StringHelper.isEmpty(properties)) {
return null;
}
String[] tmpProperties = properties.split("\\,");
Getter[] propertyGetters = new Getter[tmpProperties.length];
for (int i = 0; i < tmpProperties.length; i++) {
propertyGetters[i] = getGetter(entryClass, tmpProperties[i].trim());
if (propertyGetters[i] == null) {
throw new MappingException("Entry should has getter for property " + tmpProperties[i]);
}
Class<?> returnType = propertyGetters[i].getReturnType();
boolean found = false;
for (Class<?> clazz : allowedTypes) {
if (ReflectHelper.assignableFrom(returnType, clazz)) {
found = true;
break;
}
}
if (!found) {
throw new MappingException(
"Entry property getter should has next data types " + Arrays.toString(allowedTypes));
}
}
return propertyGetters;
}
private <T> Setter[] getEntryPropertySetters(Class<T> entryClass, String properties, Class<?>[] allowedTypes) {
if (StringHelper.isEmpty(properties)) {
return null;
}
String[] tmpProperties = properties.split("\\,");
Setter[] propertySetters = new Setter[tmpProperties.length];
for (int i = 0; i < tmpProperties.length; i++) {
propertySetters[i] = getSetter(entryClass, tmpProperties[i].trim());
if (propertySetters[i] == null) {
throw new MappingException("Entry should has setter for property " + tmpProperties[i]);
}
Class<?> paramType = ReflectHelper.getSetterType(propertySetters[i]);
boolean found = false;
for (Class<?> clazz : allowedTypes) {
if (ReflectHelper.assignableFrom(paramType, clazz)) {
found = true;
break;
}
}
if (!found) {
throw new MappingException(
"Entry property setter should has next data types " + Arrays.toString(allowedTypes));
}
}
return propertySetters;
}
protected <T> Map<T, List<T>> groupListByProperties(Class<T> entryClass, List<T> entries, String groupByProperties,
String sumByProperties) {
return groupListByProperties(entryClass, entries, false, groupByProperties, sumByProperties);
}
private <T> Map<T, List<T>> groupListByPropertiesImpl(Class<T> entryClass, List<T> entries, boolean caseSensetive,
Getter[] groupPropertyGetters, Setter[] groupPropertySetters, Getter[] sumProperyGetters,
Setter[] sumPropertySetter) {
Map<String, T> keys = new HashMap<String, T>();
Map<T, List<T>> groups = new IdentityHashMap<T, List<T>>();
for (T entry : entries) {
String key = getEntryKey(entry, caseSensetive, groupPropertyGetters);
T entryKey = keys.get(key);
if (entryKey == null) {
try {
entryKey = ReflectHelper.createObjectByDefaultConstructor(entryClass);
} catch (Exception ex) {
throw new MappingException(String.format("Entry %s should has default constructor", entryClass),
ex);
}
try {
ReflectHelper.copyObjectPropertyValues(entry, entryKey, groupPropertyGetters, groupPropertySetters);
} catch (Exception ex) {
throw new MappingException("Failed to set values in group Entry", ex);
}
keys.put(key, entryKey);
}
List<T> groupValues = groups.get(entryKey);
if (groupValues == null) {
groupValues = new ArrayList<T>();
groups.put(entryKey, groupValues);
}
try {
if (sumProperyGetters != null) {
ReflectHelper.sumObjectPropertyValues(entryKey, entry, sumProperyGetters, sumPropertySetter);
}
} catch (Exception ex) {
throw new MappingException("Failed to sum values in group Entry", ex);
}
groupValues.add(entry);
}
return groups;
}
private Map<String, AttributeData> getAttributesMap(List<AttributeData> attributes) {
Map<String, AttributeData> attributesMap = new HashMap<String, AttributeData>(attributes.size());
for (AttributeData attribute : attributes) {
attributesMap.put(attribute.getName().toLowerCase(), attribute);
}
return attributesMap;
}
private AttributeData getAttributeData(String propertyName, String ldapAttributeName, Getter propertyValueGetter,
Object entry, boolean jsonObject) {
Object propertyValue = propertyValueGetter.get(entry);
if (propertyValue == null) {
return null;
}
Object[] attributeValues = new Object[1];
if (propertyValue instanceof String) {
attributeValues[0] = StringHelper.toString(propertyValue);
} else if (propertyValue instanceof Boolean) {
attributeValues[0] = propertyValue;
} else if (propertyValue instanceof Integer) {
attributeValues[0] = propertyValue;
} else if (propertyValue instanceof Long) {
attributeValues[0] = propertyValue;
} else if (propertyValue instanceof Date) {
attributeValues[0] = encodeTime((Date) propertyValue);
} else if (propertyValue instanceof String[]) {
attributeValues = (String[]) propertyValue;
} else if (propertyValue instanceof List<?>) {
attributeValues = new Object[((List<?>) propertyValue).size()];
int index = 0;
for (Object tmpPropertyValue : (List<?>) propertyValue) {
if (jsonObject) {
attributeValues[index++] = convertValueToJson(tmpPropertyValue);
} else {
attributeValues[index++] = StringHelper.toString(tmpPropertyValue);
}
}
} else if (propertyValue instanceof AttributeEnum) {
attributeValues[0] = ((AttributeEnum) propertyValue).getValue();
} else if (propertyValue instanceof AttributeEnum[]) {
AttributeEnum[] propertyValues = (AttributeEnum[]) propertyValue;
attributeValues = new String[propertyValues.length];
for (int i = 0; i < propertyValues.length; i++) {
attributeValues[i] = (propertyValues[i] == null) ? null : propertyValues[i].getValue();
}
} else if (jsonObject) {
attributeValues[0] = convertValueToJson(propertyValue);
} else {
throw new MappingException("Entry property '" + propertyName
+ "' should has getter with String, String[], Boolean, Integer, Long, Date, List<String>, AttributeEnum or AttributeEnum[]"
+ " return type or has annotation JsonObject");
}
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Property: %s, LdapProperty: %s, PropertyValue: %s", propertyName,
ldapAttributeName, Arrays.toString(attributeValues)));
}
if (attributeValues.length == 0) {
attributeValues = new String[] {};
} else if ((attributeValues.length == 1) && (attributeValues[0] == null)) {
return null;
}
return new AttributeData(ldapAttributeName, attributeValues);
}
protected Object convertValueToJson(Object propertyValue) {
try {
String value = JSON_OBJECT_MAPPER.writeValueAsString(propertyValue);
return value;
} catch (Exception ex) {
LOG.error("Failed to convert '{}' to json value:", propertyValue, ex);
throw new MappingException(String.format("Failed to convert '%s' to json value", propertyValue));
}
}
protected List<AttributeData> getAttributesListForPersist(Object entry,
List<PropertyAnnotation> propertiesAnnotations) {
// Prepare list of properties to persist
List<AttributeData> attributes = new ArrayList<AttributeData>();
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
String propertyName = propertiesAnnotation.getPropertyName();
Annotation ldapAttribute;
// Process properties with AttributeName annotation
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute != null) {
AttributeData attribute = getAttributeFromAttribute(entry, ldapAttribute, propertiesAnnotation,
propertyName);
if (attribute != null) {
attributes.add(attribute);
}
continue;
}
// Process properties with @AttributesList annotation
ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributesList.class);
if (ldapAttribute != null) {
List<AttributeData> listAttributes = getAttributesFromAttributesList(entry, ldapAttribute,
propertyName);
if (listAttributes != null) {
attributes.addAll(listAttributes);
}
continue;
}
}
return attributes;
}
private AttributeData getAttributeFromAttribute(Object entry, Annotation ldapAttribute,
PropertyAnnotation propertiesAnnotation, String propertyName) {
Class<?> entryClass = entry.getClass();
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertyName;
}
Getter getter = getGetter(entryClass, propertyName);
if (getter == null) {
throw new MappingException("Entry should has getter for property " + propertyName);
}
Annotation ldapJsonObject = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
JsonObject.class);
boolean jsonObject = ldapJsonObject != null;
AttributeData attribute = getAttributeData(propertyName, ldapAttributeName, getter, entry, jsonObject);
return attribute;
}
private List<AttributeData> getAttributesFromAttributesList(Object entry, Annotation ldapAttribute,
String propertyName) {
Class<?> entryClass = entry.getClass();
List<AttributeData> listAttributes = new ArrayList<AttributeData>();
Getter getter = getGetter(entryClass, propertyName);
if (getter == null) {
throw new MappingException("Entry should has getter for property " + propertyName);
}
Object propertyValue = getter.get(entry);
if (propertyValue == null) {
return null;
}
if (!(propertyValue instanceof List<?>)) {
throw new MappingException("Entry property should has List base type");
}
Class<?> elementType = ReflectHelper.getListType(getter);
String entryPropertyName = ((AttributesList) ldapAttribute).name();
Getter entryPropertyNameGetter = getGetter(elementType, entryPropertyName);
if (entryPropertyNameGetter == null) {
throw new MappingException(
"Entry should has getter for property " + propertyName + "." + entryPropertyName);
}
String entryPropertyValue = ((AttributesList) ldapAttribute).value();
Getter entryPropertyValueGetter = getGetter(elementType, entryPropertyValue);
if (entryPropertyValueGetter == null) {
throw new MappingException(
"Entry should has getter for property " + propertyName + "." + entryPropertyValue);
}
for (Object entryAttribute : (List<?>) propertyValue) {
AttributeData attribute = getAttributeData(propertyName, entryPropertyNameGetter, entryPropertyValueGetter,
entryAttribute, false);
if (attribute != null) {
listAttributes.add(attribute);
}
}
return listAttributes;
}
protected <T> List<PropertyAnnotation> getEntryPropertyAnnotations(Class<T> entryClass) {
return getEntryClassAnnotations(entryClass, "property_", LDAP_ENTRY_PROPERTY_ANNOTATIONS);
}
protected <T> List<PropertyAnnotation> getEntryDnAnnotations(Class<T> entryClass) {
return getEntryClassAnnotations(entryClass, "dn_", LDAP_DN_PROPERTY_ANNOTATION);
}
protected <T> List<PropertyAnnotation> getEntryCustomObjectClassAnnotations(Class<T> entryClass) {
return getEntryClassAnnotations(entryClass, "custom_", LDAP_CUSTOM_OBJECT_CLASS_PROPERTY_ANNOTATION);
}
protected <T> List<PropertyAnnotation> getEntryClassAnnotations(Class<T> entryClass, String keyCategory,
Class<?>[] annotationTypes) {
String key = keyCategory + entryClass.getName();
List<PropertyAnnotation> annotations = classAnnotations.get(key);
if (annotations == null) {
synchronized (CLASS_ANNOTATIONS_LOCK) {
annotations = classAnnotations.get(key);
if (annotations == null) {
Map<String, List<Annotation>> annotationsMap = ReflectHelper.getPropertiesAnnotations(entryClass,
annotationTypes);
annotations = convertToPropertyAnnotationList(annotationsMap);
classAnnotations.put(key, annotations);
}
}
}
return annotations;
}
private List<PropertyAnnotation> convertToPropertyAnnotationList(Map<String, List<Annotation>> annotations) {
List<PropertyAnnotation> result = new ArrayList<PropertyAnnotation>(annotations.size());
for (Entry<String, List<Annotation>> entry : annotations.entrySet()) {
result.add(new PropertyAnnotation(entry.getKey(), entry.getValue()));
}
Collections.sort(result);
return result;
}
protected <T> Getter getGetter(Class<T> entryClass, String propertyName) {
String key = entryClass.getName() + "." + propertyName;
Getter getter = classGetters.get(key);
if (getter == null) {
synchronized (CLASS_GETTERS_LOCK) {
getter = classGetters.get(key);
if (getter == null) {
getter = ReflectHelper.getGetter(entryClass, propertyName);
classGetters.put(key, getter);
}
}
}
return getter;
}
protected <T> Setter getSetter(Class<T> entryClass, String propertyName) {
String key = entryClass.getName() + "." + propertyName;
Setter setter = classSetters.get(key);
if (setter == null) {
synchronized (CLASS_SETTERS_LOCK) {
setter = classSetters.get(key);
if (setter == null) {
setter = ReflectHelper.getSetter(entryClass, propertyName);
classSetters.put(key, setter);
}
}
}
return setter;
}
private AttributeData getAttributeData(String propertyName, Getter propertyNameGetter, Getter propertyValueGetter,
Object entry, boolean jsonObject) {
Object ldapAttributeName = propertyNameGetter.get(entry);
if (ldapAttributeName == null) {
return null;
}
return getAttributeData(propertyName, ldapAttributeName.toString(), propertyValueGetter, entry, jsonObject);
}
private void setPropertyValue(String propertyName, Setter propertyValueSetter, Object entry,
AttributeData attribute, boolean jsonObject) {
if (attribute == null) {
return;
}
LOG.debug(String.format("LdapProperty: %s, AttributeName: %s, AttributeValue: %s", propertyName,
attribute.getName(), Arrays.toString(attribute.getValues())));
Class<?> parameterType = ReflectHelper.getSetterType(propertyValueSetter);
if (parameterType.equals(String.class)) {
propertyValueSetter.set(entry, String.valueOf(attribute.getValue()));
} else if (parameterType.equals(Boolean.class) || parameterType.equals(Boolean.TYPE)) {
propertyValueSetter.set(entry, toBooleanValue(attribute));
} else if (parameterType.equals(Integer.class) || parameterType.equals(Integer.TYPE)) {
propertyValueSetter.set(entry, toIntegerValue(attribute));
} else if (parameterType.equals(Long.class) || parameterType.equals(Long.TYPE)) {
propertyValueSetter.set(entry, toLongValue(attribute));
} else if (parameterType.equals(Date.class)) {
propertyValueSetter.set(entry, decodeTime(String.valueOf(attribute.getValue())));
} else if (parameterType.equals(String[].class)) {
propertyValueSetter.set(entry, attribute.getStringValues());
} else if (ReflectHelper.assignableFrom(parameterType, List.class)) {
if (jsonObject) {
Object[] values = attribute.getValues();
List<Object> jsonValues = new ArrayList<Object>(values.length);
for (Object value : values) {
Object jsonValue = convertJsonToValue(ReflectHelper.getListType(propertyValueSetter), value);
jsonValues.add(jsonValue);
}
propertyValueSetter.set(entry, jsonValues);
} else {
propertyValueSetter.set(entry, Arrays.asList(attribute.getValues()));
}
} else if (ReflectHelper.assignableFrom(parameterType, AttributeEnum.class)) {
try {
propertyValueSetter.set(entry, parameterType.getMethod("resolveByValue", String.class)
.invoke(parameterType.getEnumConstants()[0], attribute.getValue()));
} catch (Exception ex) {
throw new MappingException("Failed to resolve Enum '" + parameterType + "' by value '" + attribute.getValue() + "'", ex);
}
} else if (ReflectHelper.assignableFrom(parameterType, AttributeEnum[].class)) {
Class<?> itemType = parameterType.getComponentType();
Method enumResolveByValue;
try {
enumResolveByValue = itemType.getMethod("resolveByValue", String.class);
} catch (Exception ex) {
throw new MappingException("Failed to resolve Enum '" + parameterType + "' by value '" + Arrays.toString(attribute.getValues()) + "'",
ex);
}
Object[] attributeValues = attribute.getValues();
AttributeEnum[] ldapEnums = (AttributeEnum[]) ReflectHelper.createArray(itemType, attributeValues.length);
for (int i = 0; i < attributeValues.length; i++) {
try {
ldapEnums[i] = (AttributeEnum) enumResolveByValue.invoke(itemType.getEnumConstants()[0],
attributeValues[i]);
} catch (Exception ex) {
throw new MappingException(
"Failed to resolve Enum '" + parameterType + "' by value '" + Arrays.toString(attribute.getValues()) + "'", ex);
}
}
propertyValueSetter.set(entry, ldapEnums);
} else if (jsonObject) {
Object stringValue = attribute.getValue();
Object jsonValue = convertJsonToValue(parameterType, stringValue);
propertyValueSetter.set(entry, jsonValue);
} else {
throw new MappingException("Entry property '" + propertyName
+ "' should has setter with String, Boolean, Integer, Long, Date, String[], List<String>, AttributeEnum or AttributeEnum[]"
+ " parameter type or has annotation JsonObject");
}
}
private Boolean toBooleanValue(AttributeData attribute) {
Boolean propertyValue = null;
Object propertyValueObject = attribute.getValue();
if (propertyValueObject != null) {
if (propertyValueObject instanceof Boolean) {
propertyValue = (Boolean) propertyValueObject;
} else {
propertyValue = Boolean.valueOf(String.valueOf(propertyValueObject));
}
}
return propertyValue;
}
private Integer toIntegerValue(AttributeData attribute) {
Integer propertyValue = null;
Object propertyValueObject = attribute.getValue();
if (propertyValueObject != null) {
if (propertyValueObject instanceof Long) {
propertyValue = (Integer) propertyValueObject;
} else {
propertyValue = Integer.valueOf(String.valueOf(propertyValueObject));
}
}
return propertyValue;
}
private Long toLongValue(AttributeData attribute) {
Long propertyValue = null;
Object propertyValueObject = attribute.getValue();
if (propertyValueObject != null) {
if (propertyValueObject instanceof Long) {
propertyValue = (Long) propertyValueObject;
} else {
propertyValue = Long.valueOf(String.valueOf(propertyValueObject));
}
}
return propertyValue;
}
protected Object convertJsonToValue(Class<?> parameterType, Object propertyValue) {
try {
Object jsonValue = JSON_OBJECT_MAPPER.readValue(String.valueOf(propertyValue), parameterType);
return jsonValue;
} catch (Exception ex) {
LOG.error("Failed to convert json value '{}' to object `{}`", propertyValue, parameterType, ex);
throw new MappingException(String.format("Failed to convert json value '%s' to object of type %s",
propertyValue, parameterType));
}
}
private Object getListItem(String propertyName, Setter propertyNameSetter, Setter propertyValueSetter,
Class<?> classType, AttributeData attribute) {
if (attribute == null) {
return null;
}
Object result;
try {
result = ReflectHelper.createObjectByDefaultConstructor(classType);
} catch (Exception ex) {
throw new MappingException(String.format("Entry %s should has default constructor", classType));
}
propertyNameSetter.set(result, attribute.getName());
setPropertyValue(propertyName, propertyValueSetter, result, attribute, false);
return result;
}
protected <T> Object getDNValue(Object entry, Class<T> entryClass) {
// Check if entry has DN property
String dnProperty = getDNPropertyName(entryClass);
// Get DN value
Getter dnGetter = getGetter(entryClass, dnProperty);
if (dnGetter == null) {
throw new MappingException("Entry should has getter for property " + dnProperty);
}
Object dnValue = dnGetter.get(entry);
if (StringHelper.isEmptyString(dnValue)) {
throw new MappingException("Entry should has not null base DN property value");
}
return dnValue;
}
private <T> String getEntryKey(T entry, boolean caseSensetive, Getter[] propertyGetters) {
StringBuilder sb = new StringBuilder("key");
for (Getter getter : propertyGetters) {
sb.append("__").append(getter.get(entry));
}
if (caseSensetive) {
return sb.toString();
} else {
return sb.toString().toLowerCase();
}
}
private Map<String, AttributeData> getAttributesDataMap(List<AttributeData> attributesData) {
Map<String, AttributeData> result = new HashMap<String, AttributeData>();
for (AttributeData attributeData : attributesData) {
result.put(attributeData.getName(), attributeData);
}
return result;
}
private String getEntryKey(Object dnValue, boolean caseSensetive, List<PropertyAnnotation> propertiesAnnotations,
List<AttributeData> attributesData) {
StringBuilder sb = new StringBuilder("_HASH__").append((String.valueOf(dnValue)).toLowerCase()).append("__");
List<String> processedProperties = new ArrayList<String>();
Map<String, AttributeData> attributesDataMap = getAttributesDataMap(attributesData);
for (PropertyAnnotation propertiesAnnotation : propertiesAnnotations) {
Annotation ldapAttribute = ReflectHelper.getAnnotationByType(propertiesAnnotation.getAnnotations(),
AttributeName.class);
if (ldapAttribute == null) {
continue;
}
String ldapAttributeName = ((AttributeName) ldapAttribute).name();
if (StringHelper.isEmpty(ldapAttributeName)) {
ldapAttributeName = propertiesAnnotation.getPropertyName();
}
processedProperties.add(ldapAttributeName);
String[] values = null;
AttributeData attributeData = attributesDataMap.get(ldapAttributeName);
if ((attributeData != null) && (attributeData.getValues() != null)) {
values = attributeData.getStringValues();
Arrays.sort(values);
}
addPropertyWithValuesToKey(sb, ldapAttributeName, values);
}
for (AttributeData attributeData : attributesData) {
if (processedProperties.contains(attributeData.getName())) {
continue;
}
addPropertyWithValuesToKey(sb, attributeData.getName(), attributeData.getStringValues());
}
if (caseSensetive) {
return sb.toString();
} else {
return sb.toString().toLowerCase();
}
}
private void addPropertyWithValuesToKey(StringBuilder sb, String propertyName, String[] values) {
sb.append(':').append(propertyName).append('=');
if (values == null) {
sb.append("null");
} else {
if (values.length == 1) {
sb.append(values[0]);
} else {
String[] tmpValues = values.clone();
Arrays.sort(tmpValues);
for (int i = 0; i < tmpValues.length; i++) {
sb.append(tmpValues[i]);
if (i < tmpValues.length - 1) {
sb.append(';');
}
}
}
}
}
@Override
public int getHashCode(Object entry) {
if (entry == null) {
throw new MappingException("Entry to persist is null");
}
// Check entry class
Class<?> entryClass = entry.getClass();
checkEntryClass(entryClass, false);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Object dnValue = getDNValue(entry, entryClass);
List<AttributeData> attributes = getAttributesListForPersist(entry, propertiesAnnotations);
String key = getEntryKey(dnValue, false, propertiesAnnotations, attributes);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Entry key HashCode is: %s", key.hashCode()));
}
return key.hashCode();
}
protected byte[][] toBinaryValues(String[] attributeValues) {
byte[][] binaryValues = new byte[attributeValues.length][];
for (int i = 0; i < attributeValues.length; i++) {
binaryValues[i] = Base64.decodeBase64(attributeValues[i]);
}
return binaryValues;
}
protected <T> Filter createFilterByEntry(Object entry, Class<T> entryClass, List<AttributeData> attributes) {
Filter[] attributesFilters = createAttributesFilter(attributes);
Filter attributesFilter = null;
if (attributesFilters != null) {
attributesFilter = Filter.createANDFilter(attributesFilters);
}
String[] objectClasses = getCustomObjectClasses(entry, entryClass);
return addObjectClassFilter(attributesFilter, objectClasses);
}
protected Filter[] createAttributesFilter(List<AttributeData> attributes) {
if ((attributes == null) || (attributes.size() == 0)) {
return null;
}
List<Filter> results = new ArrayList<Filter>(attributes.size());
for (AttributeData attribute : attributes) {
String attributeName = attribute.getName();
for (Object value : attribute.getValues()) {
Filter filter = Filter.createEqualityFilter(attributeName, value);
results.add(filter);
}
}
return results.toArray(new Filter[results.size()]);
}
protected Filter addObjectClassFilter(Filter filter, String[] objectClasses) {
if (objectClasses.length == 0) {
return filter;
}
Filter[] objectClassFilter = new Filter[objectClasses.length];
for (int i = 0; i < objectClasses.length; i++) {
objectClassFilter[i] = Filter.createEqualityFilter(OBJECT_CLASS, objectClasses[i]).arrayType();
}
Filter searchFilter = Filter.createANDFilter(objectClassFilter);
if (filter != null) {
searchFilter = Filter.createANDFilter(Filter.createANDFilter(objectClassFilter), filter);
}
return searchFilter;
}
protected static final class PropertyComparator<T> implements Comparator<T>, Serializable {
private static final long serialVersionUID = 574848841116711467L;
private Getter[][] propertyGetters;
private boolean caseSensetive;
private PropertyComparator(Getter[][] propertyGetters, boolean caseSensetive) {
this.propertyGetters = propertyGetters;
this.caseSensetive = caseSensetive;
}
@Override
public int compare(T entry1, T entry2) {
if ((entry1 == null) && (entry2 == null)) {
return 0;
}
if ((entry1 == null) && (entry2 != null)) {
return -1;
} else if ((entry1 != null) && (entry2 == null)) {
return 1;
}
int result = 0;
for (Getter[] curPropertyGetters : propertyGetters) {
result = compare(entry1, entry2, curPropertyGetters);
if (result != 0) {
break;
}
}
return result;
}
public int compare(T entry1, T entry2, Getter[] propertyGetters) {
Object value1 = ReflectHelper.getPropertyValue(entry1, propertyGetters);
Object value2 = ReflectHelper.getPropertyValue(entry2, propertyGetters);
if ((value1 == null) && (value2 == null)) {
return 0;
}
if ((value1 == null) && (value2 != null)) {
return -1;
} else if ((value1 != null) && (value2 == null)) {
return 1;
}
if (value1 instanceof Date) {
return ((Date) value1).compareTo((Date) value2);
} else if (value1 instanceof Integer) {
return ((Integer) value1).compareTo((Integer) value2);
} else if (value1 instanceof String && value2 instanceof String) {
if (caseSensetive) {
return ((String) value1).compareTo((String) value2);
} else {
return ((String) value1).toLowerCase().compareTo(((String) value2).toLowerCase());
}
}
return 0;
}
}
protected static final class LineLenghtComparator<T> implements Comparator<T>, Serializable {
private static final long serialVersionUID = 575848841116711467L;
private boolean ascending;
public LineLenghtComparator(boolean ascending) {
this.ascending = ascending;
}
@Override
public int compare(T entry1, T entry2) {
if ((entry1 == null) && (entry2 == null)) {
return 0;
}
if ((entry1 == null) && (entry2 != null)) {
return -1;
} else if ((entry1 != null) && (entry2 == null)) {
return 1;
}
int result = entry1.toString().length() - entry2.toString().length();
if (ascending) {
return result;
} else {
return -result;
}
}
}
}
|
package xyz.chunkstories.coreplugin;
import io.xol.chunkstories.api.plugin.ChunkStoriesPlugin;
import io.xol.chunkstories.api.plugin.commands.Command;
import io.xol.chunkstories.api.plugin.commands.CommandEmitter;
import io.xol.chunkstories.api.server.Player;
import io.xol.chunkstories.api.Location;
import io.xol.chunkstories.api.entity.interfaces.EntityWithInventory;
import io.xol.chunkstories.api.item.ItemType;
import io.xol.chunkstories.item.ItemPile;
import io.xol.chunkstories.item.ItemTypes;
import io.xol.chunkstories.server.Server;
public class CorePlugin extends ChunkStoriesPlugin {
public void onEnable() {
System.out.println("Enabling Core plugin ... " + getServer());
}
public void onDisable() {
System.out.println("Disabling Core plugin");
}
public boolean handleCommand(CommandEmitter e, Command cmd, String[] a) {
if ((e instanceof Player)) {
Player player = (Player) e;
if (cmd.equals("clear")) {
player.sendMessage("#FF969BRemoving " + ((EntityWithInventory) player.getControlledEntity()).getInventory().size()
+ " items from your inventory.");
((EntityWithInventory) player.getControlledEntity()).getInventory().clear();
} else if (cmd.equals("give")) {
if (a.length == 0) {
player.sendMessage("#FF969BSyntax : /give <item> [amount] [to]");
return true;
}
ItemType type = null;
String[] info = null;
int amount = 1;
Player to = player;
String itemCall = a[0];
if(itemCall.contains(":"))
{
String[] itemCallS = itemCall.split(":");
itemCall = itemCallS[0];
info = new String[itemCallS.length - 1];
for(int i = 0; i < itemCallS.length - 1; i++)
info[i] = itemCallS[i+1];
}
type = ItemTypes.getItemTypeByName(itemCall);
if (type == null) {
try{
type = ItemTypes.getItemTypeById(Integer.parseInt(itemCall));
}
catch(NumberFormatException ex)
{
}
}
if (type == null) {
player.sendMessage("#FF969BItem \"" + a[0] + " can't be found.");
return true;
}
if (a.length >= 2) {
amount = Integer.parseInt(a[1]);
}
if (a.length >= 3) {
to = Server.getInstance().getPlayer(a[2]);
}
if (to == null) {
player.sendMessage("#FF969BPlayer \"" + a[2] + " can't be found.");
return true;
}
ItemPile itemPile = new ItemPile(type.newItem(), info);
itemPile.setAmount(amount);
//player.sendMessage("#FF969B" + to.getControlledEntity());
((EntityWithInventory) to.getControlledEntity()).getInventory().addItemPile(itemPile);
player.sendMessage("#FF969BGave " + itemPile + " to " + to);
}
else if (cmd.equals("tp")) {
Player who = (Player) e;
Location to = null;
if(a.length == 1)
{
Player otherPlayer = this.getServer().getPlayer(a[0]);
if(otherPlayer != null)
to = otherPlayer.getLocation();
else
e.sendMessage("#FF8966Player not found : "+a[0]);
}
else if(a.length == 2)
{
who = this.getServer().getPlayer(a[0]);
if(who == null)
e.sendMessage("#FF8966Player not found : "+a[0]);
Player otherPlayer = this.getServer().getPlayer(a[1]);
if(otherPlayer != null)
to = otherPlayer.getLocation();
else
e.sendMessage("#FF8966Player not found : "+a[1]);
}
else if(a.length == 3)
{
int x = Integer.parseInt(a[0]);
int y = Integer.parseInt(a[1]);
int z = Integer.parseInt(a[2]);
to = new Location(who.getLocation().getWorld(), x, y, z);
}
else if(a.length == 4)
{
who = this.getServer().getPlayer(a[0]);
if(who == null)
e.sendMessage("#FF8966Player not found : "+a[0]);
int x = Integer.parseInt(a[1]);
int y = Integer.parseInt(a[2]);
int z = Integer.parseInt(a[3]);
to = new Location(who.getLocation().getWorld(), x, y, z);
}
if(who != null && to != null)
{
e.sendMessage("#FF8966Teleported to : "+to);
who.setLocation(to);
}
}
else if (cmd.equals("time")) {
if(a.length == 1)
{
long newTime = Long.parseLong(a[0]);
player.getLocation().getWorld().setTime(newTime);
e.sendMessage("#82FFDBSet time to :"+newTime);
}
else
e.sendMessage("#82FFDBSyntax : /time [0-10000]");
}
else if (cmd.equals("weather")) {
if(a.length == 1)
{
float overcastFactor = Float.parseFloat(a[0]);
player.getLocation().getWorld().setWeather(overcastFactor);
}
else
e.sendMessage("#82FFDBSyntax : /weather [0.0 - 1.0]");
}
}
return true;
}
}
|
package placebooks.controller;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.log4j.Logger;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.map.introspect.VisibilityChecker;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import placebooks.model.AudioItem;
import placebooks.model.GPSTraceItem;
import placebooks.model.ImageItem;
import placebooks.model.LoginDetails;
import placebooks.model.MediaItem;
import placebooks.model.PlaceBook;
import placebooks.model.PlaceBookBinder;
import placebooks.model.PlaceBookBinder.State;
import placebooks.model.PlaceBookItem;
import placebooks.model.User;
import placebooks.model.VideoItem;
import placebooks.model.json.PlaceBookBinderDistanceEntry;
import placebooks.model.json.PlaceBookBinderSearchEntry;
import placebooks.model.json.PlaceBookItemDistanceEntry;
import placebooks.model.json.ServerInfo;
import placebooks.model.json.Shelf;
import placebooks.model.json.ShelfEntry;
import placebooks.model.json.UserShelf;
import placebooks.services.Service;
import placebooks.services.ServiceRegistry;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
// TODO: general todo is to do file checking to reduce unnecessary file writes,
// part of which is ensuring new file writes in cases of changes
// TODO: stop orphan / null field elements being added to database
@Controller
public class PlaceBooksAdminController
{
public PlaceBooksAdminController()
{
jsonMapper.configure(org.codehaus.jackson.map.SerializationConfig.Feature.AUTO_DETECT_FIELDS, true);
jsonMapper.configure(org.codehaus.jackson.map.SerializationConfig.Feature.AUTO_DETECT_GETTERS, false);
jsonMapper.configure(org.codehaus.jackson.map.SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
jsonMapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
jsonMapper.setVisibilityChecker(new VisibilityChecker.Std(JsonAutoDetect.Visibility.NONE, JsonAutoDetect.Visibility.NONE, JsonAutoDetect.Visibility.NONE, JsonAutoDetect.Visibility.NONE, JsonAutoDetect.Visibility.ANY));
}
// Helper class for passing around general PlaceBookItem data
public static class ItemData
{
private Geometry geometry;
private User owner;
private URL sourceURL;
public ItemData()
{
}
public Geometry getGeometry()
{
return geometry;
}
public User getOwner()
{
return owner;
}
public URL getSourceURL()
{
return sourceURL;
}
public boolean processItemData(final EntityManager pm, final String field, final String value)
{
if (field.equals("owner"))
{
setOwner(UserManager.getUser(pm, value));
}
else if (field.equals("sourceurl"))
{
try
{
setSourceURL(new URL(value));
}
catch (final java.net.MalformedURLException e)
{
log.error(e.toString(), e);
}
}
else if (field.equals("geometry"))
{
try
{
setGeometry(new WKTReader().read(value));
}
catch (final ParseException e)
{
log.error(e.toString(), e);
}
}
else
{
return false;
}
return true;
}
private void setGeometry(final Geometry geometry)
{
this.geometry = geometry;
}
private void setOwner(final User owner)
{
this.owner = owner;
}
private void setSourceURL(final URL sourceURL)
{
this.sourceURL = sourceURL;
}
}
private static final Logger log = Logger.getLogger(PlaceBooksAdminController.class.getName());
private final ObjectMapper jsonMapper = new ObjectMapper();
private static final int MEGABYTE = 1048576;
@RequestMapping(value = "/account", method = RequestMethod.GET)
public String accountPage()
{
return "account";
}
@RequestMapping(value = "/addLoginDetails", method = RequestMethod.POST)
public void addLoginDetails(@RequestParam final String username, @RequestParam final String password,
@RequestParam final String service, final HttpServletResponse res)
{
final Service serviceImpl = ServiceRegistry.getService(service);
if (service != null)
{
if (!serviceImpl.checkLogin(username, password))
{
res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
}
final EntityManager manager = EMFSingleton.getEntityManager();
final User user = UserManager.getCurrentUser(manager);
try
{
manager.getTransaction().begin();
final LoginDetails loginDetails = new LoginDetails(user, service, null, username, password);
manager.persist(loginDetails);
user.add(loginDetails);
manager.getTransaction().commit();
final TypedQuery<PlaceBookBinder> q =
manager.createQuery("SELECT p FROM PlaceBookBinder p WHERE p.owner= :owner",
PlaceBookBinder.class);
q.setParameter("owner", user);
final Collection<PlaceBookBinder> pbs = q.getResultList();
log.info("Converting " + pbs.size() + " PlaceBookBinders to JSON");
log.info("User " + user.getName());
try
{
jsonMapper.writeValue(res.getWriter(), new UserShelf(pbs, user));
res.setContentType("application/json");
res.flushBuffer();
}
catch (final Exception e)
{
log.error(e.toString());
}
}
catch (final Exception e)
{
log.error("Error creating user", e);
}
finally
{
if (manager.getTransaction().isActive())
{
manager.getTransaction().rollback();
log.error("Rolling login detail creation");
}
manager.close();
}
new Thread(new Runnable()
{
@Override
public void run()
{
final EntityManager manager = EMFSingleton.getEntityManager();
Service serviceImpl = ServiceRegistry.getService(service);
try
{
if(serviceImpl != null)
{
serviceImpl.sync(manager, user, true, Double.parseDouble(PropertiesSingleton.get(CommunicationHelper.class.getClassLoader()).getProperty(PropertiesSingleton.IDEN_SEARCH_LON, "0")),
Double.parseDouble(PropertiesSingleton.get(CommunicationHelper.class.getClassLoader()).getProperty(PropertiesSingleton.IDEN_SEARCH_LAT, "0")),
Double.parseDouble(PropertiesSingleton.get(CommunicationHelper.class.getClassLoader()).getProperty(PropertiesSingleton.IDEN_SEARCH_RADIUS, "0"))
);
}
}
catch(Exception e)
{
log.warn(e.getMessage(), e);
}
finally
{
manager.close();
}
}
}).start();
}
@RequestMapping(value = "/createUserAccount", method = RequestMethod.POST)
public String createUserAccount(@RequestParam final String name, @RequestParam final String email,
@RequestParam final String password)
{
final Md5PasswordEncoder encoder = new Md5PasswordEncoder();
final User user = new User(name, email, encoder.encodePassword(password, null));
final EntityManager manager = EMFSingleton.getEntityManager();
try
{
manager.getTransaction().begin();
manager.persist(user);
manager.getTransaction().commit();
}
catch (final Exception e)
{
log.error("Error creating user", e);
}
finally
{
if (manager.getTransaction().isActive())
{
manager.getTransaction().rollback();
log.error("Rolling back user creation");
}
manager.close();
}
return "redirect:/index.html";
}
@RequestMapping(value = "/currentUser", method = RequestMethod.GET)
public void currentUser(final HttpServletRequest req, final HttpServletResponse res)
{
res.setContentType("application/json");
final EntityManager entityManager = EMFSingleton.getEntityManager();
try
{
final User user = UserManager.getCurrentUser(entityManager);
if (user == null)
{
try
{
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
jsonMapper.writeValue(res.getWriter(), req.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION));
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.getMessage(), e);
}
new Thread(new Runnable()
{
@Override
public void run()
{
final EntityManager manager = EMFSingleton.getEntityManager();
ServiceRegistry.updateServices(manager, user);
}
}).start();
}
else
{
try
{
jsonMapper.writeValue(res.getWriter(), user);
res.setContentType("application/json");
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.getMessage(), e);
}
}
}
finally
{
entityManager.close();
}
}
@RequestMapping(value = "/palette", method = RequestMethod.GET)
public void getPaletteItemsJSON(final HttpServletResponse res)
{
final EntityManager manager = EMFSingleton.getEntityManager();
final User user = UserManager.getCurrentUser(manager);
if (user == null)
{
try
{
log.info("User not logged in");
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
res.setContentType("application/json");
res.getWriter().write("User not logged in");
return;
}
catch (final Exception e)
{
log.error(e.getMessage(), e);
}
}
final TypedQuery<PlaceBookItem> q = manager
.createQuery( "SELECT p FROM PlaceBookItem p WHERE p.owner = :owner AND p.placebook IS NULL",
PlaceBookItem.class);
q.setParameter("owner", user);
final Collection<PlaceBookItem> pbs = q.getResultList();
// Add preset items to the Palette
final ArrayList<PlaceBookItem> presetItems = PresetItemsHelper.getPresetItems(user);
pbs.addAll(presetItems);
log.info("Converting " + pbs.size() + " PlaceBookItems to JSON");
log.info("User " + user.getName());
try
{
final Writer sos = res.getWriter();
sos.write("[");
boolean comma = false;
for (final PlaceBookItem item : pbs)
{
if (comma)
{
sos.write(",");
}
else
{
comma = true;
}
sos.write(jsonMapper.writeValueAsString(item));
}
sos.write("]");
res.setContentType("application/json");
res.flushBuffer();
}
catch (final Exception e)
{
log.error(e.getMessage(), e);
}
manager.close();
}
@RequestMapping(value = "/placebookitem/{key}", method = RequestMethod.GET)
public void getPlaceBookItemJSON(final HttpServletResponse res, @PathVariable("key") final String key)
{
final EntityManager manager = EMFSingleton.getEntityManager();
try
{
final PlaceBookItem item = manager.find(PlaceBookItem.class, key);
if (item != null)
{
try
{
jsonMapper.writeValue(res.getWriter(), item);
res.setContentType("application/json");
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.toString());
}
}
}
catch (final Throwable e)
{
log.error(e.getMessage(), e);
}
finally
{
manager.close();
}
}
@RequestMapping(value = "/placebook/{key}", method = RequestMethod.GET)
public void getPlaceBookJSON(final HttpServletResponse res, @PathVariable("key") final String key)
{
final EntityManager manager = EMFSingleton.getEntityManager();
try
{
final PlaceBook placebook = manager.find(PlaceBook.class, key);
if (placebook != null)
{
try
{
jsonMapper.writeValue(res.getWriter(), placebook);
res.setContentType("application/json");
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.toString());
}
}
}
catch (final Throwable e)
{
log.error(e.getMessage(), e);
}
finally
{
manager.close();
}
}
@RequestMapping(value = "/placebookbinder/{key}",
method = RequestMethod.GET)
public void getPlaceBookBinderJSON(final HttpServletResponse res,
@PathVariable("key") final String key)
{
final EntityManager manager = EMFSingleton.getEntityManager();
try
{
final PlaceBookBinder pb = manager.find(PlaceBookBinder.class, key);
if (pb != null)
{
try
{
jsonMapper.writeValue(res.getWriter(), pb);
res.setContentType("application/json");
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.toString());
}
}
}
catch (final Throwable e)
{
log.error(e.getMessage(), e);
}
finally
{
manager.close();
}
}
@RequestMapping(value = "/shelf", method = RequestMethod.GET)
public void getPlaceBookBindersJSON(final HttpServletRequest req,
final HttpServletResponse res)
{
log.info("Shelf");
final EntityManager manager = EMFSingleton.getEntityManager();
try
{
final User user = UserManager.getCurrentUser(manager);
if (user != null)
{
final TypedQuery<PlaceBookBinder> q =
manager.createQuery("SELECT p FROM PlaceBookBinder p WHERE p.owner = :user OR p.permsUsers LIKE :email",
PlaceBookBinder.class);
q.setParameter("user", user);
q.setParameter("email",
"'%" + user.getEmail() + "%'");
final Collection<PlaceBookBinder> pbs = q.getResultList();
log.info("Converting " + pbs.size() +
" PlaceBookBinders to JSON");
log.info("User " + user.getName());
try
{
jsonMapper.writeValue(res.getWriter(),
new UserShelf(pbs, user));
res.setContentType("application/json");
res.flushBuffer();
}
catch (final Exception e)
{
log.error(e.toString());
}
new Thread(new Runnable()
{
@Override
public void run()
{
final EntityManager manager =
EMFSingleton.getEntityManager();
ServiceRegistry.updateServices(manager, user);
}
}).start();
}
else
{
try
{
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
jsonMapper.writeValue(res.getWriter(),
((Exception) req.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).getMessage());
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.getMessage(), e);
}
}
}
finally
{
manager.close();
}
}
@RequestMapping(value = "/admin/shelf/{owner}", method = RequestMethod.GET)
public void getPlaceBookBindersJSON(final HttpServletResponse res,
@PathVariable("owner") final String owner)
{
if (owner.trim().isEmpty()) { return; }
final EntityManager pm = EMFSingleton.getEntityManager();
final TypedQuery<User> uq =
pm.createQuery("SELECT u FROM User u WHERE u.email LIKE :email", User.class);
uq.setParameter("email", owner.trim());
try
{
final User user = uq.getSingleResult();
final TypedQuery<PlaceBookBinder> q =
pm.createQuery("SELECT p FROM PlaceBookBinder p "
+ "WHERE p.owner = :user OR p.permsUsers LIKE :email",
PlaceBookBinder.class
);
q.setParameter("user", user);
q.setParameter("email", "'%" + owner.trim() + "%'");
final Collection<PlaceBookBinder> pbs = q.getResultList();
log.info("Converting " + pbs.size() + " PlaceBookBinders to JSON");
if (!pbs.isEmpty())
{
try
{
jsonMapper.writeValue(res.getWriter(),
new UserShelf(pbs, user));
res.setContentType("application/json");
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.toString());
}
}
}
catch (final NoResultException e)
{
log.error(e.toString());
}
finally
{
pm.close();
}
}
@RequestMapping(value = "/randomized/{count}", method = RequestMethod.GET)
public void getRandomPlaceBookBindersJSON(final HttpServletResponse res,
@PathVariable("count") final int count)
{
final EntityManager manager = EMFSingleton.getEntityManager();
try
{
final TypedQuery<PlaceBookBinder> q =
manager.createQuery("SELECT p FROM PlaceBookBinder p WHERE p.state= :state",
PlaceBookBinder.class);
q.setParameter("state", State.PUBLISHED);
final List<PlaceBookBinder> pbs = q.getResultList();
final Collection<ShelfEntry> result = new ArrayList<ShelfEntry>();
if(!pbs.isEmpty())
{
final Random random = new Random();
for (int index = 0; index < count && !pbs.isEmpty(); index++)
{
final int rindex = random.nextInt(pbs.size());
final PlaceBookBinderSearchEntry entry =
new PlaceBookBinderSearchEntry(pbs.get(rindex), 0);
result.add(entry);
pbs.remove(rindex);
}
}
log.info("Converting " + result.size() + " PlaceBooks to JSON");
try
{
jsonMapper.writeValue(res.getWriter(), new Shelf(result));
res.setContentType("application/json");
res.flushBuffer();
}
catch (final Exception e)
{
log.error(e.toString());
}
}
finally
{
manager.close();
}
}
@RequestMapping(value = "/admin/serverinfo", method = RequestMethod.GET)
public void getServerInfoJSON(final HttpServletResponse res)
{
final ServerInfo si = new ServerInfo();
try
{
jsonMapper.writeValue(res.getWriter(), si);
res.setContentType("application/json");
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.toString());
}
}
@RequestMapping(value = "/admin/package/{key}", method = RequestMethod.GET)
public ModelAndView makePackage(final HttpServletResponse res,
@PathVariable("key") final String key)
{
final EntityManager pm = EMFSingleton.getEntityManager();
final PlaceBookBinder p = pm.find(PlaceBookBinder.class, key);
final File zipFile = PlaceBooksAdminHelper.makePackage(pm, p);
if (zipFile == null) { return new ModelAndView("message", "text", "Making and compressing package"); }
try
{
// Serve up file from disk
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final FileInputStream fis = new FileInputStream(zipFile);
final BufferedInputStream bis = new BufferedInputStream(fis);
final byte data[] = new byte[2048];
int i;
while ((i = bis.read(data, 0, 2048)) != -1)
{
bos.write(data, 0, i);
}
fis.close();
final ServletOutputStream sos = res.getOutputStream();
res.setContentType("application/zip");
res.setHeader("Content-Disposition", "attachment; filename=\"" + p.getKey() + ".zip\"");
res.addHeader("Content-Length", Integer.toString(bos.size()));
sos.write(bos.toByteArray());
sos.flush();
}
catch (final IOException e)
{
log.error(e.toString(), e);
return new ModelAndView("message", "text", "Error sending package");
}
finally
{
pm.close();
}
return null;
}
@RequestMapping(value = "/publishplacebookbinder",
method = RequestMethod.POST)
public void publishPlaceBookBinderJSON(final HttpServletResponse res,
@RequestParam("placebookbinder") final String json)
{
log.info("Publish PlacebookBinder: " + json);
final EntityManager manager = EMFSingleton.getEntityManager();
final User currentUser = UserManager.getCurrentUser(manager);
if (currentUser == null)
{
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try
{
res.getWriter().write("User not logged in");
}
catch (final IOException e)
{
e.printStackTrace();
}
return;
}
try
{
final ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
final PlaceBookBinder placebookBinder = mapper.readValue(json, PlaceBookBinder.class);
final PlaceBookBinder result =
PlaceBooksAdminHelper.savePlaceBookBinder(manager, placebookBinder);
log.debug("Saved PlacebookBinder:" + mapper.writeValueAsString(result));
log.info("Published PlacebookBinder:" + mapper.writeValueAsString(result));
final PlaceBookBinder published = PlaceBooksAdminHelper.publishPlaceBookBinder(manager, result);
jsonMapper.writeValue(res.getWriter(), published);
res.setContentType("application/json");
res.flushBuffer();
}
catch (final Throwable e)
{
log.warn(e.getMessage(), e);
}
finally
{
if (manager.getTransaction().isActive())
{
manager.getTransaction().rollback();
}
manager.close();
}
}
@RequestMapping(value = "/saveplacebookbinder", method = RequestMethod.POST)
public void savePlaceBookBinderJSON(final HttpServletResponse res,
@RequestParam("placebookbinder") final String json)
{
log.info("Save PlacebookBinder: " + json);
final EntityManager manager = EMFSingleton.getEntityManager();
final User currentUser = UserManager.getCurrentUser(manager);
if (currentUser == null)
{
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try
{
res.getWriter().write("User not logged in");
}
catch (final IOException e)
{
e.printStackTrace();
}
return;
}
try
{
final PlaceBookBinder placebookBinder = jsonMapper.readValue(json, PlaceBookBinder.class);
final PlaceBookBinder result =
PlaceBooksAdminHelper.savePlaceBookBinder(manager, placebookBinder);
jsonMapper.writeValue(res.getWriter(), result);
res.setContentType("application/json");
res.flushBuffer();
}
catch (final Throwable e)
{
log.info(json);
log.warn(e.getMessage(), e);
}
finally
{
if (manager.getTransaction().isActive())
{
manager.getTransaction().rollback();
}
manager.close();
}
}
@RequestMapping(value = "/admin/search/{terms}", method = RequestMethod.GET)
public void searchGET(final HttpServletResponse res,
@PathVariable("terms") final String terms)
{
final long timeStart = System.nanoTime();
final long timeEnd;
final EntityManager em = EMFSingleton.getEntityManager();
final Collection<ShelfEntry> pbs = new ArrayList<ShelfEntry>();
for (final Map.Entry<PlaceBookBinder, Integer> entry : PlaceBooksAdminHelper.search(em, terms))
{
final PlaceBookBinder p = entry.getKey();
if (p != null && p.getState() == PlaceBookBinder.State.PUBLISHED)
{
log.info("Search result: pb key=" + entry.getKey().getKey() + ", score=" + entry.getValue());
pbs.add(new PlaceBookBinderSearchEntry(p, entry.getValue()));
}
}
em.close();
try
{
jsonMapper.writeValue(res.getWriter(), new Shelf(pbs));
res.setContentType("application/json");
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.toString());
}
timeEnd = System.nanoTime();
log.info("Search execution time = " + (timeEnd - timeStart) + " ns");
}
@RequestMapping(value = "/admin/location_search/placebookitem/{geometry}", method = RequestMethod.GET)
public void searchLocationPlaceBookItemsGET(final HttpServletResponse res,
@PathVariable("geometry") final String geometry)
{
Geometry geometry_ = null;
try
{
geometry_ = new WKTReader().read(geometry);
}
catch (final ParseException e)
{
log.error(e.toString(), e);
return;
}
final EntityManager em = EMFSingleton.getEntityManager();
final Collection<ShelfEntry> ps = new ArrayList<ShelfEntry>();
for (final Map.Entry<PlaceBookItem, Double> entry : PlaceBooksAdminHelper
.searchLocationForPlaceBookItems(em, geometry_))
{
final PlaceBookItem p = entry.getKey();
if (p != null)
{
log.info("Search result: pbi key=" + entry.getKey().getKey() + ", distance=" + entry.getValue());
ps.add(new PlaceBookItemDistanceEntry(p, entry.getValue()));
}
}
em.close();
try
{
jsonMapper.writeValue(res.getWriter(), new Shelf(ps));
res.setContentType("application/json");
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.toString());
}
}
@RequestMapping(value = "/admin/location_search/placebookbinder/{geometry}",
method = RequestMethod.GET)
public void searchLocationPlaceBooksGET(final HttpServletResponse res,
@PathVariable("geometry") final String geometry)
{
Geometry geometry_ = null;
try
{
geometry_ = new WKTReader().read(geometry);
}
catch (final ParseException e)
{
log.error(e.toString(), e);
return;
}
final EntityManager em = EMFSingleton.getEntityManager();
final Collection<ShelfEntry> pbs = new ArrayList<ShelfEntry>();
for (final Map.Entry<PlaceBookBinder, Double> entry : PlaceBooksAdminHelper
.searchLocationForPlaceBookBinders(em, geometry_))
{
final PlaceBookBinder p = entry.getKey();
if (p != null)
{
log.info("Search result: pbb key=" + entry.getKey().getKey() + ", distance=" + entry.getValue());
pbs.add(new PlaceBookBinderDistanceEntry(p, entry.getValue()));
}
}
em.close();
try
{
jsonMapper.writeValue(res.getWriter(), new Shelf(pbs));
res.setContentType("application/json");
res.flushBuffer();
}
catch (final IOException e)
{
log.error(e.toString());
}
}
@RequestMapping(value = "/admin/search", method = RequestMethod.POST)
public void searchPOST(final HttpServletRequest req, final HttpServletResponse res)
{
final StringBuffer out = new StringBuffer();
final String[] terms = req.getParameter("terms").split("\\s");
for (int i = 0; i < terms.length; ++i)
{
out.append(terms[i]);
if (i < terms.length - 1)
{
out.append("+");
}
}
searchGET(res, out.toString());
}
@RequestMapping(value = "/admin/serve/gpstraceitem/{key}", method = RequestMethod.GET)
public void serveGPSTraceItem(final HttpServletResponse res,
@PathVariable("key") final String key)
{
final EntityManager em = EMFSingleton.getEntityManager();
log.info("Serving GPS Trace for " + key);
try
{
final GPSTraceItem g = em.find(GPSTraceItem.class, key);
if (g != null)
{
final String trace = g.getTrace();
res.setContentType("text/xml");
final PrintWriter p = res.getWriter();
p.print(trace);
p.close();
}
else
{
throw new Exception("GPSTrace is null");
}
}
catch (final Throwable e)
{
log.error(e.getMessage(), e);
}
finally
{
em.close();
}
}
@RequestMapping(value = "/admin/serve/imageitem/thumb/{key}", method = RequestMethod.GET)
public void serveImageItemThumb(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("key") final String key)
{
final EntityManager em = EMFSingleton.getEntityManager();
log.info("Serving ImageItem thumbnail: " + key);
try
{
final ImageItem i = em.find(ImageItem.class, key);
if (i != null)
{
log.info("ImageItem thumnail path:" + (i.getThumbPath() != null ? i.getThumbPath() : "null"));
if(i.getTimestamp() != null)
{
try
{
long lastModified = req.getDateHeader("If-Modified-Since");
if(lastModified >= i.getTimestamp().getTime())
{
res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
}
catch(Exception e)
{
log.warn(e.getMessage(), e);
}
res.addDateHeader("Last-Modified", i.getTimestamp().getTime());
}
ServeImage(i.getThumbPath(), res);
}
else
{
log.info("Image Item " + key + " not found in db");
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
catch (final Throwable e)
{
log.error(e.getMessage(), e);
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
try
{
e.printStackTrace(res.getWriter());
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
finally
{
em.close();
}
}
@RequestMapping(value = "/admin/serve/imageitem/{key}", method = RequestMethod.GET)
public void serveImageItem(final HttpServletRequest req, final HttpServletResponse res,
@PathVariable("key") final String key)
{
final EntityManager em = EMFSingleton.getEntityManager();
log.info("Serving Image Item: " + key);
try
{
final ImageItem i = em.find(ImageItem.class, key);
if (i != null)
{
String imagePath = i.getPath();
log.info("ImageItem path: " + (imagePath != null ? imagePath : "null"));
if(i.getTimestamp() != null)
{
try
{
long lastModified = req.getDateHeader("If-Modified-Since");
if(lastModified >= i.getTimestamp().getTime())
{
res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
}
catch(Exception e)
{
log.warn(e.getMessage(), e);
}
res.addDateHeader("Last-Modified", i.getTimestamp().getTime());
}
if (imagePath != null)
{
ServeImage(imagePath, res);
}
else
{
log.error("Image for ImageItem " + i.getKey() + " does not exist");
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
else
{
log.info("ImageItem " + key + " not found in db");
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
catch (final Throwable e)
{
log.error(e.getMessage(), e);
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
try
{
e.printStackTrace(res.getWriter());
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
finally
{
em.close();
}
}
private void ServeImage(String path, final HttpServletResponse res) throws IOException
{
log.debug("Serve image: " + path);
File image = new File(path);
final ImageInputStream iis = ImageIO.createImageInputStream(image);
final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
String fmt = "png";
while (readers.hasNext())
{
final ImageReader read = readers.next();
fmt = read.getFormatName();
read.dispose();
}
final OutputStream out = res.getOutputStream();
ImageIO.write(ImageIO.read(new File(path)), fmt, out);
out.close();
iis.close();
}
@RequestMapping(value = "/admin/serve/{type}item/{key}", method = RequestMethod.GET)
public void streamMediaItem(final HttpServletRequest req, final HttpServletResponse res,
@PathVariable("type") final String type, @PathVariable("key") final String key)
{
log.debug("Request for media: " + type + " " + key);
String path = null;
final EntityManager em = EMFSingleton.getEntityManager();
try
{
final MediaItem m = em.find(MediaItem.class, key);
if (m == null)
{
throw new Exception("Error getting media file, invalid key");
}
path = m.getPath();
}
catch (final Throwable e)
{
log.error(e.getMessage(), e);
}
finally
{
em.close();
}
if (path == null) { return; }
log.debug("Serving media: " + path);
try
{
String type_ = null;
if (type.trim().equalsIgnoreCase("video"))
{
type_ = "video";
}
else if (type.trim().equalsIgnoreCase("audio"))
{
type_ = "audio";
}
else
{
throw new Exception("Unrecognised media item type '" + type_ + "'");
}
final File file = new File(path);
String[] split = PlaceBooksAdminHelper.getExtension(path);
if (split == null)
{
split = new String[2];
split[1] = (type=="audio" ? "mp3" : "mpeg");
log.warn("Couildn't get name and extension for " + path + " defaulting to " + type + " and " + split[1]);
}
final ServletOutputStream sos = res.getOutputStream();
final FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = null;
long startByte = 0;
long endByte = file.length() - 1;
String contentType = type + "/" + split[1];
log.debug("Content type: " + contentType);
res.setContentType("Content type: " + contentType);
res.addHeader("Accept-Ranges", "bytes");
String range = req.getHeader("Range");
//log.debug(range);
if (range != null)
{
if (range.startsWith("bytes="))
{
try
{
//log.debug("Range string: " + range.substring(6));
final String[] rangeItems = range.substring(6).split("-");
switch(rangeItems.length)
{
case 0:
// do all of file (start and end already set above)
break;
case 1:
//set start position then go to end
startByte = Long.parseLong(rangeItems[0]);
break;
default:
// user start and end
startByte = Long.parseLong(rangeItems[0]);
endByte = Long.parseLong(rangeItems[1]);
break;
}
//log.debug("Range decoded: " + Long.toString(startByte) + " " + Long.toString(endByte));
}
catch (final Exception e)
{
log.error(e.getMessage());
}
}
}
bis = new BufferedInputStream(fis);
long totalLengthToSend = file.length() - startByte;
long totalLengthOfFile = file.length();
//log.debug("Serving " + type + " data range " + startByte + " to " + endByte + " of " + totalLengthOfFile);
res.setContentLength((int) totalLengthToSend);
res.addHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + totalLengthOfFile);
res.addHeader("ETag", "placebooks-video-" + key);
if(totalLengthOfFile>totalLengthToSend)
{
res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
}
final int bufferLen = 4096;
final byte data[] = new byte[bufferLen];
int totalBytesSent = 0;
int length = 0;
try
{
// Read only the number of bytes to left to send, in case it's less than the buffer size
// also start at the start byte
//log.debug("Reading " + Math.min(bufferLen, (totalLengthToSend - totalBytesSent)) + " bytes starting at " + startByte + " for a total of " + totalLengthToSend);
bis.skip(startByte);
length = bis.read(data, 0, (int) Math.min(bufferLen, (totalLengthToSend - totalBytesSent)));
while (length != -1)
{
sos.write(data, 0, length);
totalBytesSent += length;
//log.debug(totalBytesSent + " / " + totalLengthToSend + " remaining: " + (totalLengthToSend - totalBytesSent));
if(totalBytesSent >= totalLengthToSend)
{
length = -1;
}
else
{
//log.debug("Reading " + Math.min(bufferLen, (totalLengthToSend - totalBytesSent)) + " bytes starting at " + (startByte+totalBytesSent) + " for a total of " + totalLengthToSend);
length = bis.read(data, 0, (int) Math.min(bufferLen, (totalLengthToSend - totalBytesSent)));
//log.debug("Read bytes: " + length);
}
}
}
finally
{
sos.close();
fis.close();
}
}
catch (final Throwable e)
{
/*Enumeration headers = req.getHeaderNames();
while(headers.hasMoreElements())
{
String header = (String)headers.nextElement();
log.info(header + ": " + req.getHeader(header));
}*/
log.error("Error serving " + type + " " + key);
e.printStackTrace(System.out);
}
}
@RequestMapping(value = "/admin/xserve/{type}item/{key}", method = RequestMethod.GET)
public void streamTranscodedMediaItem(final HttpServletRequest req, final HttpServletResponse res,
@PathVariable("type") final String type, @PathVariable("key") final String key)
{
log.debug("Request for media: " + type + " " + key);
String path = null;
final EntityManager em = EMFSingleton.getEntityManager();
try
{
final MediaItem m = em.find(MediaItem.class, key);
if (m == null)
{
throw new Exception("Error getting media file, invalid key");
}
path = m.getPath() + "x.ogg";
}
catch (final Throwable e)
{
log.error(e.getMessage(), e);
}
finally
{
em.close();
}
if (path == null) { return; }
log.debug("Serving media: " + path);
try
{
String type_ = null;
if (type.trim().equalsIgnoreCase("video"))
{
type_ = "video";
}
else if (type.trim().equalsIgnoreCase("audio"))
{
type_ = "audio";
}
else
{
throw new Exception("Unrecognised media item type '" + type_ + "'");
}
final File file = new File(path);
String[] split = PlaceBooksAdminHelper.getExtension(path);
if (split == null)
{
split = new String[2];
split[1] = (type=="audio" ? "mp3" : "mpeg");
log.warn("Couildn't get name and extension for " + path + " defaulting to " + type + " and " + split[1]);
}
final ServletOutputStream sos = res.getOutputStream();
final FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = null;
long startByte = 0;
long endByte = file.length() - 1;
String contentType = type + "/" + split[1];
log.debug("Content type: " + contentType);
res.setContentType("Content type: " + contentType);
res.addHeader("Accept-Ranges", "bytes");
String range = req.getHeader("Range");
//log.debug(range);
if (range != null)
{
if (range.startsWith("bytes="))
{
try
{
//log.debug("Range string: " + range.substring(6));
final String[] rangeItems = range.substring(6).split("-");
switch(rangeItems.length)
{
case 0:
// do all of file (start and end already set above)
break;
case 1:
//set start position then go to end
startByte = Long.parseLong(rangeItems[0]);
break;
default:
// user start and end
startByte = Long.parseLong(rangeItems[0]);
endByte = Long.parseLong(rangeItems[1]);
break;
}
//log.debug("Range decoded: " + Long.toString(startByte) + " " + Long.toString(endByte));
}
catch (final Exception e)
{
log.error(e.getMessage());
}
}
}
bis = new BufferedInputStream(fis);
long totalLengthToSend = file.length() - startByte;
long totalLengthOfFile = file.length();
//log.debug("Serving " + type + " data range " + startByte + " to " + endByte + " of " + totalLengthOfFile);
res.setContentLength((int) totalLengthToSend);
res.addHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + totalLengthOfFile);
res.addHeader("ETag", "placebooks-video-" + key);
if(totalLengthOfFile>totalLengthToSend)
{
res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
}
final int bufferLen = 4096;
final byte data[] = new byte[bufferLen];
int totalBytesSent = 0;
int length = 0;
try
{
// Read only the number of bytes to left to send, in case it's less than the buffer size
// also start at the start byte
//log.debug("Reading " + Math.min(bufferLen, (totalLengthToSend - totalBytesSent)) + " bytes starting at " + startByte + " for a total of " + totalLengthToSend);
bis.skip(startByte);
length = bis.read(data, 0, (int) Math.min(bufferLen, (totalLengthToSend - totalBytesSent)));
while (length != -1)
{
sos.write(data, 0, length);
totalBytesSent += length;
//log.debug(totalBytesSent + " / " + totalLengthToSend + " remaining: " + (totalLengthToSend - totalBytesSent));
if(totalBytesSent >= totalLengthToSend)
{
length = -1;
}
else
{
//log.debug("Reading " + Math.min(bufferLen, (totalLengthToSend - totalBytesSent)) + " bytes starting at " + (startByte+totalBytesSent) + " for a total of " + totalLengthToSend);
length = bis.read(data, 0, (int) Math.min(bufferLen, (totalLengthToSend - totalBytesSent)));
//log.debug("Read bytes: " + length);
}
}
}
finally
{
sos.close();
fis.close();
}
}
catch (final Throwable e)
{
/*Enumeration headers = req.getHeaderNames();
while(headers.hasMoreElements())
{
String header = (String)headers.nextElement();
log.info(header + ": " + req.getHeader(header));
}*/
log.error("Error serving " + type + " " + key);
e.printStackTrace(System.out);
}
}
@RequestMapping(value = "/sync/{serviceName}", method = RequestMethod.GET)
public void syncService(final HttpServletResponse res, @PathVariable("serviceName") final String serviceName)
{
log.info("Sync " + serviceName);
final Service service = ServiceRegistry.getService(serviceName);
if (service != null)
{
final EntityManager manager = EMFSingleton.getEntityManager();
final User user = UserManager.getCurrentUser(manager);
service.sync(manager, user, true, Double.parseDouble(PropertiesSingleton.get(CommunicationHelper.class.getClassLoader()).getProperty(PropertiesSingleton.IDEN_SEARCH_LON, "0")),
Double.parseDouble(PropertiesSingleton.get(CommunicationHelper.class.getClassLoader()).getProperty(PropertiesSingleton.IDEN_SEARCH_LAT, "0")),
Double.parseDouble(PropertiesSingleton.get(CommunicationHelper.class.getClassLoader()).getProperty(PropertiesSingleton.IDEN_SEARCH_RADIUS, "0"))
);
}
res.setStatus(200);
}
@RequestMapping(value = "/admin/add_item/upload", method = RequestMethod.POST)
public ModelAndView uploadFile(final HttpServletRequest req)
{
final EntityManager manager = EMFSingleton.getEntityManager();
final ItemData itemData = new ItemData();
try
{
FileItem fileData = null;
String name = null;
String type = null;
String itemKey = null;
String placebookKey = null;
manager.getTransaction().begin();
@SuppressWarnings("unchecked")
final List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
for (final FileItem item : items)
{
if (item.isFormField())
{
final String value = Streams.asString(item.getInputStream());
if (!itemData.processItemData(manager, item.getFieldName(), value))
{
if (item.getFieldName().equals("key"))
{
placebookKey = value;
}
else if (item.getFieldName().equals("itemKey"))
{
itemKey = value;
}
}
}
else
{
name = item.getName();
fileData = item;
final String[] split = PlaceBooksAdminHelper.getExtension(item.getFieldName());
if (split == null)
{
continue;
}
type = split[0];
String dLimit = null, iden = null;
if (type.equals("image"))
{
iden = PropertiesSingleton.IDEN_IMAGE_MAX_SIZE;
dLimit = "1";
}
else if (type.equals("video"))
{
iden = PropertiesSingleton.IDEN_VIDEO_MAX_SIZE;
dLimit = "20";
}
else if (type.equals("audio"))
{
iden = PropertiesSingleton.IDEN_AUDIO_MAX_SIZE;
dLimit = "10";
}
if (dLimit != null && iden != null)
{
final int maxSize = Integer.parseInt(PropertiesSingleton.get( PlaceBooksAdminHelper.class
.getClassLoader())
.getProperty(iden, dLimit));
if ((item.getSize() / MEGABYTE) > maxSize) { throw new Exception("File too big, limit = "
+ Integer.toString(maxSize) + "Mb"); }
}
}
}
if (itemData.getOwner() == null)
{
itemData.setOwner(UserManager.getCurrentUser(manager));
}
PlaceBookItem item = null;
if (itemKey != null)
{
item = manager.find(PlaceBookItem.class, itemKey);
}
else if (placebookKey != null)
{
final PlaceBook placebook = manager.find(PlaceBook.class, placebookKey);
if (type.equals("gpstrace"))
{
item = new GPSTraceItem(itemData.getOwner(), itemData.getSourceURL(), null);
item.setPlaceBook(placebook);
}
else if (type.equals("image"))
{
item = new ImageItem(itemData.getOwner(), itemData.getGeometry(), itemData.getSourceURL(), null);
item.setPlaceBook(placebook);
}
else if (type.equals("video"))
{
item = new VideoItem(itemData.getOwner(), itemData.getGeometry(), itemData.getSourceURL(), null);
item.setPlaceBook(placebook);
}
else if (type.equals("audio"))
{
item = new AudioItem(itemData.getOwner(), itemData.getGeometry(), itemData.getSourceURL(), null);
item.setPlaceBook(placebook);
}
}
if (item instanceof MediaItem)
{
((MediaItem) item).setSourceURL(null);
((MediaItem) item).writeDataToDisk(name, fileData.getInputStream());
}
else if (item instanceof GPSTraceItem)
{
((GPSTraceItem) item).setSourceURL(null);
((GPSTraceItem) item).readTrace(fileData.getInputStream());
}
manager.getTransaction().commit();
return new ModelAndView("message", "text", "Success");
}
catch (final Exception e)
{
log.error(e.toString(), e);
}
finally
{
if (manager.getTransaction().isActive())
{
manager.getTransaction().rollback();
}
manager.close();
}
return new ModelAndView("message", "text", "Failed");
}
// TODO: needs to be viewPlaceBookBinder
@RequestMapping(value = "/view/{key}", method = RequestMethod.GET)
public void viewPlaceBook(final HttpServletRequest req, final HttpServletResponse res,
@PathVariable("key") final String key)
{
final EntityManager manager = EMFSingleton.getEntityManager();
try
{
final PlaceBook placebook = manager.find(PlaceBook.class, key);
if (placebook != null)
{
try
{
//if (placebook.getState() != State.PUBLISHED) { return; }
String urlbase;
if (req.getServerPort() != 80)
{
urlbase = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/";
}
else
{
urlbase = req.getScheme() + "://" + req.getServerName() + req.getContextPath() + "/";
}
final PrintWriter writer = res.getWriter();
writer.write("<!doctype html>");
writer.write("<html xmlns=\"http:
writer.write(" xmlns:og=\"http://ogp.me/ns
writer.write(" xmlns:fb=\"http:
writer.write("<head>");
writer.write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
writer.write("<title>" + placebook.getMetadataValue("title") + "</title>");
writer.write("<meta property=\"og:title\" content=\"" + placebook.getMetadataValue("title")
+ "\"/>");
writer.write("<meta property=\"og:type\" content=\"article\"/>");
// writer.write("<meta property=\"og:url\" content=\"" + urlbase + "#preview:" +
// placebook.getKey() + "\"/>");
if (placebook.getMetadataValue("placebookImage") != null)
{
writer.write("<meta property=\"og:image\" content=\"" + urlbase
+ "placebooks/a/admin/serve/imageitem/" + placebook.getMetadataValue("placebookImage")
+ "\"/>");
}
writer.write("<meta property=\"og:site_name\" content=\"PlaceBooks\"/>");
writer.write("<meta property=\"og:description\" content=\""
+ placebook.getMetadataValue("description") + "\"/>");
writer.write("<meta http-equiv=\"Refresh\" content=\"0; url=" + urlbase + "#preview:"
+ placebook.getKey() + "\" />");
writer.write("<link rel=\"icon\" type=\"image/png\" href=\"../../../images/Logo_016.png\" />");
writer.write("</head>");
writer.write("<body></body>");
writer.write("</html>");
writer.flush();
writer.close();
}
catch (final IOException e)
{
log.error(e.toString());
}
}
}
catch (final Throwable e)
{
log.error(e.getMessage(), e);
}
finally
{
manager.close();
}
}
}
|
package com.intellij.openapi.actionSystem;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.PossiblyDumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.util.SmartList;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
/**
* Represents an entity that has a state, a presentation and can be performed.
*
* For an action to be useful, you need to implement {@link AnAction#actionPerformed}
* and optionally to override {@link AnAction#update}. By overriding the
* {@link AnAction#update} method you can dynamically change action's presentation
* depending on the place (for more information on places see {@link com.intellij.openapi.actionSystem.ActionPlaces}.
*
* The same action can have various presentations.
*
* <pre>
* public class MyAction extends AnAction {
* public MyAction() {
* // ...
* }
*
* public void update(AnActionEvent e) {
* Presentation presentation = e.getPresentation();
* if (e.getPlace().equals(ActionPlaces.MAIN_MENU)) {
* presentation.setText("My Menu item name");
* } else if (e.getPlace().equals(ActionPlaces.MAIN_TOOLBAR)) {
* presentation.setText("My Toolbar item name");
* }
* }
*
* public void actionPerformed(AnActionEvent e) { ... }
* }
* </pre>
*
* @see AnActionEvent
* @see Presentation
* @see com.intellij.openapi.actionSystem.ActionPlaces
*/
public abstract class AnAction implements PossiblyDumbAware {
private static final Logger LOG = Logger.getInstance(AnAction.class);
public static final Key<List<AnAction>> ACTIONS_KEY = Key.create("AnAction.shortcutSet");
public static final AnAction[] EMPTY_ARRAY = new AnAction[0];
private Presentation myTemplatePresentation;
@NotNull
private ShortcutSet myShortcutSet = CustomShortcutSet.EMPTY;
private boolean myEnabledInModalContext;
private boolean myIsDefaultIcon = true;
private boolean myWorksInInjected;
/**
* Creates a new action with its text, description and icon set to {@code null}.
*/
public AnAction(){
// avoid eagerly creating template presentation
}
/**
* Creates a new action with {@code icon} provided. Its text, description set to {@code null}.
*
* @param icon Default icon to appear in toolbars and menus (Note some platform don't have icons in menu).
*/
public AnAction(Icon icon){
this(null, null, icon);
}
/**
* Creates a new action with the specified text. Description and icon are
* set to {@code null}.
*
* @param text Serves as a tooltip when the presentation is a button and the name of the
* menu item when the presentation is a menu item.
*/
public AnAction(@Nullable @Nls(capitalization = Nls.Capitalization.Title) String text){
this(text, null, null);
}
/**
* Constructs a new action with the specified text, description and icon.
*
* @param text Serves as a tooltip when the presentation is a button and the name of the
* menu item when the presentation is a menu item
*
* @param description Describes current action, this description will appear on
* the status bar when presentation has focus
*
* @param icon Action's icon
*/
public AnAction(@Nullable @Nls(capitalization = Nls.Capitalization.Title) String text,
@Nullable @Nls(capitalization = Nls.Capitalization.Sentence) String description,
@Nullable Icon icon) {
Presentation presentation = getTemplatePresentation();
presentation.setText(text);
presentation.setDescription(description);
presentation.setIcon(icon);
}
/**
* Returns the shortcut set associated with this action.
*
* @return shortcut set associated with this action
*/
@NotNull
public final ShortcutSet getShortcutSet(){
return myShortcutSet;
}
/**
* Registers a set of shortcuts that will be processed when the specified component
* is the ancestor of focused component. Note that the action doesn't have
* to be registered in action manager in order for that shortcut to work.
*
* @param shortcutSet the shortcuts for the action.
* @param component the component for which the shortcuts will be active.
*/
public final void registerCustomShortcutSet(@NotNull ShortcutSet shortcutSet, @Nullable JComponent component) {
registerCustomShortcutSet(shortcutSet, component, null);
}
public final void registerCustomShortcutSet(int keyCode, @JdkConstants.InputEventMask int modifiers, @Nullable JComponent component) {
registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(keyCode, modifiers)), component);
}
public final void registerCustomShortcutSet(@NotNull ShortcutSet shortcutSet, @Nullable JComponent component, @Nullable Disposable parentDisposable) {
setShortcutSet(shortcutSet);
registerCustomShortcutSet(component, parentDisposable);
}
public final void registerCustomShortcutSet(@Nullable JComponent component, @Nullable Disposable parentDisposable) {
if (component == null) return;
List<AnAction> actionList = UIUtil.getClientProperty(component, ACTIONS_KEY);
if (actionList == null) {
UIUtil.putClientProperty(component, ACTIONS_KEY, actionList = new SmartList<>());
}
if (!actionList.contains(this)) {
actionList.add(this);
}
if (parentDisposable != null) {
Disposer.register(parentDisposable, () -> unregisterCustomShortcutSet(component));
}
}
public final void unregisterCustomShortcutSet(@Nullable JComponent component) {
List<AnAction> actionList = UIUtil.getClientProperty(component, ACTIONS_KEY);
if (actionList != null) {
actionList.remove(this);
}
}
/**
* Copies template presentation and shortcuts set from {@code sourceAction}.
*/
public final void copyFrom(@NotNull AnAction sourceAction){
Presentation sourcePresentation = sourceAction.getTemplatePresentation();
Presentation presentation = getTemplatePresentation();
presentation.copyFrom(sourcePresentation);
copyShortcutFrom(sourceAction);
}
public final void copyShortcutFrom(@NotNull AnAction sourceAction) {
setShortcutSet(sourceAction.getShortcutSet());
}
public final boolean isEnabledInModalContext() {
return myEnabledInModalContext;
}
protected final void setEnabledInModalContext(boolean enabledInModalContext) {
myEnabledInModalContext = enabledInModalContext;
}
/**
* Override with true returned if your action has to display its text along with the icon when placed in the toolbar
*/
public boolean displayTextInToolbar() {
return false;
}
/**
* Override with true returned if your action displays text in a smaller font (same as toolbar combobox font) when placed in the toolbar
*/
public boolean useSmallerFontForTextInToolbar() {
return false;
}
/**
* Updates the state of the action. Default implementation does nothing.
* Override this method to provide the ability to dynamically change action's
* state and(or) presentation depending on the context (For example
* when your action state depends on the selection you can check for
* selection and change the state accordingly).<p></p>
*
* This method can be called frequently, and on UI thread.
* This means that this method is supposed to work really fast,
* no real work should be done at this phase. For example, checking selection in a tree or a list,
* is considered valid, but working with a file system or PSI (especially resolve) is not.
* If you cannot determine the state of the action fast enough,
* you should do it in the {@link #actionPerformed(AnActionEvent)} method and notify
* the user that action cannot be executed if it's the case.<p></p>
*
* If the action is added to a toolbar, its "update" can be called twice a second, but only if there was
* any user activity or a focus transfer. If your action's availability is changed
* in absence of any of these events, please call {@code ActivityTracker.getInstance().inc()} to notify
* action subsystem to update all toolbar actions when your subsystem's determines that its actions' visibility might be affected.
*
* @param e Carries information on the invocation place and data available
*/
public void update(@NotNull AnActionEvent e) {
}
/**
* Same as {@link #update(AnActionEvent)} but is calls immediately before actionPerformed() as final check guard.
* Default implementation delegates to {@link #update(AnActionEvent)}.
*
* @param e Carries information on the invocation place and data available
*/
public void beforeActionPerformedUpdate(@NotNull AnActionEvent e) {
boolean worksInInjected = isInInjectedContext();
e.setInjectedContext(worksInInjected);
update(e);
if (!e.getPresentation().isEnabled() && worksInInjected) {
e.setInjectedContext(false);
update(e);
}
}
/**
* Returns a template presentation that will be used
* as a template for created presentations.
*
* @return template presentation
*/
@NotNull
public final Presentation getTemplatePresentation() {
Presentation presentation = myTemplatePresentation;
if (presentation == null){
myTemplatePresentation = presentation = createTemplatePresentation();
}
return presentation;
}
@NotNull
Presentation createTemplatePresentation() {
return new Presentation();
}
/**
* Implement this method to provide your action handler.
*
* @param e Carries information on the invocation place
*/
public abstract void actionPerformed(@NotNull AnActionEvent e);
protected void setShortcutSet(@NotNull ShortcutSet shortcutSet) {
if (myShortcutSet != shortcutSet &&
!"ProxyShortcutSet".equals(shortcutSet.getClass().getSimpleName()) && // avoid CyclicDependencyException
ActionManager.getInstance() != null &&
ActionManager.getInstance().getId(this) != null) {
LOG.warn("ShortcutSet of global AnActions should not be changed outside of KeymapManager.\n" +
"This is likely not what you wanted to do. Consider setting shortcut in keymap defaults, inheriting from other action " +
"using `use-shortcut-of` or wrapping with EmptyAction.wrap().", new Throwable());
}
myShortcutSet = shortcutSet;
}
/**
* Sets the flag indicating whether the action has an internal or a user-customized icon.
* @param isDefaultIconSet true if the icon is internal, false if the icon is customized by the user.
*/
public void setDefaultIcon(boolean isDefaultIconSet) {
myIsDefaultIcon = isDefaultIconSet;
}
/**
* Returns true if the action has an internal, not user-customized icon.
* @return true if the icon is internal, false if the icon is customized by the user.
*/
public boolean isDefaultIcon() {
return myIsDefaultIcon;
}
/**
* Enables automatic detection of injected fragments in editor. Values in DataContext, passed to the action, like EDITOR, PSI_FILE
* will refer to an injected fragment, if caret is currently positioned on it.
*/
public void setInjectedContext(boolean worksInInjected) {
myWorksInInjected = worksInInjected;
}
public boolean isInInjectedContext() {
return myWorksInInjected;
}
public boolean isTransparentUpdate() {
return this instanceof TransparentUpdate;
}
/**
* @return whether this action should be wrapped into a single transaction. PSI/VFS-related actions
* that can show progresses or modal dialogs should return true. The default value is false, to prevent
* transaction-related assertions from actions in harmless dialogs like "Enter password" shown inside invokeLater.
* @see com.intellij.openapi.application.TransactionGuard
*/
public boolean startInTransaction() {
return false;
}
public interface TransparentUpdate {
}
@Nullable
public static Project getEventProject(AnActionEvent e) {
return e == null ? null : e.getData(CommonDataKeys.PROJECT);
}
@Override
public String toString() {
return getTemplatePresentation().toString();
}
/**
* Returns default action text.
* This method must be overridden in case template presentation contains user data like Project name,
* Run Configuration name, etc
*
* @return action presentable text without private user data
*/
@Nullable
@Nls(capitalization = Nls.Capitalization.Title)
public String getTemplateText() {
return getTemplatePresentation().getText();
}
}
|
package pt.iscte.lei.pi.firujo.scores;
import java.io.Serializable;
/*
* objecto score, contem um nome string e resultado int
* serializable para se poder gravar o estado do objecto em ficheiro
*/
public class Score implements Serializable{
private static final long serialVersionUID = 1L;
private int score;
private String name;
public Score(String name, int score){
this.score = score;
this.name = name;
}
public int getScore(){
return this.score;
}
public String getName(){
return this.name;
}
}
|
package helper;
import java.io.File;
import java.lang.Process;
import java.lang.ProcessBuilder;
import models.Gatherconf;
import play.Logger;
public class WpullThread extends Thread {
Gatherconf conf = null;
ProcessBuilder pb = null;
File log = null;
private static final Logger.ALogger WebgatherLogger =
Logger.of("webgatherer");
public WpullThread(Gatherconf conf, ProcessBuilder pb, File log) {
this.conf = conf;
this.pb = pb;
this.log = log;
}
public void run() {
try {
Process proc = pb.start();
assert pb.redirectInput() == ProcessBuilder.Redirect.PIPE;
assert pb.redirectOutput().file() == log;
assert proc.getInputStream().read() == -1;
int exitState = proc.waitFor();
WebgatherLogger.info("Webcrawl for " + conf.getName()
+ " exited with exitState " + exitState);
if (exitState != 0) {
WpullThread wpullThread = new WpullThread(conf, pb, log);
wpullThread.start();
}
} catch (Exception e) {
WebgatherLogger.error(e.toString());
throw new RuntimeException("wpull crawl not successfully started!", e);
}
}
}
|
package cpw.mods.fml.common;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import com.google.common.base.Joiner;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Iterators;
import com.google.common.collect.Multimap;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import cpw.mods.fml.common.LoaderState.ModState;
import cpw.mods.fml.common.event.FMLConstructionEvent;
import cpw.mods.fml.common.event.FMLLoadEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLStateEvent;
import cpw.mods.fml.common.network.FMLNetworkHandler;
public class LoadController
{
private Loader loader;
private EventBus masterChannel;
private ImmutableMap<String,EventBus> eventChannels;
private LoaderState state;
private Multimap<String, ModState> modStates = ArrayListMultimap.create();
private Multimap<String, Throwable> errors = ArrayListMultimap.create();
private Map<String, ModContainer> modList;
private List<ModContainer> activeModList = Lists.newArrayList();
private String activeContainer;
private BiMap<ModContainer, Object> modObjectList;
public LoadController(Loader loader)
{
this.loader = loader;
this.masterChannel = new EventBus("FMLMainChannel");
this.masterChannel.register(this);
state = LoaderState.NOINIT;
}
@Subscribe
public void buildModList(FMLLoadEvent event)
{
this.modList = loader.getIndexedModList();
Builder<String, EventBus> eventBus = ImmutableMap.builder();
for (ModContainer mod : loader.getModList())
{
EventBus bus = new EventBus(mod.getModId());
boolean isActive = mod.registerBus(bus, this);
if (isActive)
{
FMLLog.fine("Activating mod %s", mod.getModId());
activeModList.add(mod);
modStates.put(mod.getModId(), ModState.UNLOADED);
eventBus.put(mod.getModId(), bus);
}
else
{
FMLLog.warning("Mod %s has been disabled through configuration", mod.getModId());
modStates.put(mod.getModId(), ModState.UNLOADED);
modStates.put(mod.getModId(), ModState.DISABLED);
}
}
eventChannels = eventBus.build();
}
public void distributeStateMessage(LoaderState state, Object... eventData)
{
if (state.hasEvent())
{
masterChannel.post(state.getEvent(eventData));
}
}
public void transition(LoaderState desiredState)
{
LoaderState oldState = state;
state = state.transition(!errors.isEmpty());
if (state != desiredState)
{
FMLLog.severe("Fatal errors were detected during the transition from %s to %s. Loading cannot continue", oldState, desiredState);
StringBuilder sb = new StringBuilder();
printModStates(sb);
FMLLog.severe(sb.toString());
FMLLog.severe("The following problems were captured during this phase");
for (Entry<String, Throwable> error : errors.entries())
{
FMLLog.log(Level.SEVERE, error.getValue(), "Caught exception from %s", error.getKey());
}
// Throw embedding the first error (usually the only one)
throw new LoaderException(errors.values().iterator().next());
}
}
public ModContainer activeContainer()
{
return activeContainer!=null ? modList.get(activeContainer) : null;
}
@Subscribe
public void propogateStateMessage(FMLStateEvent stateEvent)
{
if (stateEvent instanceof FMLPreInitializationEvent)
{
modObjectList = buildModObjectList();
}
for (Map.Entry<String,EventBus> entry : eventChannels.entrySet())
{
activeContainer = entry.getKey();
stateEvent.applyModContainer(activeContainer());
FMLLog.finer("Posting state event %s to mod %s", stateEvent, entry.getKey());
entry.getValue().post(stateEvent);
FMLLog.finer("State event %s delivered to mod %s", stateEvent, entry.getKey());
activeContainer = null;
if (!errors.containsKey(entry.getKey()))
{
modStates.put(entry.getKey(), stateEvent.getModState());
}
else
{
modStates.put(entry.getKey(), ModState.ERRORED);
}
}
}
public ImmutableBiMap<ModContainer, Object> buildModObjectList()
{
ImmutableBiMap.Builder<ModContainer, Object> builder = ImmutableBiMap.<ModContainer, Object>builder();
for (ModContainer mc : activeModList)
{
if (!mc.isImmutable() && mc.getMod()!=null)
{
builder.put(mc, mc.getMod());
}
if (mc.getMod()==null)
{
FMLLog.severe("There is a severe problem with %s - it appears not to have constructed correctly", mc.getModId());
if (state != LoaderState.CONSTRUCTING)
{
this.errorOccurred(mc, new RuntimeException());
}
}
}
return builder.build();
}
public void errorOccurred(ModContainer modContainer, Throwable exception)
{
errors.put(modContainer.getModId(), exception);
}
public void printModStates(StringBuilder ret)
{
for (String modId : modStates.keySet())
{
ModContainer mod = modList.get(modId);
ret.append("\n\t").append(mod.getName()).append(" (").append(mod.getSource().getName()).append(") ");
Joiner.on("->"). appendTo(ret, modStates.get(modId));
}
}
public List<ModContainer> getActiveModList()
{
return activeModList;
}
public ModState getModState(ModContainer selectedMod)
{
return Iterables.getLast(modStates.get(selectedMod.getModId()), ModState.AVAILABLE);
}
public void distributeStateMessage(Class<?> customEvent)
{
try
{
masterChannel.post(customEvent.newInstance());
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "An unexpected exception");
throw new LoaderException(e);
}
}
public BiMap<ModContainer, Object> getModObjectList()
{
if (modObjectList == null)
{
FMLLog.severe("Detected an attempt by a mod %s to perform game activity during mod construction. This is a serious programming error.", activeContainer);
return buildModObjectList();
}
return ImmutableBiMap.copyOf(modObjectList);
}
public boolean isInState(LoaderState state)
{
return this.state == state;
}
}
|
package com.intellij;
import com.intellij.openapi.util.SystemInfoRt;
import com.intellij.util.text.OrdinalFormat;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* @author yole
*/
public abstract class BundleBase {
public static final char MNEMONIC = 0x1B;
public static final String MNEMONIC_STRING = Character.toString(MNEMONIC);
private static boolean assertOnMissedKeys = false;
public static void assertOnMissedKeys(boolean doAssert) {
assertOnMissedKeys = doAssert;
}
@NotNull
public static String message(@NotNull ResourceBundle bundle, @NotNull String key, @NotNull Object... params) {
return messageOrDefault(bundle, key, null, params);
}
public static String messageOrDefault(@Nullable ResourceBundle bundle,
@NotNull String key,
@Nullable String defaultValue,
@NotNull Object... params) {
if (bundle == null) return defaultValue;
String value;
try {
value = bundle.getString(key);
}
catch (MissingResourceException e) {
value = useDefaultValue(bundle, key, defaultValue);
}
return postprocessValue(bundle, value, params);
}
@NotNull
static String useDefaultValue(@Nullable ResourceBundle bundle, @NotNull String key, @Nullable String defaultValue) {
if (defaultValue != null) {
return defaultValue;
}
if (assertOnMissedKeys) {
assert false : "'" + key + "' is not found in " + bundle;
}
return "!" + key + "!";
}
@Nullable
static String postprocessValue(@NotNull ResourceBundle bundle, String value, @NotNull Object[] params) {
value = replaceMnemonicAmpersand(value);
if (params.length > 0 && value.indexOf('{') >= 0) {
Locale locale = bundle.getLocale();
try {
MessageFormat format = locale != null ? new MessageFormat(value, locale) : new MessageFormat(value);
OrdinalFormat.apply(format);
value = format.format(params);
}
catch (IllegalArgumentException e) {
value = "!invalid format: `" + value + "`!";
}
}
return value;
}
@NotNull
public static String format(@NotNull String value, @NotNull Object... params) {
return params.length > 0 && value.indexOf('{') >= 0 ? MessageFormat.format(value, params) : value;
}
public static String replaceMnemonicAmpersand(@Nullable String value) {
if (value == null || value.indexOf('&') < 0) {
return value;
}
StringBuilder builder = new StringBuilder();
boolean macMnemonic = value.contains("&&");
int i = 0;
while (i < value.length()) {
char c = value.charAt(i);
if (c == '\\') {
if (i < value.length() - 1 && value.charAt(i + 1) == '&') {
builder.append('&');
i++;
}
else {
builder.append(c);
}
}
else if (c == '&') {
if (i < value.length() - 1 && value.charAt(i + 1) == '&') {
if (SystemInfoRt.isMac) {
builder.append(MNEMONIC);
}
i++;
}
else if (!SystemInfoRt.isMac || !macMnemonic) {
builder.append(MNEMONIC);
}
}
else {
builder.append(c);
}
i++;
}
return builder.toString();
}
}
|
package com.intellij.openapi.command.impl;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.undo.DocumentReference;
import com.intellij.openapi.command.undo.UndoableAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorState;
import com.intellij.openapi.fileEditor.FileEditorStateLevel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
abstract class UndoRedo {
protected final UndoManagerImpl myManager;
protected final FileEditor myEditor;
protected final UndoableGroup myUndoableGroup;
//public static void execute(UndoManagerImpl manager, FileEditor editor, boolean isUndo) {
// UndoRedo undoOrRedo = isUndo ? new Undo(manager, editor) : new Redo(manager, editor);
// undoOrRedo.doExecute();
// boolean shouldRepeat = undoOrRedo.isTransparent() && undoOrRedo.hasMoreActions();
// if (!shouldRepeat) break;
// while (true);
protected UndoRedo(UndoManagerImpl manager, FileEditor editor) {
myManager = manager;
myEditor = editor;
myUndoableGroup = getLastAction();
}
private UndoableGroup getLastAction() {
return getStackHolder().getLastAction(getDecRefs());
}
boolean isTransparent() {
return myUndoableGroup.isTransparent();
}
boolean isTemporary() {
return myUndoableGroup.isTemporary();
}
boolean hasMoreActions() {
return getStackHolder().canBeUndoneOrRedone(getDecRefs());
}
private Set<DocumentReference> getDecRefs() {
return myEditor == null ? Collections.emptySet() : UndoManagerImpl.getDocumentReferences(myEditor);
}
protected abstract UndoRedoStacksHolder getStackHolder();
protected abstract UndoRedoStacksHolder getReverseStackHolder();
protected abstract String getActionName();
protected abstract String getActionName(String commandName);
protected abstract EditorAndState getBeforeState();
protected abstract EditorAndState getAfterState();
protected abstract void performAction();
protected abstract void setBeforeState(EditorAndState state);
public boolean execute(boolean drop, boolean disableConfirmation) {
if (!myUndoableGroup.isUndoable()) {
reportCannotUndo(IdeBundle.message("cannot.undo.error.contains.nonundoable.changes.message"),
myUndoableGroup.getAffectedDocuments());
return false;
}
Set<DocumentReference> clashing = getStackHolder().collectClashingActions(myUndoableGroup);
if (!clashing.isEmpty()) {
reportCannotUndo(IdeBundle.message("cannot.undo.error.other.affected.files.changed.message"), clashing);
return false;
}
if (!disableConfirmation && myUndoableGroup.shouldAskConfirmation(isRedo()) && !UndoManagerImpl.ourNeverAskUser) {
if (!askUser()) return false;
}
else {
if (restore(getBeforeState(), true)) {
setBeforeState(new EditorAndState(myEditor, myEditor.getState(FileEditorStateLevel.UNDO)));
return true;
}
}
Collection<VirtualFile> readOnlyFiles = collectReadOnlyAffectedFiles();
if (!readOnlyFiles.isEmpty()) {
final Project project = myManager.getProject();
if (project == null) {
return false;
}
final ReadonlyStatusHandler.OperationStatus operationStatus = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(readOnlyFiles);
if (operationStatus.hasReadonlyFiles()) {
return false;
}
}
Collection<Document> readOnlyDocuments = collectReadOnlyDocuments();
if (!readOnlyDocuments.isEmpty()) {
for (Document document : readOnlyDocuments) {
document.fireReadOnlyModificationAttempt();
}
return false;
}
getStackHolder().removeFromStacks(myUndoableGroup);
if (!drop) {
getReverseStackHolder().addToStacks(myUndoableGroup);
}
performAction();
restore(getAfterState(), false);
return true;
}
protected abstract boolean isRedo();
private Collection<Document> collectReadOnlyDocuments() {
Collection<Document> readOnlyDocs = new ArrayList<>();
for (UndoableAction action : myUndoableGroup.getActions()) {
if (action instanceof MentionOnlyUndoableAction) continue;
DocumentReference[] refs = action.getAffectedDocuments();
if (refs == null) continue;
for (DocumentReference ref : refs) {
if (ref instanceof DocumentReferenceByDocument) {
Document doc = ref.getDocument();
if (doc != null && !doc.isWritable()) readOnlyDocs.add(doc);
}
}
}
return readOnlyDocs;
}
private Collection<VirtualFile> collectReadOnlyAffectedFiles() {
Collection<VirtualFile> readOnlyFiles = new ArrayList<>();
for (UndoableAction action : myUndoableGroup.getActions()) {
if (action instanceof MentionOnlyUndoableAction) continue;
DocumentReference[] refs = action.getAffectedDocuments();
if (refs == null) continue;
for (DocumentReference ref : refs) {
VirtualFile file = ref.getFile();
if ((file != null) && file.isValid() && !file.isWritable()) {
readOnlyFiles.add(file);
}
}
}
return readOnlyFiles;
}
private void reportCannotUndo(String message, Collection<? extends DocumentReference> problemFiles) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
throw new RuntimeException(
message + "\n" + StringUtil.join(problemFiles, StringUtil.createToStringFunction(DocumentReference.class), "\n"));
}
new CannotUndoReportDialog(myManager.getProject(), message, problemFiles).show();
}
private boolean askUser() {
String actionText = getActionName(myUndoableGroup.getCommandName());
return Messages.showOkCancelDialog(myManager.getProject(), actionText + "?", getActionName(),
Messages.getQuestionIcon()) == Messages.OK;
}
boolean confirmSwitchTo(@NotNull UndoRedo other) {
String message = IdeBundle.message("undo.conflicting.change.confirmation") + "\n" +
getActionName(other.myUndoableGroup.getCommandName()) + "?";
return Messages.showOkCancelDialog(myManager.getProject(), message, getActionName(),
Messages.getQuestionIcon()) == Messages.OK;
}
private boolean restore(EditorAndState pair, boolean onlyIfDiffers) {
// editor can be invalid if underlying file is deleted during undo (e.g. after undoing scratch file creation)
if (pair == null || myEditor == null || !myEditor.isValid() || !pair.canBeAppliedTo(myEditor)) return false;
// If current editor state isn't equals to remembered state then
// we have to try to restore previous state. But sometime it's
// not possible to restore it. For example, it's not possible to
// restore scroll proportion if editor doesn not have scrolling any more.
FileEditorState currentState = myEditor.getState(FileEditorStateLevel.UNDO);
if (onlyIfDiffers && currentState.equals(pair.getState())) {
return false;
}
myEditor.setState(pair.getState());
return true;
}
public boolean isBlockedByOtherChanges() {
return myUndoableGroup.isGlobal() && myUndoableGroup.isUndoable() &&
!getStackHolder().collectClashingActions(myUndoableGroup).isEmpty();
}
}
|
package com.intellij.remote.ui;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.ExecutionException;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.remote.CredentialsType;
import com.intellij.remote.RemoteSdkAdditionalData;
import com.intellij.remote.RemoteSdkCredentials;
import com.intellij.remote.RemoteSdkException;
import com.intellij.remote.ext.*;
import com.intellij.ui.ComponentUtil;
import com.intellij.ui.ContextHelpLabel;
import com.intellij.ui.StatusPanel;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBRadioButton;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.List;
import java.util.*;
abstract public class CreateRemoteSdkForm<T extends RemoteSdkAdditionalData> extends JPanel implements RemoteSdkEditorForm, Disposable {
private JPanel myMainPanel;
private JBLabel myInterpreterPathLabel;
protected TextFieldWithBrowseButton myInterpreterPathField;
protected TextFieldWithBrowseButton myHelpersPathField;
private JTextField myNameField;
private JBLabel myNameLabel;
private JBLabel myHelpersPathLabel;
private JPanel myStatusPanelHolder;
private final StatusPanel myStatusPanel;
private JPanel myRadioPanel;
private JPanel myTypesPanel;
private JPanel myRunAsRootViaSudoPanel;
private JBCheckBox myRunAsRootViaSudoJBCheckBox;
private JPanel myRunAsRootViaSudoHelpPanel;
private ButtonGroup myTypeButtonGroup;
private boolean myNameVisible;
private final Project myProject;
@NotNull
private final RemoteSdkEditorContainer myParentContainer;
private final Runnable myValidator;
@NotNull
private final BundleAccessor myBundleAccessor;
private boolean myTempFilesPathVisible;
private CredentialsType myConnectionType;
private final Map<CredentialsType, TypeHandler> myCredentialsType2Handler;
private final Set<CredentialsType> myUnsupportedConnectionTypes = new HashSet<>();
@NotNull
private final SdkScopeController mySdkScopeController;
public CreateRemoteSdkForm(@Nullable Project project,
@NotNull RemoteSdkEditorContainer parentContainer,
@Nullable Runnable validator,
@NotNull final BundleAccessor bundleAccessor) {
this(project, parentContainer, ApplicationOnlySdkScopeController.INSTANCE, validator, bundleAccessor);
}
public CreateRemoteSdkForm(@Nullable Project project,
@NotNull RemoteSdkEditorContainer parentContainer,
@NotNull SdkScopeController sdkScopeController,
@Nullable Runnable validator,
@NotNull final BundleAccessor bundleAccessor) {
super(new BorderLayout());
myProject = project;
myParentContainer = parentContainer;
Disposer.register(parentContainer.getDisposable(), this);
mySdkScopeController = sdkScopeController;
myBundleAccessor = bundleAccessor;
myValidator = validator;
add(myMainPanel, BorderLayout.CENTER);
myStatusPanel = new StatusPanel();
myStatusPanelHolder.setLayout(new BorderLayout());
myStatusPanelHolder.add(myStatusPanel, BorderLayout.CENTER);
setNameVisible(false);
setTempFilesPathVisible(false);
myInterpreterPathLabel.setLabelFor(myInterpreterPathField.getTextField());
myInterpreterPathLabel.setText(myBundleAccessor.message("remote.interpreter.configure.path.label"));
myHelpersPathLabel.setText(myBundleAccessor.message("remote.interpreter.configure.temp.files.path.label"));
myInterpreterPathField.addActionListener(e -> {
showBrowsePathsDialog(myInterpreterPathField, myBundleAccessor.message("remote.interpreter.configure.path.title"));
});
myHelpersPathField.addActionListener(e -> {
showBrowsePathsDialog(myHelpersPathField, myBundleAccessor.message("remote.interpreter.configure.temp.files.path.title"));
});
myTypesPanel.setLayout(new ResizingCardLayout());
myCredentialsType2Handler = new HashMap<>();
installExtendedTypes(project);
installRadioListeners(myCredentialsType2Handler.values());
if (isSshSudoSupported()) {
myRunAsRootViaSudoJBCheckBox.setText(
bundleAccessor.message("remote.interpreter.configure.ssh.run_as_root_via_sudo.checkbox"));
myRunAsRootViaSudoHelpPanel.add(ContextHelpLabel.create(
bundleAccessor.message("remote.interpreter.configure.ssh.run_as_root_via_sudo.help")),
BorderLayout.WEST);
}
else {
myRunAsRootViaSudoPanel.setVisible(false);
}
// select the first credentials type for the start
Iterator<TypeHandler> iterator = myCredentialsType2Handler.values().iterator();
if (iterator.hasNext()) {
iterator.next().getRadioButton().setSelected(true);
}
radioSelected(true);
}
public void showBrowsePathsDialog(@NotNull TextFieldWithBrowseButton textFieldWithBrowseButton, @NotNull String dialogTitle) {
if (myConnectionType instanceof PathsBrowserDialogProvider) {
((PathsBrowserDialogProvider)myConnectionType).showPathsBrowserDialog(
myProject, textFieldWithBrowseButton.getTextField(),
dialogTitle,
() -> createSdkDataInner()
);
}
}
protected void disableChangeTypePanel() {
myRadioPanel.setVisible(false);
}
private void installRadioListeners(@NotNull final Collection<TypeHandler> values) {
ActionListener l = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
radioSelected(true);
}
};
for (TypeHandler typeHandler : values) {
typeHandler.getRadioButton().addActionListener(l);
}
}
private void installExtendedTypes(@Nullable Project project) {
for (final CredentialsTypeEx typeEx : CredentialsManager.getInstance().getExTypes()) {
CredentialsEditorProvider editorProvider = ObjectUtils.tryCast(typeEx, CredentialsEditorProvider.class);
if (editorProvider != null) {
final List<CredentialsLanguageContribution> contributions = getContributions();
if (!contributions.isEmpty()) {
for (CredentialsLanguageContribution contribution : contributions) {
if (contribution.getType() == typeEx && editorProvider.isAvailable(contribution)) {
final CredentialsEditor<?> editor = editorProvider.createEditor(project, contribution, this);
trackEditorLabelsColumn(editor);
JBRadioButton typeButton = new JBRadioButton(editor.getName());
myTypeButtonGroup.add(typeButton);
myRadioPanel.add(typeButton);
final JPanel editorMainPanel = editor.getMainPanel();
myTypesPanel.add(editorMainPanel, typeEx.getName());
myCredentialsType2Handler.put(typeEx,
new TypeHandlerEx(typeButton,
editorMainPanel,
editorProvider.getDefaultInterpreterPath(myBundleAccessor),
typeEx,
editor));
// set initial connection type
if (myConnectionType == null) {
myConnectionType = typeEx;
}
}
}
}
}
}
}
@NotNull
protected List<CredentialsLanguageContribution> getContributions() {
return Collections.emptyList();
}
@NotNull
@Override
public final SdkScopeController getSdkScopeController() {
return mySdkScopeController;
}
private void radioSelected(boolean propagateEvent) {
CredentialsType selectedType = getSelectedType();
CardLayout layout = (CardLayout)myTypesPanel.getLayout();
layout.show(myTypesPanel, selectedType.getName());
changeWindowHeightToPreferred();
setBrowseButtonsVisible(myCredentialsType2Handler.get(selectedType).isBrowsingAvailable());
if (propagateEvent) {
myStatusPanel.resetState();
// store interpreter path entered for previously selected type
String interpreterPath = myInterpreterPathField.getText();
if (StringUtil.isNotEmpty(interpreterPath)) {
myCredentialsType2Handler.get(myConnectionType).setInterpreterPath(interpreterPath);
}
myConnectionType = selectedType;
TypeHandler typeHandler = myCredentialsType2Handler.get(myConnectionType);
myInterpreterPathField.setText(typeHandler.getInterpreterPath());
typeHandler.onSelected();
}
else {
myCredentialsType2Handler.get(selectedType).onInit();
}
}
private void changeWindowHeightToPreferred() {
final Window window = ComponentUtil.getWindow(myMainPanel);
if (window != null) {
ApplicationManager.getApplication().invokeLater(() -> {
Dimension currentSize = window.getSize();
Dimension preferredSize = window.getPreferredSize();
window.setSize(currentSize.width, preferredSize.height);
}, ModalityState.stateForComponent(window));
}
}
private CredentialsType getSelectedType() {
for (Map.Entry<CredentialsType, TypeHandler> type2handler : myCredentialsType2Handler.entrySet()) {
if (type2handler.getValue().getRadioButton().isSelected()) {
return type2handler.getKey();
}
}
throw new IllegalStateException();
}
private void setBrowseButtonsVisible(boolean visible) {
myInterpreterPathField.getButton().setVisible(visible);
myHelpersPathField.getButton().setVisible(visible);
}
// TODO: (next) may propose to start DockerMachine - somewhere
@NotNull
public final RemoteSdkCredentials computeSdkCredentials() throws ExecutionException, InterruptedException {
final T sdkData = createSdkDataInner();
return sdkData.getRemoteSdkCredentials(myProject, true);
}
@Nullable
public JComponent getPreferredFocusedComponent() {
if (myNameVisible) {
return myNameField;
}
else {
final CredentialsType selectedType = getSelectedType();
final TypeHandler typeHandler = myCredentialsType2Handler.get(selectedType);
if (typeHandler != null) {
JComponent preferredFocusedComponent = UIUtil.getPreferredFocusedComponent(typeHandler.getContentComponent());
if (preferredFocusedComponent != null) return preferredFocusedComponent;
}
return myTypesPanel;
}
}
public T createSdkData() throws RemoteSdkException {
return createSdkDataInner();
}
protected T createSdkDataInner() {
final T sdkData = doCreateSdkData(getInterpreterPath());//todo ???
//if (!myCredentialsType2Handler.containsKey(sdkData.getRemoteConnectionType())) return sdkData;
// ArrayUtil.mergeArrays(cases, exCases.toArray(new CredentialsCase[exCases.size()]))
myConnectionType.saveCredentials(
sdkData,
new CaseCollector() {
@Override
protected void processEx(CredentialsEditor editor, Object credentials) {
editor.saveCredentials(credentials);
}
}.collectCases());
sdkData.setRunAsRootViaSudo(myRunAsRootViaSudoJBCheckBox.isSelected());
sdkData.setHelpersPath(getTempFilesPath());
return sdkData;
}
@NotNull
abstract protected T doCreateSdkData(@NotNull String interpreterPath);
private void setNameVisible(boolean visible) {
myNameField.setVisible(visible);
myNameLabel.setVisible(visible);
myNameVisible = visible;
}
public void setSdkName(String name) {
if (name != null) {
setNameVisible(true);
myNameField.setText(name);
}
}
public void init(final @NotNull T data) {
myConnectionType = data.connectionCredentials().getRemoteConnectionType();
TypeHandler typeHandler = myCredentialsType2Handler.get(myConnectionType);
if (typeHandler == null) {
typeHandler = createUnsupportedConnectionTypeHandler();
myUnsupportedConnectionTypes.add(myConnectionType);
myCredentialsType2Handler.put(myConnectionType, typeHandler);
myTypeButtonGroup.add(typeHandler.getRadioButton());
myRadioPanel.add(typeHandler.getRadioButton());
myTypesPanel.add(typeHandler.getContentComponent(), myConnectionType.getName());
}
typeHandler.getRadioButton().setSelected(true);
boolean connectionTypeIsSupported = !myUnsupportedConnectionTypes.contains(myConnectionType);
myRadioPanel.setVisible(connectionTypeIsSupported);
data.switchOnConnectionType(
new CaseCollector() {
@Override
protected void processEx(CredentialsEditor editor, Object credentials) {
editor.init(credentials);
}
}.collectCases());
radioSelected(false);
String interpreterPath = data.getInterpreterPath();
myInterpreterPathField.setText(interpreterPath);
typeHandler.setInterpreterPath(interpreterPath);
setTempFilesPath(data);
if (isSshSudoSupported()) {
myRunAsRootViaSudoJBCheckBox.setSelected(data.isRunAsRootViaSudo());
}
}
@NotNull
private TypeHandler createUnsupportedConnectionTypeHandler() {
JBRadioButton typeButton = new JBRadioButton(myConnectionType.getName());
JPanel typeComponent = new JPanel(new BorderLayout());
String errorMessage = ExecutionBundle.message("remote.interpreter.cannot.load.interpreter.message", myConnectionType.getName());
JBLabel errorLabel = new JBLabel(errorMessage);
errorLabel.setIcon(AllIcons.General.BalloonError);
typeComponent.add(errorLabel, BorderLayout.CENTER);
return new TypeHandler(typeButton, typeComponent, null) {
@Override
public void onInit() {
}
@Override
public void onSelected() {
}
@Override
public ValidationInfo validate() {
return null;
}
@Nullable
@Override
public String validateFinal() {
return null;
}
};
}
private void setTempFilesPath(RemoteSdkAdditionalData data) {
myHelpersPathField.setText(data.getHelpersPath());
if (!StringUtil.isEmpty(data.getHelpersPath())) {
setTempFilesPathVisible(true);
}
}
protected void setTempFilesPathVisible(boolean visible) {
myHelpersPathField.setVisible(visible);
myHelpersPathLabel.setVisible(visible);
myTempFilesPathVisible = visible;
}
protected void setInterpreterPathVisible(boolean visible) {
myInterpreterPathField.setVisible(visible);
myInterpreterPathLabel.setVisible(visible);
}
public String getInterpreterPath() {
return myInterpreterPathField.getText().trim();
}
public String getTempFilesPath() {
return myHelpersPathField.getText();
}
@Nullable
public ValidationInfo validateRemoteInterpreter() {
TypeHandler typeHandler = myCredentialsType2Handler.get(getSelectedType());
if (StringUtil.isEmpty(getInterpreterPath())) {
return new ValidationInfo(
myBundleAccessor.message("remote.interpreter.unspecified.interpreter.path"),
myInterpreterPathField);
}
if (myTempFilesPathVisible) {
if (StringUtil.isEmpty(getTempFilesPath())) {
return new ValidationInfo(myBundleAccessor.message("remote.interpreter.unspecified.temp.files.path"), myHelpersPathField);
}
}
return typeHandler.validate();
}
@Nullable
public String getSdkName() {
if (myNameVisible) {
return myNameField.getText().trim();
}
else {
return null;
}
}
public void updateModifiedValues(RemoteSdkCredentials data) {
myHelpersPathField.setText(data.getHelpersPath());
}
public void updateHelpersPath(String helpersPath) {
myHelpersPathField.setText(helpersPath);
}
@Override
public boolean isSdkInConsistentState(@NotNull CredentialsType<?> connectionType) {
return myCredentialsType2Handler.get(connectionType).getRadioButton().isSelected(); // TODO: may encapsutate
}
public String getValidationError() {
return myStatusPanel.getError();
}
@Nullable
public String validateFinal() {
return myCredentialsType2Handler.get(myConnectionType).validateFinal();
}
@Override
public void dispose() {
// Disposable is the marker interface for CreateRemoteSdkForm
}
@NotNull
@Override
public final Disposable getDisposable() {
return this;
}
@NotNull
@Override
public final BundleAccessor getBundleAccessor() {
return myBundleAccessor;
}
private abstract static class TypeHandler {
@NotNull private final JBRadioButton myRadioButton;
@NotNull private final JPanel myPanel;
private @Nullable String myInterpreterPath;
TypeHandler(@NotNull JBRadioButton radioButton,
@NotNull JPanel panel,
@Nullable String defaultInterpreterPath) {
myRadioButton = radioButton;
myPanel = panel;
myInterpreterPath = defaultInterpreterPath;
}
@NotNull
public JPanel getContentComponent() {
return myPanel;
}
@NotNull
public JBRadioButton getRadioButton() {
return myRadioButton;
}
public void setInterpreterPath(@Nullable String interpreterPath) {
myInterpreterPath = interpreterPath;
}
@Nullable
public String getInterpreterPath() {
return myInterpreterPath;
}
public abstract void onInit();
public abstract void onSelected();
public boolean isBrowsingAvailable() {
return true;
}
@Nullable
public abstract ValidationInfo validate();
@Nullable
public abstract String validateFinal();
}
private class TypeHandlerEx extends TypeHandler {
@NotNull private final CredentialsTypeEx myType;
@NotNull private final CredentialsEditor<?> myEditor;
TypeHandlerEx(@NotNull JBRadioButton radioButton,
@NotNull JPanel panel,
@Nullable String defaultInterpreterPath,
@NotNull CredentialsTypeEx type,
@NotNull CredentialsEditor editor) {
super(radioButton, panel, defaultInterpreterPath);
myType = type;
myEditor = editor;
}
@NotNull
public CredentialsEditor getEditor() {
return myEditor;
}
@Override
public void onInit() {
}
@Override
public void onSelected() {
myConnectionType = myType;
myEditor.onSelected();
}
@Nullable
@Override
public ValidationInfo validate() {
return myEditor.validate();
}
@Nullable
@Override
public String validateFinal() {
return myEditor.validateFinal(() -> createSdkDataInner(), helpersPath -> updateHelpersPath(helpersPath));
}
@NotNull
public CredentialsType getType() {
return myType;
}
@Override
public boolean isBrowsingAvailable() {
return myType.isBrowsingAvailable();
}
}
private abstract class CaseCollector {
public CredentialsCase[] collectCases(CredentialsCase... cases) {
List<CredentialsCase> exCases = new ArrayList<>();
for (TypeHandler typeHandler : myCredentialsType2Handler.values()) {
final TypeHandlerEx handlerEx = ObjectUtils.tryCast(typeHandler, TypeHandlerEx.class);
if (handlerEx != null) {
exCases.add(new CredentialsCase() {
@Override
public CredentialsType getType() {
return handlerEx.getType();
}
@Override
public void process(Object credentials) {
processEx(handlerEx.getEditor(), credentials);
}
});
}
}
return ArrayUtil.mergeArrays(cases, exCases.toArray(new CredentialsCase[0]));
}
protected abstract void processEx(CredentialsEditor editor, Object credentials);
}
@Nullable
public Project getProject() {
return myProject;
}
@NotNull
@Override
public final RemoteSdkEditorContainer getParentContainer() {
return myParentContainer;
}
@NotNull
@Override
public StatusPanel getStatusPanel() {
return myStatusPanel;
}
@Nullable
@Override
public Runnable getValidator() {
return myValidator;
}
/**
* Returns whether running SSH interpreter as root via sudo is
* supported or not.
*/
public boolean isSshSudoSupported() {
return false;
}
/**
* Returns whether editing of SDK with specified {@link CredentialsType} is
* supported or not.
* <p>
* Certain remote interpreters (e.g. PHP, Python, Ruby, etc.) may or may not
* support SDK with certain credentials type (e.g. Docker, Docker Compose,
* WSL, etc.).
*
* @param type credentials type to check
* @return whether editing of SDK is supported or not
*/
public boolean isConnectionTypeSupported(@NotNull CredentialsType type) {
return myCredentialsType2Handler.containsKey(type) && !myUnsupportedConnectionTypes.contains(type);
}
/**
* {@link ResizingCardLayout#preferredLayoutSize(Container)} and {@link ResizingCardLayout#minimumLayoutSize(Container)} methods are the
* same as in {@link CardLayout} but they take into account only visible components.
*/
private static final class ResizingCardLayout extends CardLayout {
@Override
public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int w = 0;
int h = 0;
for (int i = 0; i < ncomponents; i++) {
Component comp = parent.getComponent(i);
if (comp.isVisible()) {
Dimension d = comp.getPreferredSize();
if (d.width > w) {
w = d.width;
}
if (d.height > h) {
h = d.height;
}
}
}
return new Dimension(insets.left + insets.right + w + getHgap() * 2,
insets.top + insets.bottom + h + getVgap() * 2);
}
}
@Override
public Dimension minimumLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int w = 0;
int h = 0;
for (int i = 0; i < ncomponents; i++) {
Component comp = parent.getComponent(i);
if (comp.isVisible()) {
Dimension d = comp.getMinimumSize();
if (d.width > w) {
w = d.width;
}
if (d.height > h) {
h = d.height;
}
}
}
return new Dimension(insets.left + insets.right + w + getHgap() * 2,
insets.top + insets.bottom + h + getVgap() * 2);
}
}
}
@TestOnly
public void selectType(CredentialsType credentialsType) {
for (Map.Entry<CredentialsType, TypeHandler> type2handler : myCredentialsType2Handler.entrySet()) {
if (type2handler.getKey() == credentialsType) {
type2handler.getValue().getRadioButton().setSelected(true);
break;
}
}
radioSelected(true);
}
private void trackEditorLabelsColumn(@NotNull CredentialsEditor<?> editor) {
if (editor instanceof FormWithAlignableLabelsColumn) {
for (JBLabel label : ((FormWithAlignableLabelsColumn)editor).getLabelsColumn()) {
label.addAncestorListener(myLabelsColumnTracker);
label.addComponentListener(myLabelsColumnTracker);
}
}
}
@NotNull
private final CredentialsEditorLabelsColumnTracker myLabelsColumnTracker = new CredentialsEditorLabelsColumnTracker();
private class CredentialsEditorLabelsColumnTracker implements ComponentListener, AncestorListener {
@NotNull
private final Set<JBLabel> myVisibleLabelsColumn = new HashSet<>();
@Nullable
private JBLabel myAnchoredLabel;
@Override
public void componentResized(ComponentEvent e) { /* do nothing */ }
@Override
public void componentMoved(ComponentEvent e) { /* do nothing */ }
@Override
public void componentShown(ComponentEvent e) { onEvent(e.getComponent()); }
@Override
public void componentHidden(ComponentEvent e) { onEvent(e.getComponent()); }
@Override
public void ancestorAdded(AncestorEvent event) { onEvent(event.getComponent()); }
@Override
public void ancestorRemoved(AncestorEvent event) { onEvent(event.getComponent()); }
@Override
public void ancestorMoved(AncestorEvent event) { onEvent(event.getComponent()); }
private void onEvent(@Nullable Component component) {
if (component == null) return;
if (component instanceof JBLabel) {
if (component.isShowing()) {
onLabelShowing((JBLabel)component);
}
else {
onLabelHidden((JBLabel)component);
}
}
}
private void onLabelShowing(@NotNull JBLabel component) {
if (myVisibleLabelsColumn.add(component)) {
alignForm();
}
}
protected void onLabelHidden(@NotNull JBLabel component) {
if (myVisibleLabelsColumn.remove(component)) {
alignForm();
}
}
private void alignForm() {
myInterpreterPathLabel.setAnchor(null);
if (myAnchoredLabel != null) {
myAnchoredLabel.setAnchor(null);
myAnchoredLabel = null;
}
if (!myVisibleLabelsColumn.isEmpty()) {
JBLabel labelWithMaxWidth = Collections.max(myVisibleLabelsColumn, Comparator.comparingInt(o -> o.getPreferredSize().width));
if (myInterpreterPathLabel.getPreferredSize().width < labelWithMaxWidth.getPreferredSize().getWidth()) {
myInterpreterPathLabel.setAnchor(labelWithMaxWidth);
}
else {
for (JBLabel label : myVisibleLabelsColumn) {
label.setAnchor(myInterpreterPathLabel);
label.revalidate();
}
myAnchoredLabel = labelWithMaxWidth;
}
}
}
}
}
|
/**
* Face of s-lib
*
* @author ed
*
*/
package com.shuimin.common;
import com.shuimin.common.f.*;
import com.shuimin.common.struc.Cache;
import com.shuimin.common.struc.IterableEnumeration;
import com.shuimin.common.struc.Matrix;
import com.shuimin.common.util.cui.Rect;
import com.shuimin.common.util.logger.Logger;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import sun.misc.Unsafe;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
public class S {
private final static Logger logger = Logger.getDefault();
private final static Unsafe unsafe = ((Function.F0<Unsafe>) () -> {
try {
Field uf = Unsafe.class.getDeclaredField("theUnsafe");
uf.setAccessible(true);
return (Unsafe) uf.get(null);
} catch (IllegalAccessException | NoSuchFieldException a) {
a.printStackTrace();
}
return null;
}).apply();
public static Logger logger() {
return logger;
}
public static String author() {
return " edwinyxc@gmail.com ";
}
public static String version() {
return "v0.0.1 2014";
}
/**
* @param <T> Type val
* @param t value of type T
*/
public static <T> Some<T> _some(T t) {
return Option.some(t);
}
public static <T> None<T> _none() {
return Option.none();
}
public static void _assert(boolean b) {
_assert(b, "assert failure, something`s wrong");
}
public static void _assert(boolean a, String err) {
if (a) {
return;
}
throw new RuntimeException(err);
}
public static boolean _in(Object some, Object... conditions){
_assert(some);
for(Object o : conditions) {
if(some.equals(o))return true;
}
return false;
}
public static void _lazyThrow(Throwable a) {
throw new RuntimeException(a);
}
public static void _throw(Throwable th) {
unsafe.throwException(th);
}
public static <T> T _fail() {
throw new RuntimeException("BUG OCCUR, CONTACT ME:" + author());
}
public static <T> T _fail(String err) {
throw new RuntimeException(err);
}
public static <T> T _avoidNull(T t, Class<T> clazz) {
if (t == null) return nothing.of(clazz);
return t;
}
public static <T> T _notNull(T t) {
_assert(t, "noNull assert failure");
return t;
}
public static <T> T _notNull(T t, String err) {
_assert(t, err);
return t;
}
public static <T> T _notNullElse(T _check, T _else) {
return _check != null ? _check : _else;
}
public static <E> ForIt<E> _for(Iterable<E> c) {
return new ForIt<>(c);
}
public static <E> ForIt<E> _for(E[] c) {
return new ForIt<>(c);
}
public static <E> ForIt<E> _for(Enumeration<E> enumeration) {
return new ForIt<>(new IterableEnumeration<>(enumeration));
}
public static <K, V> ForMap<K, V> _for(Map<K, V> c) {
return new ForMap<>(c);
}
@SuppressWarnings("unchecked")
public static <T> T _one(Class<?> clazz) throws InstantiationException,
IllegalAccessException {
return (T) clazz.newInstance();
}
/**
* Assert an Object is NonNull, if not throw an RuntimeException.
*
* @param a potential null value
*/
public static void _assert(Object a) {
if (a == null) {
throw new RuntimeException(new NullPointerException());
}
}
/**
* Assert an object is non-null, if not throw an RuntimeException
* with input err string.
*
* @param a potential null value
* @param err err value
*/
public static void _assert(Object a, String err) {
if (a == null) {
throw new RuntimeException(err);
}
}
public static void _assertNotNull(Object... x) {
for (Object o : x) {
if (o == null) throw new NullPointerException();
}
}
/**
* <p>Print somethings to the default logger</p>
*
* @param o object(s) to print
*/
public static void echo(Object o) {
logger.echo(dump(o));
}
@SuppressWarnings("unchecked")
public static String dump(Object o) {
if (o == null) return "null";
Class clazz = o.getClass();
if (clazz.isPrimitive()) {
return String.valueOf(o);
} else if (o instanceof String) {
return (String) o;
} else if (o instanceof Iterable) {
return "["
+ String.join(",",
_notNullElse(_for((Iterable) o).
map((i) -> (dump(i))).val(),
list.one()))
+ "]";
} else if (clazz.isArray()) {
Object[] oArr = new Object[Array.getLength(o)];
for (int i = 0; i < oArr.length; i++) {
oArr[i] = Array.get(o, i);
}
return "["
+ String.join(",", _for(oArr).
<String>map((i) -> (dump(i))).val())
+ "]";
} else if (o instanceof Map) {
return _for((Map) o).map((i) -> (dump(i))).val().toString();
} else {
return o.toString();
}
}
@SafeVarargs
public static <E> list.FList<E> list(E... e) {
return list.one(e);
}
/**
* @return system current time as millseconds
*/
public static long time() {
return System.currentTimeMillis();
}
public static class array {
public static <T> Iterable<T> to(T[] arr) {
return list.one(arr);
}
public static <T> T last(T[] array) {
return array[array.length - 1];
}
public static <T> T first(T[] array) {
return array[0];
}
public static <T> T[] of(Iterable<T> iter) {
List<T> tmp = new LinkedList<>();
for (T e : iter) {
tmp.add(e);
}
return of(tmp.toArray());
}
public static <T> T[] of(Enumeration<T> enumeration) {
List<T> tmp = new LinkedList<>();
while (enumeration.hasMoreElements()) {
tmp.add(enumeration.nextElement());
}
return of(tmp.toArray());
}
@SuppressWarnings("unchecked")
public static <T> T[] of(Object[] arr) {
if (arr.length == 0) {
return (T[]) arr;
}
Class<?> tClass = arr[0].getClass();
Object array = Array.newInstance(tClass, arr.length);
for (int i = 0; i < arr.length; i++) {
Array.set(array, i, arr[i]);
}
return (T[]) array;
}
/**
* check if an array contains something
*
* @param arr array
* @param o the thing ...
* @return -1 if not found or the first index of the object
*/
public static int contains(Object[] arr, Object o) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null && arr[i].equals(o)) {
return i;
}
}
return -1;
}
/**
* check if an array contains something
*
* @param arr array
* @param o the thing ...
* @return -1 if not found or the first index of the object
*/
public static int contains(int[] arr, int o) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == o) {
return i;
}
}
return -1;
}
/**
* put elements to the left.delete the null ones
*
* @param arr input Object array
* @return compacted array
*/
public static Object[] compact(Object[] arr) {
int cur = 0;
int next_val = 0;
while (next_val < arr.length) {
if (arr[cur] == null) {
/* find next available */
for (; next_val < arr.length; next_val++) {
if (arr[next_val] != null) {
break;// get the value
}
}
if (next_val >= arr.length) {
break;
}
/* move it to the cur */
arr[cur] = arr[next_val];
arr[next_val] = null;
cur++;
} else {
next_val++;
cur++;
}
}
Object[] ret;
if (arr[0] != null) {
Class<?> c = arr[0].getClass();
ret = (Object[]) Array.newInstance(c, cur);
} else {
ret = new Object[cur];
}
System.arraycopy(arr, 0, ret, 0, ret.length);
return ret;
}
/**
* Convert a list to an array.
*
* @param clazz Class of input list
* @param list input list
* @return array
*/
public static Object fromList(Class<?> clazz, List<?> list) {
Object array = Array.
newInstance(clazz, list.size());
for (int i = 0; i < list.size(); i++) {
Array.set(array, i, list.get(i));
}
return array;
}
/**
* Convert an array to a new one in which every element has type converted.
*
* @param clazz Class to convert to
* @param arr input array
* @return converted array
*/
public static Object convertType(Class<?> clazz, Object[] arr) {
Object array = Array.
newInstance(clazz, arr.length);
for (int i = 0; i < arr.length; i++) {
Array.set(array, i, arr[i]);
}
return array;
}
}
public static class collection {
public static class set {
public static <E> HashSet<E> hashSet(Iterable<E> arr) {
HashSet<E> ret = new HashSet<>();
for (E e : arr) {
ret.add(e);
}
return ret;
}
public static <E> HashSet<E> hashSet(E[] arr) {
final HashSet<E> ret = new HashSet<>();
ret.addAll(Arrays.asList(arr));
return ret;
}
}
public static class list {
public static <E> ArrayList<E> arrayList(Iterable<E> arr) {
final ArrayList<E> ret = new ArrayList<>();
for (E t : arr) {
ret.add(t);
}
return ret;
}
public static <E> ArrayList<E> arrayList(E[] arr) {
final ArrayList<E> ret = new ArrayList<>();
/*
for (E val : arr) {
ret.add(val);
}
*/
ret.addAll(Arrays.asList(arr));
return ret;
}
public static <E> LinkedList<E> linkedList(Iterable<E> arr) {
final LinkedList<E> ret = new LinkedList<>();
for (E t : arr) ret.add(t);
return ret;
}
public static <E> LinkedList<E> linkedList(E[] arr) {
final LinkedList<E> ret = new LinkedList<>();
ret.addAll(Arrays.asList(arr));
return ret;
}
}
}
public static class date {
public static Date fromString(String aDate, String aFormat) throws ParseException {
return new SimpleDateFormat(aFormat).parse(aDate);
}
public static Date fromLong(String aDate) {
return new Date(parse.toLong(aDate));
}
public static String fromLong(String aDate, String aFormat) {
return toString(new Date(parse.toLong(aDate)), aFormat);
}
public static String toString(Date aDate, String aFormat) {
return new SimpleDateFormat(aFormat).format(aDate);
}
public static Long stringToLong(String aDate, String aFormat) throws ParseException {
return fromString(aDate, aFormat).getTime();
}
}
public final static class ForMap<K, V> {
private final Map<K, V> map;
protected ForMap(Map<K, V> map) {
this.map = map;
}
public ForMap<K, V> grep(Function<Boolean, Entry<K, V>> grepFunc) {
Map<K, V> newMap = S.map.hashMap(null);
for (Entry<K, V> entry : map.entrySet()) {
if (grepFunc.apply(entry)) {
newMap.put(entry.getKey(), entry.getValue());
}
}
return new ForMap<>(newMap);
}
public ForMap<K, V> grepByKey(Function<Boolean, K> grepFunc) {
Map<K, V> newMap = S.map.hashMap(null);
for (Entry<K, V> entry : map.entrySet()) {
if (grepFunc.apply(entry.getKey())) {
newMap.put(entry.getKey(), entry.getValue());
}
}
return new ForMap<>(newMap);
}
public ForMap<K, V> grepByValue(Function<Boolean, V> grepFunc) {
Map<K, V> newMap = S.map.hashMap(null);
for (Entry<K, V> entry : map.entrySet()) {
if (grepFunc.apply(entry.getValue())) {
newMap.put(entry.getKey(), entry.getValue());
}
}
return new ForMap<>(newMap);
}
public Entry<K, V> reduce(Function.F2<Entry<K, V>, Entry<K, V>, Entry<K, V>> reduceLeft) {
return list.one(map.entrySet()).reduceLeft(reduceLeft);
}
public <R> ForMap<K, R> map(Function<R, V> mapFunc) {
Map<K, R> newMap = S.map.hashMap(null);
for (Entry<K, V> entry : map.entrySet()) {
newMap.put(entry.getKey(), mapFunc.apply(entry.getValue()));
}
return new ForMap<>(newMap);
}
public ForMap<K, V> each(Callback<Entry<K, V>> eachFunc) {
map.entrySet().forEach(eachFunc::apply);
return this;
}
public Map<K, V> val() {
return map;
}
}
public final static class ForIt<E> {
private final Iterable<E> iter;
public ForIt(Iterable<E> e) {
iter = e;
}
public ForIt(E[] e) {
iter = list.one(e);
}
private <R> Collection<R> _initCollection(Class<?> itClass) {
if (Collection.class.isAssignableFrom(itClass)
&& !itClass.getSimpleName().startsWith("Unmodifiable")
&& !itClass.getSimpleName().startsWith("Empty")) {
try {
return S._one(itClass);
} catch (InstantiationException | IllegalAccessException e) {
return list.one();
}
} else {
return list.one();
}
}
public <R> ForIt<R> map(final Function<R, E> mapper) {
final Class<?> itClass = iter.getClass();
final Collection<R> result = _initCollection(itClass);
each((e) -> {
result.add(mapper.apply(e));
});
return new ForIt<>(result);
}
public ForIt<E> each(Callback<E> eachFunc) {
iter.forEach(eachFunc::apply);
return this;
}
public ForIt<E> grep(final Function<Boolean, E> grepFunc) {
final Class<?> itClass = iter.getClass();
final Collection<E> c = _initCollection(itClass);
each((e) -> {
if (grepFunc.apply(e)) {
c.add(e);
}
});
return new ForIt<>(c);
}
public E reduce(final Function.F2<E, E, E> reduceLeft) {
return list.one(iter).reduceLeft(reduceLeft);
}
public Iterable<E> val() {
return iter;
}
public ForIt<E> compact() {
return grep((e) -> (e != null));
}
public E first() {
Iterator<E> it = iter.iterator();
if (it.hasNext()) {
return it.next();
}
return null;
}
public E[] join() {
return array.of(iter);
}
public List<E> toList() {
return list.one(this.val());
}
public Set<E> toSet() {
return collection.set.hashSet(this.val());
}
}
public static class file {
public static String fileNameFromPath(String path) {
return path.substring(path.lastIndexOf("\\") + 1);
}
/**
* Returns file extension name,
* return null if it has no extension.
* @param fileName
* @return
*/
public static String fileExt(String fileName) {
String[] filename = splitFileName(fileName);
return filename[filename.length - 1];
}
public static String[] splitFileName(String filename) {
int idx_dot = filename.lastIndexOf('.');
if (idx_dot <= 0 || idx_dot == filename.length()) {
return new String[]{filename, null};
}
return new String[]{filename.substring(0, idx_dot), filename.substring(idx_dot + 1)};
}
/**
* abc.txt => [abc, txt] abc.def.txt => [abc.def, txt] abc. =>
* [abc.,null] .abc => [.abc,null] abc => [abc,null]
*
* @param file file
* @return string array with size of 2, first is the filename, remain the suffix;
*/
public static String[] splitFileName(File file) {
return splitFileName(file.getName());
}
public static File mkdir(File par, String name) throws IOException {
final String path = par.getAbsolutePath() + File.separatorChar + name;
File f = new File(path);
if (f.mkdirs() && f.createNewFile()) {
return f;
}
return null;
}
public static File touch(File par, String name) throws IOException {
final String path = par.getAbsolutePath() + File.separatorChar + name;
File f = new File(path);
if (f.createNewFile()) {
return f;
}
return null;
}
/**
* Delete a dir recursively deleting anything inside it.
*
* @param file The dir to delete
* @return true if the dir was successfully deleted
*/
public static boolean rm(File file) {
if (!file.exists() || !file.isDirectory()) {
return false;
}
String[] files = file.list();
for (String file1 : files) {
File f = new File(file, file1);
if (f.isDirectory()) {
rm(f);
} else {
f.delete();
}
}
return file.delete();
}
}
final static public class list {
public static <E> FList<E> one() {
return new FList<>();
}
public static <E> FList<E> one(Iterable<E> iterable) {
return new FList<>(iterable);
}
public static <E> FList<E> one(E... arr) {
return new FList<>(arr);
}
@SuppressWarnings("serial")
final static public class FList<T> extends ArrayList<T> {
public FList() {
super();
}
public FList(T[] a) {
super();
this.addAll(Arrays.asList(a));
}
public FList(List<T> a) {
super(a);
}
public FList(Iterable<T> iter) {
super();
iter.forEach(this::add);
}
public FList(int i) {
super(i);
}
public FList<T> slice(int start, int end) {
final FList<T> ret = new FList<>();
for (int i = start; i < end; i++) {
ret.add(this.get(i));
}
return ret;
}
public FList<T> slice(int start) {
final FList<T> ret = new FList<>();
for (int i = start; i < size(); i++) {
ret.add(this.get(i));
}
return ret;
}
public T reduceLeft(Function.F2<T, T, T> reduceFunc) {
if (this.size() == 1) {
return this.get(0);
}
T result = this.get(0);
for (int i = 1; i < this.size(); i++) {
result = reduceFunc.apply(result, this.get(i));
}
return result;
}
public String join(String sep) {
final StringBuilder sb = new StringBuilder();
for (T t : this) {
sb.append(t.toString()).append(sep);
}
return sb.toString();
}
}
}
public static class math {
public static int max(int a, int b) {
return a > b ? a : b;
}
}
public static class map {
@SuppressWarnings("unchecked")
public static <K, V> HashMap<K, V> hashMap(Object[][] kv) {
if (kv == null) {
return new HashMap();
}
HashMap<K, V> ret = new HashMap();
for (Object[] entry : kv) {
if (entry.length >= 2) {
ret.put((K) entry[0], (V) entry[1]);
}
}
return ret;
}
}
public static class matrix {
public static Matrix console(int maxLength) {
return new Matrix(0, maxLength);
}
/**
* <p>
* Print a matrix whose each row as a String.
* </p>
*
* @return a string represent the input
* matrix using '\n' to separate between lines
*/
public static String mkStr(Rect r) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < r.height; i++) {
for (int j = 0; j < r.width; j++) {
char c = (char) r.data.get(i, j);
sb.append(c);
}
sb.append("\n");
}
return sb.toString();
}
public static Matrix addHorizontal(Matrix... some) {
int height = 0;
int width = 0;
for (Matrix x : some) {
height = math.max(height, x.rows());
width += x.cols();
}
int[][] out = new int[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
out[i][j] = ' ';
}
}
int colfix = 0;
for (Matrix x : some) {
for (int h = 0; h < x.rows(); h++) {
int[] row = x.row(h);
for (int _i = 0; _i < row.length; _i++) {
out[h][colfix + _i] = (char) row[_i];
}
}
colfix += x.cols();
}
return new Matrix(out);
}
public static Matrix fromString(String... s) {
S.echo(s);
final int maxLen = list.one(array.<String>of(array.compact(s))).reduceLeft(
(String a, String b) -> {
if (a == null || b == null) {
return "";
}
return a.length() > b.length() ? a : b;
}
).length();
int[][] ret = new int[s.length][maxLen];
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length(); j++) {
ret[i][j] = s[i].charAt(j);
}
}
return new Matrix(ret);
}
}
final public static class nothing {
public final static Boolean _boolean = Boolean.FALSE;
public final static Character _char = (char) '\0';
public final static Byte _byte = (byte) 0;
public final static Integer _int = 0;
public final static Short _short = (short) 0;
public final static Long _long = (long) 0;
public final static Float _float = (float) 0;
public final static Double _double = (double) 0;
final static Cache<Class<?>, Object> _nothingValues = Cache.<Class<?>, Object>defaultCache().onNotFound(
a -> Enhancer.create(_notNull(a), (MethodInterceptor) (Object obj, Method method, Object[] args, MethodProxy proxy) -> null));
static {
_nothingValues.put(String.class, "")
.put(Boolean.class, _boolean).put(Integer.class, _int)
.put(Byte.class, _byte).put(Character.class, _char).put(Short.class, _short).put(Long.class, _long)
.put(Float.class, _float).put(Double.class, _double).put(Object.class, new Object());
}
final private Class<?> proxyClass;
protected nothing(Class<?> clazz) {
proxyClass = clazz;
}
@SuppressWarnings("unchecked")
public static <T> T of(Class<T> t) {
return (T) new nothing(t).proxy();
}
protected Object proxy() {
return _nothingValues.get(proxyClass);
}
}
/**
* @param <T>
*/
@SuppressWarnings("unchecked")
final public static class proxy<T> {
final Map<String, Function<Object, Object[]>> _mm = new HashMap<>(5);
final private Class<T> _clazz;
final private T _t;
private proxy(Class<T> clazz, T t) {
_clazz = clazz;
_t = t;
}
public static <T> proxy<T> one(Class<T> clazz) throws InstantiationException, IllegalAccessException {
return new proxy(clazz, S.<T>_one(clazz));
}
public static <T> proxy<T> of(T t) {
return new proxy(t.getClass(), t);
}
public T origin() {
return _t;
}
public Class<T> originClass() {
return _clazz;
}
public proxy<T> method(String methodName, Function<Object, Object[]> method) {
_mm.put(methodName, method);
return this;
}
public T create() {
return (T) Enhancer.create(_clazz,
(MethodInterceptor) (obj, method, args, proxy) ->
_avoidNull(_mm.get(method.getName()), Function.class).apply(args)
);
}
}
public static class path {
@SuppressWarnings("ConstantConditions")
public static String rootAbsPath(Object caller) {
return caller.getClass().getClassLoader().getResource("/").getPath();
}
@SuppressWarnings("ConstantConditions")
public static String rootAbsPath(Class<?> callerClass) {
return callerClass.getClassLoader().getResource("/").getPath();
}
@SuppressWarnings("rawtypes")
public static String get(Class clazz) {
String path = clazz.getResource("").getPath();
return new File(path).getAbsolutePath();
}
public static String get(Object object) {
String path = object.getClass().getResource("").getPath();
return new File(path).getAbsolutePath();
}
@SuppressWarnings("ConstantConditions")
public static String rootClassPath() {
try {
String path = S.class.getClassLoader().getResource("").toURI().getPath();
return new File(path).getAbsolutePath();
} catch (URISyntaxException e) {
String path = S.class.getClassLoader().getResource("").getPath();
return new File(path).getAbsolutePath();
}
}
public static String packageOf(Object object) {
Package p = object.getClass().getPackage();
return p != null ? p.getName().replaceAll("\\.", "/") : "";
}
/**
* Normally return the source dir path under the current project
* @return the source dir path under the current project
*
*/
public static String detectWebRootPath() {
try {
String path = S.class.getResource("/").toURI().getPath();
return new File(path).getParentFile().getParentFile().getCanonicalPath();
} catch (URISyntaxException | IOException e) {
throw new RuntimeException(e);
}
}
public static Boolean isAbsolute(String path) {
_assert(path);
return path.startsWith("/") ||
path.indexOf(":") == 1;
}
}
// public static class reflect {
// public static boolean isPrimitive(Object o){
// Class c = o.getClass();
// //TODO?
// return c.isPrimitive();
public static class parse {
/**
* <p>
* WARNING!!! ONLY POSITIVE VALUES WILL BE RETURN
* </p>
*
* @param value input value
* @return above zero
*/
public static int toUnsigned(String value) {
int ret = 0;
if (value == null || value.isEmpty()) {
return 0;
}
char tmp;
for (int i = 0; i < value.length(); i++) {
tmp = value.charAt(i);
if (!Character.isDigit(tmp)) {
return 0;
}
ret = ret * 10 + ((int) tmp - (int) '0');
}
return ret;
}
public static long toLong(String value) throws NumberFormatException {
return Long.parseLong(value);
}
}
/**
* @author ed
*/
public static class stream {
private static final int BUFFER_SIZE = 8192;
/**
* write from is to os;
*
* @param in inputStream
* @param out outputStream
* @throws java.io.IOException
*/
public static void write(final InputStream in, final OutputStream out) throws IOException {
final byte[] buffer = new byte[BUFFER_SIZE];
int cnt;
while ((cnt = in.read(buffer)) != -1) {
out.write(buffer, 0, cnt);
}
}
}
public static class str {
public static final String EMPTY = "";
public static final String[] EMPTY_STR_ARRAY = new String[]{};
public static final String NEWLINE;
static {
String newLine;
try {
newLine = new Formatter().format("%n").toString();
} catch (Exception e) {
newLine = "\n";
}
NEWLINE = newLine;
}
public static boolean isBlank(String str) {
return str == null || "".equals(str.trim());
}
public static boolean notBlank(String str) {
return str != null && !"".equals(str.trim());
}
public static boolean notBlank(String... strings) {
if (strings == null) {
return false;
}
for (String str : strings) {
if (str == null || "".equals(str.trim())) {
return false;
}
}
return true;
}
public static boolean notNull(Object... paras) {
if (paras == null) {
return false;
}
for (Object obj : paras) {
if (obj == null) {
return false;
}
}
return true;
}
/**
* @param ori original string
* @param ch char
* @param idx index of occurrence of specified char
* @return real index of the input char
*/
public static int indexOf(String ori, char ch, int idx) {
char c;
int occur_idx = 0;
for (int i = 0; i < ori.length(); i++) {
c = ori.charAt(i);
if (c == ch) {
if (occur_idx == idx) {
return i;
}
occur_idx++;
}
}
return -1;
}
/**
* Generates a camel case version of a phrase from underscore.
*
* @param underscore underscore version of a word to converted to camel case.
* @return camel case version of underscore.
*/
public static String camelize(String underscore) {
return camelize(underscore, false);
}
public static String pascalize(String underscore) {
return camelize(underscore, true);
}
/**
* Generates a camel case version of a phrase from underscore.
*
* @param underscore underscore version of a word to converted to camel case.
* @param capitalizeFirstChar set to true if first character needs to be capitalized, false if not.
* @return camel case version of underscore.
*/
public static String camelize(String underscore, boolean capitalizeFirstChar) {
String result = "";
StringTokenizer st = new StringTokenizer(underscore, "_");
while (st.hasMoreTokens()) {
result += capitalize(st.nextToken());
}
return capitalizeFirstChar ? result : result.substring(0, 1).toLowerCase() + result.substring(1);
}
/**
* Capitalizes a word - only a first character is converted to upper case.
*
* @param word word/phrase to capitalize.
* @return same as input argument, but the first character is capitalized.
*/
public static String capitalize(String word) {
return word.substring(0, 1).toUpperCase() + word.substring(1);
}
/**
* Converts a CamelCase string to underscores: "AliceInWonderLand" becomes:
* "alice_in_wonderland"
*
* @param camel camel case input
* @return result converted to underscores.
*/
public static String underscore(String camel) {
List<Integer> upper = new ArrayList<Integer>();
byte[] bytes = camel.getBytes();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
if (b < 97 || b > 122) {
upper.add(i);
}
}
StringBuffer b = new StringBuffer(camel);
for (int i = upper.size() - 1; i >= 0; i
Integer index = upper.get(i);
if (index != 0)
b.insert(index, "_");
}
return b.toString().toLowerCase();
}
}
public static class uuid {
public static String str() {
return UUID.randomUUID().toString();
}
public static UUID base() {
return UUID.randomUUID();
}
public static String vid() {
UUID uuid = UUID.randomUUID();
return uuid.toString().replaceAll("-", "");
}
}
}
|
package hu.vmiklos.plees_tracker;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class MainActivity extends AppCompatActivity
{
@Override protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateView();
}
@Override protected void onStart()
{
super.onStart();
Log.d("plees", "onStart");
Intent intent = new Intent(this, MainService.class);
stopService(intent);
}
@Override protected void onStop()
{
super.onStop();
Log.d("plees", "onStop");
Intent intent = new Intent(this, MainService.class);
DataModel dataModel = DataModel.getDataModel();
if (dataModel.getStart() != null && dataModel.getStop() == null)
{
startService(intent);
}
}
public void startStop(View v)
{
DataModel dataModel = DataModel.getDataModel();
if (dataModel.getStart() != null && dataModel.getStop() == null)
{
dataModel.setStop(Calendar.getInstance().getTime());
}
else
{
dataModel.setStart(Calendar.getInstance().getTime());
dataModel.setStop(null);
}
updateView();
}
private void updateView()
{
DataModel dataModel = DataModel.getDataModel();
TextView state = (TextView)findViewById(R.id.state);
Button startStop = (Button)findViewById(R.id.startStop);
SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
if (dataModel.getStart() != null && dataModel.getStop() != null)
{
long durationMS =
dataModel.getStop().getTime() - dataModel.getStart().getTime();
String duration = formatDuration(durationMS / 1000);
state.setText("Started on " + sdf.format(dataModel.getStart()) +
", stopped on " + sdf.format(dataModel.getStop()) +
", slept for " + duration + ".");
startStop.setText("Start again");
}
else if (dataModel.getStart() != null)
{
state.setText("Started on " + sdf.format(dataModel.getStart()) +
", tracking.");
startStop.setText("Stop");
}
else
{
state.setText("Press start to begin tracking.");
startStop.setText("Start");
}
}
private static String formatDuration(long seconds)
{
return String.format("%d:%02d:%02d", seconds / 3600,
(seconds % 3600) / 60, seconds % 60);
}
}
|
package theforthlesson;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.LinkedList;
import java.util.List;
public class TheNinthTest extends BaseTest {
@Test
public void theNinthTest1() {
driver.get("http://localhost/litecart/admin/?app=countries&doc=countries");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin");
driver.findElement(By.name("login")).click();
List<WebElement> rows = driver.findElements(By.cssSelector(".dataTable .row"));
List<String> listOfCountries = new LinkedList<>();
for (int i = 1; i <= rows.size(); i++) {
WebElement row = driver.findElement(By.xpath("(//table[@class='dataTable']//tr[@class='row'])[" + i + "]"));
WebElement country = row.findElement(By.xpath("(.//td)[5]"));
Integer numberOfTimeZones = Integer.valueOf(row.findElement(By.xpath("(.//td)[6]")).getText());
listOfCountries.add(country.getText());
if (numberOfTimeZones > 0) {
List<String> listOfZones = new LinkedList<>();
country.findElement(By.cssSelector("a")).click();
List<WebElement> zones = driver.findElements(By.xpath("//table[@id='table-zones']//tr[td[1][.//input[@type='hidden']]]"));
for (WebElement zone : zones) {
zone.findElement(By.xpath(".//td[3]")).getAttribute("value");
}
Assert.assertTrue(isListSorted(listOfZones));
driver.navigate().back();
}
}
Assert.assertTrue(isListSorted(listOfCountries));
}
@Test
public void theNinthTest2(){
driver.get("http://localhost/litecart/admin/?app=geo_zones&doc=geo_zones");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin");
driver.findElement(By.name("login")).click();
List<WebElement> countries=driver.findElements(By.cssSelector(".dataTable td:nth-child(3) a"));
for (int i=1;i<=countries.size();i++){
List<String> selectedZones=new LinkedList<>();
driver.findElement(By.xpath("(//table[@class='dataTable']//td[3]/a)["+i+"]")).click();
List<WebElement> selectors=driver.findElements(By.xpath("//table[@id='table-zones']//select[contains(@name,'zone_code')]"));
for (WebElement selector: selectors) {
selectedZones.add(selector.findElement(By.xpath(".//option[@selected]")).getText());
}
Assert.assertTrue(isListSorted(selectedZones));
driver.navigate().back();
}
}
}
|
package org.jetbrains.idea.devkit.inspections;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.util.SpecialAnnotationsUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.siyeh.ig.ui.ExternalizableStringSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.devkit.DevKitBundle;
import javax.swing.*;
import java.awt.*;
import java.util.List;
public class UnstableApiUsageInspection extends LocalInspectionTool {
public final List<String> unstableApiAnnotations = new ExternalizableStringSet(
"org.jetbrains.annotations.ApiStatus.Experimental",
"com.google.common.annotations.Beta",
"io.reactivex.annotations.Beta",
"io.reactivex.annotations.Experimental"
);
@Nullable
@Override
public JComponent createOptionsPanel() {
JPanel panel = new JPanel(new GridBagLayout());
//TODO in add annotation window "Include non-project items" should be enabled by default
JPanel annotationsListControl = SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
unstableApiAnnotations, DevKitBundle.message("inspections.unstable.api.usage.annotations.list"));
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weighty = 1.0;
constraints.weightx = 1.0;
constraints.anchor = GridBagConstraints.CENTER;
constraints.fill = GridBagConstraints.BOTH;
panel.add(annotationsListControl, constraints);
return panel;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
if (!isApplicable(holder.getProject())) {
return PsiElementVisitor.EMPTY_VISITOR;
}
return new PsiElementVisitor() {
@Override
public void visitElement(PsiElement element) {
super.visitElement(element);
// Java constructors must be handled a bit differently (works fine with Kotlin)
PsiMethod resolvedConstructor = null;
PsiElement elementParent = element.getParent();
if (elementParent instanceof PsiConstructorCall) {
resolvedConstructor = ((PsiConstructorCall)elementParent).resolveConstructor();
}
for (PsiReference reference : element.getReferences()) {
PsiModifierListOwner modifierListOwner = getModifierListOwner(reference, resolvedConstructor);
if (modifierListOwner == null || !isLibraryElement(modifierListOwner)) {
continue;
}
for (String annotation : unstableApiAnnotations) {
if (modifierListOwner.hasAnnotation(annotation)) {
holder.registerProblem(reference,
DevKitBundle.message("inspections.unstable.api.usage.description", getReferenceText(reference)),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
return;
}
}
}
}
};
}
private static boolean isLibraryElement(@NotNull PsiElement element) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
return true;
}
PsiFile containingPsiFile = element.getContainingFile();
if (containingPsiFile == null) {
return false;
}
VirtualFile containingVirtualFile = containingPsiFile.getVirtualFile();
if (containingVirtualFile == null) {
return false;
}
return ProjectFileIndex.getInstance(element.getProject()).isInLibrary(containingVirtualFile);
}
@NotNull
private static String getReferenceText(@NotNull PsiReference reference) {
if (reference instanceof PsiQualifiedReference) {
String referenceName = ((PsiQualifiedReference)reference).getReferenceName();
if (referenceName != null) {
return referenceName;
}
}
// references are not PsiQualifiedReference for annotation attributes
return StringUtil.getShortName(reference.getCanonicalText());
}
@Nullable
private static PsiModifierListOwner getModifierListOwner(@NotNull PsiReference reference, @Nullable PsiMethod resolvedConstructor) {
if (resolvedConstructor != null) {
return resolvedConstructor;
}
if (reference instanceof ResolvingHint) {
if (((ResolvingHint)reference).canResolveTo(PsiModifierListOwner.class)) {
return (PsiModifierListOwner)reference.resolve();
}
else {
return null;
}
}
PsiElement resolvedElement = reference.resolve();
if (resolvedElement instanceof PsiModifierListOwner) {
return (PsiModifierListOwner)resolvedElement;
}
return null;
}
private boolean isApplicable(@NotNull Project project) {
JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
GlobalSearchScope scope = GlobalSearchScope.allScope(project);
for (String annotation : unstableApiAnnotations) {
if (javaPsiFacade.findClass(annotation, scope) != null) {
return true;
}
}
return false;
}
}
|
package com.intellij.codeInspection.i18n;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.externalAnnotation.NonNlsAnnotationProvider;
import com.intellij.codeInspection.*;
import com.intellij.ide.util.TreeClassChooser;
import com.intellij.ide.util.TreeClassChooserFactory;
import com.intellij.lang.properties.PropertiesImplUtil;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.introduceField.IntroduceConstantHandler;
import com.intellij.ui.AddDeleteListPanel;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.FieldPanel;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.siyeh.HardcodedMethodConstants;
import com.siyeh.ig.psiutils.MethodUtils;
import gnu.trove.THashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.uast.*;
import org.jetbrains.uast.util.UastExpressionUtils;
import org.jetbrains.uast.visitor.AbstractUastVisitor;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.intellij.codeInsight.AnnotationUtil.CHECK_EXTERNAL;
import static com.intellij.codeInsight.AnnotationUtil.CHECK_HIERARCHY;
public class I18nInspection extends AbstractBaseUastLocalInspectionTool implements CustomSuppressableInspectionTool {
private static final HashSet<String> NON_NLS_NAMES = new HashSet<>(Arrays.asList(AnnotationUtil.NLS, AnnotationUtil.NON_NLS));
public boolean ignoreForAssertStatements = true;
public boolean ignoreForExceptionConstructors = true;
@NonNls
public String ignoreForSpecifiedExceptionConstructors = "";
public boolean ignoreForJUnitAsserts = true;
public boolean ignoreForClassReferences = true;
public boolean ignoreForPropertyKeyReferences = true;
public boolean ignoreForNonAlpha = true;
private boolean ignoreForAllButNls = false;
public boolean ignoreAssignedToConstants;
public boolean ignoreToString;
@NonNls public String nonNlsCommentPattern = "NON-NLS";
private boolean ignoreForEnumConstants;
@Nullable private Pattern myCachedNonNlsPattern;
@NonNls private static final String TO_STRING = "toString";
public I18nInspection() {
cacheNonNlsCommentPattern();
}
@Override
public SuppressIntentionAction @NotNull [] getSuppressActions(PsiElement element) {
SuppressQuickFix[] suppressActions = getBatchSuppressActions(element);
if (myCachedNonNlsPattern == null) {
return ContainerUtil.map2Array(suppressActions, SuppressIntentionAction.class, SuppressIntentionActionFromFix::convertBatchToSuppressIntentionAction);
}
else {
List<SuppressIntentionAction> suppressors = new ArrayList<>(suppressActions.length + 1);
suppressors.add(new SuppressByCommentOutAction(nonNlsCommentPattern));
suppressors.addAll(ContainerUtil.map(suppressActions, SuppressIntentionActionFromFix::convertBatchToSuppressIntentionAction));
return suppressors.toArray(SuppressIntentionAction.EMPTY_ARRAY);
}
}
private static final String SKIP_FOR_ENUM = "ignoreForEnumConstant";
private static final String IGNORE_ALL_BUT_NLS = "ignoreAllButNls";
@Override
public void writeSettings(@NotNull Element node) throws WriteExternalException {
super.writeSettings(node);
if (ignoreForEnumConstants) {
node.addContent(new Element("option")
.setAttribute("name", SKIP_FOR_ENUM)
.setAttribute("value", Boolean.toString(ignoreForEnumConstants)));
}
if (ignoreForAllButNls) {
node.addContent(new Element("option")
.setAttribute("name", IGNORE_ALL_BUT_NLS)
.setAttribute("value", Boolean.toString(ignoreForAllButNls)));
}
}
@Override
public void readSettings(@NotNull Element node) throws InvalidDataException {
super.readSettings(node);
for (Element o : node.getChildren()) {
String nameAttr = o.getAttributeValue("name");
String valueAttr = o.getAttributeValue("value");
if (Comparing.strEqual(nameAttr, SKIP_FOR_ENUM)) {
if (valueAttr != null) {
ignoreForEnumConstants = Boolean.parseBoolean(valueAttr);
}
}
else if (Comparing.strEqual(nameAttr, IGNORE_ALL_BUT_NLS)) {
if (valueAttr != null) {
ignoreForAllButNls = Boolean.parseBoolean(valueAttr);
}
}
}
cacheNonNlsCommentPattern();
}
@Override
@NotNull
public String getGroupDisplayName() {
return InspectionsBundle.message("group.names.internationalization.issues");
}
@Override
@NotNull
public String getShortName() {
return "HardCodedStringLiteral";
}
@TestOnly
public boolean setIgnoreForEnumConstants(boolean ignoreForEnumConstants) {
boolean old = this.ignoreForEnumConstants;
this.ignoreForEnumConstants = ignoreForEnumConstants;
return old;
}
@TestOnly
public boolean setIgnoreForAllButNls(boolean ignoreForAllButNls) {
boolean old = this.ignoreForAllButNls;
this.ignoreForAllButNls = ignoreForAllButNls;
return old;
}
@Override
public JComponent createOptionsPanel() {
final GridBagLayout layout = new GridBagLayout();
final JPanel panel = new JPanel(layout);
final JCheckBox assertStatementsCheckbox = new JCheckBox(CodeInsightBundle.message("inspection.i18n.option.ignore.assert"), ignoreForAssertStatements);
assertStatementsCheckbox.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreForAssertStatements = assertStatementsCheckbox.isSelected();
}
});
final JCheckBox exceptionConstructorCheck =
new JCheckBox(CodeInsightBundle.message("inspection.i18n.option.ignore.for.exception.constructor.arguments"),
ignoreForExceptionConstructors);
exceptionConstructorCheck.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreForExceptionConstructors = exceptionConstructorCheck.isSelected();
}
});
final JTextField specifiedExceptions = new JTextField(ignoreForSpecifiedExceptionConstructors);
specifiedExceptions.getDocument().addDocumentListener(new DocumentAdapter(){
@Override
protected void textChanged(@NotNull DocumentEvent e) {
ignoreForSpecifiedExceptionConstructors = specifiedExceptions.getText();
}
});
final JCheckBox junitAssertCheckbox = new JCheckBox(
CodeInsightBundle.message("inspection.i18n.option.ignore.for.junit.assert.arguments"), ignoreForJUnitAsserts);
junitAssertCheckbox.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreForJUnitAsserts = junitAssertCheckbox.isSelected();
}
});
final JCheckBox classRef = new JCheckBox(CodeInsightBundle.message("inspection.i18n.option.ignore.qualified.class.names"), ignoreForClassReferences);
classRef.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreForClassReferences = classRef.isSelected();
}
});
final JCheckBox propertyRef = new JCheckBox(CodeInsightBundle.message("inspection.i18n.option.ignore.property.keys"), ignoreForPropertyKeyReferences);
propertyRef.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreForPropertyKeyReferences = propertyRef.isSelected();
}
});
final JCheckBox nonAlpha = new JCheckBox(CodeInsightBundle.message("inspection.i18n.option.ignore.nonalphanumerics"), ignoreForNonAlpha);
nonAlpha.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreForNonAlpha = nonAlpha.isSelected();
}
});
final JCheckBox assignedToConstants = new JCheckBox(CodeInsightBundle.message("inspection.i18n.option.ignore.assigned.to.constants"), ignoreAssignedToConstants);
assignedToConstants.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreAssignedToConstants = assignedToConstants.isSelected();
}
});
final JCheckBox chkToString = new JCheckBox(CodeInsightBundle.message("inspection.i18n.option.ignore.tostring"), ignoreToString);
chkToString.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreToString = chkToString.isSelected();
}
});
final JCheckBox ignoreEnumConstants = new JCheckBox(CodeInsightBundle.message("inspection.i18n.option.ignore.enum"), ignoreForEnumConstants);
ignoreEnumConstants.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreForEnumConstants = ignoreEnumConstants.isSelected();
}
});
final JCheckBox ignoreAllButNls = new JCheckBox(CodeInsightBundle.message("inspection.i18n.option.ignore.nls"), ignoreForAllButNls);
ignoreAllButNls.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
ignoreForAllButNls = ignoreAllButNls.isSelected();
}
});
final GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.HORIZONTAL;
gc.insets.bottom = 2;
gc.gridx = GridBagConstraints.REMAINDER;
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 0;
panel.add(ignoreAllButNls, gc);
gc.gridy ++;
panel.add(assertStatementsCheckbox, gc);
gc.gridy ++;
panel.add(junitAssertCheckbox, gc);
gc.gridy ++;
panel.add(exceptionConstructorCheck, gc);
gc.gridy ++;
final Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
panel.add(new FieldPanel(specifiedExceptions,
null,
CodeInsightBundle.message("inspection.i18n.option.ignore.for.specified.exception.constructor.arguments"),
openProjects.length == 0 ? null :
new ActionListener() {
@Override
public void actionPerformed(@NotNull ActionEvent e) {
createIgnoreExceptionsConfigurationDialog(openProjects[0], specifiedExceptions).show();
}
},
null), gc);
gc.gridy ++;
panel.add(classRef, gc);
gc.gridy ++;
panel.add(propertyRef, gc);
gc.gridy++;
panel.add(assignedToConstants, gc);
gc.gridy++;
panel.add(chkToString, gc);
gc.gridy ++;
panel.add(nonAlpha, gc);
gc.gridy ++;
panel.add(ignoreEnumConstants, gc);
gc.gridy ++;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.weighty = 1;
final JTextField text = new JTextField(nonNlsCommentPattern);
final FieldPanel nonNlsCommentPatternComponent =
new FieldPanel(text, CodeInsightBundle.message("inspection.i18n.option.ignore.comment.pattern"),
CodeInsightBundle.message("inspection.i18n.option.ignore.comment.title"), null, () -> {
nonNlsCommentPattern = text.getText();
cacheNonNlsCommentPattern();
});
panel.add(nonNlsCommentPatternComponent, gc);
final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(panel);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBorder(null);
scrollPane.setPreferredSize(new Dimension(panel.getPreferredSize().width + scrollPane.getVerticalScrollBar().getPreferredSize().width,
panel.getPreferredSize().height +
scrollPane.getHorizontalScrollBar().getPreferredSize().height));
return scrollPane;
}
private DialogWrapper createIgnoreExceptionsConfigurationDialog(final Project project, final JTextField specifiedExceptions) {
return new DialogWrapper(true) {
private AddDeleteListPanel myPanel;
{
setTitle(CodeInsightBundle.message(
"inspection.i18n.option.ignore.for.specified.exception.constructor.arguments"));
init();
}
@Override
protected JComponent createCenterPanel() {
final String[] ignored = ignoreForSpecifiedExceptionConstructors.split(",");
final List<String> initialList = new ArrayList<>();
for (String e : ignored) {
if (!e.isEmpty()) initialList.add(e);
}
myPanel = new AddDeleteListPanel<String>(null, initialList) {
@Override
protected String findItemToAdd() {
final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
TreeClassChooser chooser = TreeClassChooserFactory.getInstance(project).
createInheritanceClassChooser(
CodeInsightBundle.message("inspection.i18n.option.ignore.for.specified.exception.constructor.arguments"), scope,
JavaPsiFacade.getInstance(project).findClass("java.lang.Throwable", scope), true, true, null);
chooser.showDialog();
PsiClass selectedClass = chooser.getSelected();
return selectedClass != null ? selectedClass.getQualifiedName() : null;
}
};
return myPanel;
}
@Override
protected void doOKAction() {
StringBuilder buf = new StringBuilder();
final Object[] exceptions = myPanel.getListItems();
for (Object exception : exceptions) {
buf.append(",").append(exception);
}
specifiedExceptions.setText(buf.length() > 0 ? buf.substring(1) : buf.toString());
super.doOKAction();
}
};
}
@Override
public ProblemDescriptor @Nullable [] checkMethod(@NotNull UMethod method, @NotNull InspectionManager manager, boolean isOnTheFly) {
if (isClassNonNls(method)) {
return null;
}
List<ProblemDescriptor> results = new ArrayList<>();
final UExpression body = method.getUastBody();
if (body != null) {
ProblemDescriptor[] descriptors = checkElement(body, manager, isOnTheFly);
if (descriptors != null) {
ContainerUtil.addAll(results, descriptors);
}
}
checkAnnotations(method, manager, isOnTheFly, results);
for (UParameter parameter : method.getUastParameters()) {
checkAnnotations(parameter, manager, isOnTheFly, results);
}
return results.isEmpty() ? null : results.toArray(ProblemDescriptor.EMPTY_ARRAY);
}
@Override
public ProblemDescriptor @Nullable [] checkClass(@NotNull UClass aClass, @NotNull InspectionManager manager, boolean isOnTheFly) {
if (isClassNonNls(aClass)) {
return null;
}
final UClassInitializer[] initializers = aClass.getInitializers();
List<ProblemDescriptor> result = new ArrayList<>();
for (UClassInitializer initializer : initializers) {
final ProblemDescriptor[] descriptors = checkElement(initializer.getUastBody(), manager, isOnTheFly);
if (descriptors != null) {
ContainerUtil.addAll(result, descriptors);
}
}
checkAnnotations(aClass, manager, isOnTheFly, result);
return result.isEmpty() ? null : result.toArray(ProblemDescriptor.EMPTY_ARRAY);
}
private void checkAnnotations(UDeclaration member,
@NotNull InspectionManager manager,
boolean isOnTheFly, List<? super ProblemDescriptor> result) {
for (UAnnotation annotation : member.getUAnnotations()) {
final ProblemDescriptor[] descriptors = checkElement(annotation, manager, isOnTheFly);
if (descriptors != null) {
ContainerUtil.addAll(result, descriptors);
}
}
}
@Override
public ProblemDescriptor @Nullable [] checkField(@NotNull UField field, @NotNull InspectionManager manager, boolean isOnTheFly) {
if (isClassNonNls(field)) {
return null;
}
if (AnnotationUtil.isAnnotated((PsiModifierListOwner)field.getJavaPsi(), AnnotationUtil.NON_NLS, CHECK_EXTERNAL)) {
return null;
}
List<ProblemDescriptor> result = new ArrayList<>();
final UExpression initializer = field.getUastInitializer();
if (initializer != null) {
ProblemDescriptor[] descriptors = checkElement(initializer, manager, isOnTheFly);
if (descriptors != null) {
ContainerUtil.addAll(result, descriptors);
}
} else if (field instanceof UEnumConstant) {
List<UExpression> arguments = ((UEnumConstant)field).getValueArguments();
for (UExpression argument : arguments) {
ProblemDescriptor[] descriptors = checkElement(argument, manager, isOnTheFly);
if (descriptors != null) {
ContainerUtil.addAll(result, descriptors);
}
}
}
checkAnnotations(field, manager, isOnTheFly, result);
return result.isEmpty() ? null : result.toArray(ProblemDescriptor.EMPTY_ARRAY);
}
@Nullable
@Override
public String getAlternativeID() {
return "nls";
}
private ProblemDescriptor[] checkElement(@NotNull UElement element, @NotNull InspectionManager manager, boolean isOnTheFly) {
StringI18nVisitor visitor = new StringI18nVisitor(manager, isOnTheFly);
element.accept(visitor);
List<ProblemDescriptor> problems = visitor.getProblems();
return problems.isEmpty() ? null : problems.toArray(ProblemDescriptor.EMPTY_ARRAY);
}
@NotNull
private static LocalQuickFix createIntroduceConstantFix() {
return new LocalQuickFix() {
@Override
@NotNull
public String getFamilyName() {
return IntroduceConstantHandler.getRefactoringNameText();
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
PsiElement element = descriptor.getPsiElement();
if (!(element instanceof PsiExpression)) return;
PsiExpression[] expressions = {(PsiExpression)element};
new IntroduceConstantHandler().invoke(project, expressions);
}
};
}
private class StringI18nVisitor extends AbstractUastVisitor {
private final List<ProblemDescriptor> myProblems = new ArrayList<>();
private final InspectionManager myManager;
private final boolean myOnTheFly;
private StringI18nVisitor(@NotNull InspectionManager manager, boolean onTheFly) {
myManager = manager;
myOnTheFly = onTheFly;
}
@Override
public boolean visitObjectLiteralExpression(@NotNull UObjectLiteralExpression objectLiteralExpression) {
for (UExpression argument : objectLiteralExpression.getValueArguments()) {
argument.accept(this);
}
return true;
}
@Override
public boolean visitClass(@NotNull UClass node) {
return false;
}
@Override
public boolean visitField(@NotNull UField node) {
return false;
}
@Override
public boolean visitMethod(@NotNull UMethod node) {
return false;
}
@Override
public boolean visitInitializer(@NotNull UClassInitializer node) {
return false;
}
@Override
public boolean visitLiteralExpression(@NotNull ULiteralExpression expression) {
Object value = expression.getValue();
if (!(value instanceof String)) return false;
String stringValue = (String)value;
if (stringValue.trim().isEmpty()) {
return false;
}
Set<PsiModifierListOwner> nonNlsTargets = new THashSet<>();
if (canBeI18ned(myManager.getProject(), expression, stringValue, nonNlsTargets)) {
UField parentField =
UastUtils.getParentOfType(expression, UField.class); // PsiTreeUtil.getParentOfType(expression, PsiField.class);
if (parentField != null) {
nonNlsTargets.add((PsiModifierListOwner)parentField.getJavaPsi());
}
final String description = CodeInsightBundle.message("inspection.i18n.message.general.with.value", "#ref");
PsiElement sourcePsi = expression.getSourcePsi();
List<LocalQuickFix> fixes = new ArrayList<>();
if (myOnTheFly) {
if (sourcePsi instanceof PsiLiteralExpression) {
if (I18nizeConcatenationQuickFix.getEnclosingLiteralConcatenation(sourcePsi) != null) {
fixes.add(new I18nizeConcatenationQuickFix());
}
fixes.add(new I18nizeQuickFix());
if (!isNotConstantFieldInitializer((PsiExpression)sourcePsi)) {
fixes.add(createIntroduceConstantFix());
}
if (PsiUtil.isLanguageLevel5OrHigher(sourcePsi)) {
final JavaPsiFacade facade = JavaPsiFacade.getInstance(myManager.getProject());
for (PsiModifierListOwner element : nonNlsTargets) {
if (!AnnotationUtil.isAnnotated(element, AnnotationUtil.NLS, CHECK_HIERARCHY | CHECK_EXTERNAL)) {
if (!element.getManager().isInProject(element) ||
facade.findClass(AnnotationUtil.NON_NLS, element.getResolveScope()) != null) {
fixes.add(new NonNlsAnnotationProvider().createFix(element));
}
}
}
}
}
}
else if (Registry.is("i18n.for.idea.project") ) {
fixes.add(new I18nizeBatchQuickFix());
}
LocalQuickFix[] farr = fixes.toArray(LocalQuickFix.EMPTY_ARRAY);
final ProblemDescriptor problem = myManager.createProblemDescriptor(sourcePsi,
description, myOnTheFly, farr,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
myProblems.add(problem);
}
return false;
}
private boolean isNotConstantFieldInitializer(final PsiExpression expression) {
PsiField parentField = expression.getParent() instanceof PsiField ? (PsiField)expression.getParent() : null;
return parentField != null && expression == parentField.getInitializer() &&
parentField.hasModifierProperty(PsiModifier.FINAL) &&
parentField.hasModifierProperty(PsiModifier.STATIC);
}
@Override
public boolean visitAnnotation(UAnnotation annotation) {
//prevent from @SuppressWarnings
if (BatchSuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME.equals(annotation.getQualifiedName())) {
return true;
}
return super.visitAnnotation(annotation);
}
private List<ProblemDescriptor> getProblems() {
return myProblems;
}
}
private boolean canBeI18ned(@NotNull Project project,
@NotNull ULiteralExpression expression,
@NotNull String value,
@NotNull Set<? super PsiModifierListOwner> nonNlsTargets) {
if (ignoreForNonAlpha && !StringUtil.containsAlphaCharacters(value)) {
return false;
}
if (ignoreForAllButNls) {
return JavaI18nUtil.isPassedToAnnotatedParam(expression, AnnotationUtil.NLS, null) ||
isReturnedFromAnnotatedMethod(expression, AnnotationUtil.NLS, null);
}
if (JavaI18nUtil.isPassedToAnnotatedParam(expression, AnnotationUtil.NON_NLS, nonNlsTargets)) {
return false;
}
if (isInNonNlsCall(expression, nonNlsTargets)) {
return false;
}
if (isInNonNlsEquals(expression, nonNlsTargets)) {
return false;
}
if (isPassedToNonNlsVariable(expression, nonNlsTargets)) {
return false;
}
if (JavaI18nUtil.mustBePropertyKey(expression, null)) {
return false;
}
if (isReturnedFromAnnotatedMethod(expression, AnnotationUtil.NON_NLS, nonNlsTargets)) {
return false;
}
if (ignoreForAssertStatements && isArgOfAssertStatement(expression)) {
return false;
}
if (ignoreForExceptionConstructors && isExceptionArgument(expression)) {
return false;
}
if (ignoreForEnumConstants && isArgOfEnumConstant(expression)) {
return false;
}
if (!ignoreForExceptionConstructors && isArgOfSpecifiedExceptionConstructor(expression, ignoreForSpecifiedExceptionConstructors.split(","))) {
return false;
}
if (ignoreForJUnitAsserts && isArgOfJUnitAssertion(expression)) {
return false;
}
if (ignoreForClassReferences && isClassRef(expression, value)) {
return false;
}
if (ignoreForPropertyKeyReferences && !PropertiesImplUtil.findPropertiesByKey(project, value).isEmpty()) {
return false;
}
if (ignoreToString && isToString(expression)) {
return false;
}
Pattern pattern = myCachedNonNlsPattern;
if (pattern != null) {
PsiFile file = expression.getSourcePsi().getContainingFile();
Document document = PsiDocumentManager.getInstance(project).getDocument(file);
int line = document.getLineNumber(expression.getSourcePsi().getTextRange().getStartOffset());
int lineStartOffset = document.getLineStartOffset(line);
CharSequence lineText = document.getCharsSequence().subSequence(lineStartOffset, document.getLineEndOffset(line));
Matcher matcher = pattern.matcher(lineText);
int start = 0;
while (matcher.find(start)) {
start = matcher.start();
PsiElement element = file.findElementAt(lineStartOffset + start);
if (PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null) return false;
if (start == lineText.length() - 1) break;
start++;
}
}
return true;
}
private static boolean isArgOfEnumConstant(ULiteralExpression expression) {
return expression.getUastParent() instanceof UEnumConstant;
}
public void cacheNonNlsCommentPattern() {
myCachedNonNlsPattern = nonNlsCommentPattern.trim().isEmpty() ? null : Pattern.compile(nonNlsCommentPattern);
}
private static boolean isClassRef(final ULiteralExpression expression, String value) {
if (StringUtil.startsWithChar(value,'
value = value.substring(1); // A favor for JetBrains team to catch common Logger usage practice.
}
Project project = Objects.requireNonNull(expression.getSourcePsi()).getProject();
return JavaPsiFacade.getInstance(project).findClass(value, GlobalSearchScope.allScope(project)) != null;
}
private static boolean isClassNonNls(@NotNull UDeclaration clazz) {
UFile uFile = UastUtils.getContainingUFile(clazz);
if (uFile == null) return false;
final PsiDirectory directory = uFile.getSourcePsi().getContainingDirectory();
return directory != null && isPackageNonNls(JavaDirectoryService.getInstance().getPackage(directory));
}
public static boolean isPackageNonNls(final PsiPackage psiPackage) {
if (psiPackage == null || psiPackage.getName() == null) {
return false;
}
final PsiModifierList pkgModifierList = psiPackage.getAnnotationList();
return pkgModifierList != null && pkgModifierList.hasAnnotation(AnnotationUtil.NON_NLS)
|| isPackageNonNls(psiPackage.getParentPackage());
}
private boolean isPassedToNonNlsVariable(@NotNull ULiteralExpression expression,
final Set<? super PsiModifierListOwner> nonNlsTargets) {
UExpression toplevel = JavaI18nUtil.getTopLevelExpression(expression);
PsiModifierListOwner var = null;
if (UastExpressionUtils.isAssignment(toplevel)) {
UExpression lExpression = ((UBinaryExpression)toplevel).getLeftOperand();
while (lExpression instanceof UArrayAccessExpression) {
lExpression = ((UArrayAccessExpression)lExpression).getReceiver();
}
if (lExpression instanceof UResolvable) {
final PsiElement resolved = ((UResolvable)lExpression).resolve();
if (resolved instanceof PsiVariable) var = (PsiVariable)resolved;
}
}
if (var == null) {
UElement parent = toplevel.getUastParent();
if (parent instanceof UVariable && toplevel.equals(((UVariable)parent).getUastInitializer())) {
if (((UVariable)parent).findAnnotation(AnnotationUtil.NON_NLS) != null) {
return true;
}
PsiElement psi = parent.getSourcePsi();
if (psi instanceof PsiModifierListOwner) {
var = (PsiModifierListOwner)psi;
}
}
else if (toplevel instanceof USwitchExpression) {
UExpression switchExpression = ((USwitchExpression)toplevel).getExpression();
if (switchExpression instanceof UResolvable) {
PsiElement resolved = ((UResolvable)switchExpression).resolve();
if (resolved instanceof PsiVariable) {
UElement caseParent = expression.getUastParent();
if (caseParent instanceof USwitchClauseExpression && ((USwitchClauseExpression)caseParent).getCaseValues().contains(expression)) {
var = (PsiVariable)resolved;
}
}
}
}
}
if (var != null) {
if (annotatedAsNonNls(var)) {
return true;
}
if (ignoreAssignedToConstants &&
var.hasModifierProperty(PsiModifier.STATIC) &&
var.hasModifierProperty(PsiModifier.FINAL)) {
return true;
}
nonNlsTargets.add(var);
}
return false;
}
private static boolean annotatedAsNonNls(final PsiModifierListOwner parent) {
if (parent instanceof PsiParameter) {
final PsiParameter parameter = (PsiParameter)parent;
final PsiElement declarationScope = parameter.getDeclarationScope();
if (declarationScope instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)declarationScope;
final int index = method.getParameterList().getParameterIndex(parameter);
return JavaI18nUtil.isMethodParameterAnnotatedWith(method, index, null, AnnotationUtil.NON_NLS, null, null);
}
}
return AnnotationUtil.isAnnotated(parent, AnnotationUtil.NON_NLS, CHECK_EXTERNAL);
}
private static boolean isInNonNlsEquals(ULiteralExpression expression, final Set<? super PsiModifierListOwner> nonNlsTargets) {
UElement parent = UastUtils.skipParenthesizedExprUp(expression.getUastParent());
if (!(parent instanceof UQualifiedReferenceExpression)) return false;
UExpression selector = ((UQualifiedReferenceExpression)parent).getSelector();
if (!(selector instanceof UCallExpression)) return false;
UCallExpression call = (UCallExpression)selector;
if (!HardcodedMethodConstants.EQUALS.equals(call.getMethodName()) ||
!MethodUtils.isEquals(call.resolve())) return false;
final List<UExpression> expressions = call.getValueArguments();
if (expressions.size() != 1) return false;
final UExpression arg = UastUtils.skipParenthesizedExprDown(expressions.get(0));
UResolvable ref = ObjectUtils.tryCast(arg, UResolvable.class);
if (ref != null) {
final PsiElement resolvedEntity = ref.resolve();
if (resolvedEntity instanceof PsiModifierListOwner) {
PsiModifierListOwner modifierListOwner = (PsiModifierListOwner)resolvedEntity;
if (annotatedAsNonNls(modifierListOwner)) {
return true;
}
nonNlsTargets.add(modifierListOwner);
}
}
return false;
}
private static boolean isInNonNlsCall(@NotNull UExpression expression,
final Set<? super PsiModifierListOwner> nonNlsTargets) {
UExpression parent = UastUtils.skipParenthesizedExprDown(JavaI18nUtil.getTopLevelExpression(expression));
if (parent instanceof UQualifiedReferenceExpression) {
return isNonNlsCall((UQualifiedReferenceExpression)parent, nonNlsTargets);
}
else if (parent != null && UastExpressionUtils.isAssignment(parent)) {
UExpression operand = ((UBinaryExpression)parent).getLeftOperand();
if (operand instanceof UReferenceExpression &&
isNonNlsCall((UReferenceExpression)operand, nonNlsTargets)) return true;
}
else if (parent instanceof UCallExpression) {
UElement parentOfNew = UastUtils.skipParenthesizedExprUp(parent.getUastParent());
if (parentOfNew instanceof ULocalVariable) {
final ULocalVariable newVariable = (ULocalVariable)parentOfNew;
if (annotatedAsNonNls(newVariable.getPsi())) {
return true;
}
PsiElement variableJavaPsi = newVariable.getJavaPsi();
if (variableJavaPsi instanceof PsiModifierListOwner) {
nonNlsTargets.add(((PsiModifierListOwner)variableJavaPsi));
}
return false;
}
}
return false;
}
private static boolean isNonNlsCall(UReferenceExpression qualifier, Set<? super PsiModifierListOwner> nonNlsTargets) {
final PsiElement resolved = qualifier.resolve();
if (resolved instanceof PsiModifierListOwner) {
final PsiModifierListOwner modifierListOwner = (PsiModifierListOwner)resolved;
if (annotatedAsNonNls(modifierListOwner)) {
return true;
}
nonNlsTargets.add(modifierListOwner);
}
if (qualifier instanceof UQualifiedReferenceExpression) {
UExpression receiver = UastUtils.skipParenthesizedExprDown(((UQualifiedReferenceExpression)qualifier).getReceiver());
if (receiver instanceof UReferenceExpression) {
return isNonNlsCall((UReferenceExpression)receiver, nonNlsTargets);
}
}
return false;
}
private static boolean isReturnedFromAnnotatedMethod(final ULiteralExpression expression,
final String fqn,
@Nullable final Set<? super PsiModifierListOwner> nonNlsTargets) {
PsiMethod method;
UNamedExpression nameValuePair = UastUtils.getParentOfType(expression, UNamedExpression.class);
if (nameValuePair != null) {
method = UastUtils.getAnnotationMethod(nameValuePair);
}
else {
//todo return from lambda
UElement parent = UastUtils.skipParenthesizedExprUp(expression.getUastParent());
while (parent instanceof UCallExpression &&
((UCallExpression)parent).getKind() == UastCallKind.NEW_ARRAY_WITH_INITIALIZER) {
parent = parent.getUastParent();
}
final UElement returnStmt = UastUtils.getParentOfType(parent, UReturnExpression.class, false, UCallExpression.class, ULambdaExpression.class);
if (!(returnStmt instanceof UReturnExpression)) {
return false;
}
UMethod uMethod = UastUtils.getParentOfType(expression, UMethod.class);
method = uMethod != null ? uMethod.getJavaPsi() : null;
}
if (method == null) return false;
String oppositeFQN = fqn.equals(AnnotationUtil.NLS) ? AnnotationUtil.NON_NLS : AnnotationUtil.NLS;
PsiAnnotation annotation = AnnotationUtil.findAnnotationInHierarchy(method, NON_NLS_NAMES);
if (annotation != null && annotation.hasQualifiedName(oppositeFQN)) {
return false;
}
if (AnnotationUtil.isAnnotated(method, fqn, CHECK_HIERARCHY | CHECK_EXTERNAL)) {
return true;
}
if (nonNlsTargets != null) {
nonNlsTargets.add(method);
}
return false;
}
private static boolean isToString(final ULiteralExpression expression) {
final UMethod method = UastUtils.getParentOfType(expression, UMethod.class);
if (method == null) return false;
final PsiType returnType = method.getReturnType();
return TO_STRING.equals(method.getName())
&& method.getUastParameters().isEmpty()
&& returnType != null
&& "java.lang.String".equals(returnType.getCanonicalText());
}
private static boolean isArgOfJUnitAssertion(ULiteralExpression expression) {
final UElement parent = UastUtils.skipParenthesizedExprUp(expression.getUastParent());
if (parent == null || !UastExpressionUtils.isMethodCall(parent)) {
return false;
}
@NonNls final String methodName = ((UCallExpression)parent).getMethodName();
if (methodName == null) {
return false;
}
if (!methodName.startsWith("assert") && !methodName.equals("fail")) {
return false;
}
final PsiMethod method = ((UCallExpression)parent).resolve();
if (method == null) {
return false;
}
final PsiClass containingClass = method.getContainingClass();
if (containingClass == null) {
return false;
}
return InheritanceUtil.isInheritor(containingClass,"org.junit.Assert") ||
InheritanceUtil.isInheritor(containingClass,"org.junit.jupiter.api.Assertions") ||
InheritanceUtil.isInheritor(containingClass, "junit.framework.Assert");
}
private static boolean isArgOfSpecifiedExceptionConstructor(ULiteralExpression expression,
String[] specifiedExceptions) {
if (specifiedExceptions.length == 0) return false;
UCallExpression parent = UastUtils.getParentOfType(expression, UCallExpression.class, true, UClass.class);
if (parent == null || !UastExpressionUtils.isConstructorCall(parent)) {
return false;
}
final PsiMethod resolved = parent.resolve();
final PsiClass aClass = resolved != null ? resolved.getContainingClass() : null;
if (aClass == null) {
return false;
}
return ArrayUtil.contains(aClass.getQualifiedName(), specifiedExceptions);
}
private static boolean isArgOfAssertStatement(UExpression expression) {
UCallExpression parent = UastUtils.getParentOfType(expression, UCallExpression.class);
return parent != null && "assert".equals(parent.getMethodName());
}
public static boolean isExceptionArgument(@NotNull UExpression expression) {
final UCallExpression newExpression =
UastUtils.getParentOfType(expression, UCallExpression.class, true, UBlockExpression.class, UClass.class);
if (newExpression != null) {
if (UastExpressionUtils.isConstructorCall(newExpression)) {
final PsiType newExpressionType = newExpression.getExpressionType();
return InheritanceUtil.isInheritor(newExpressionType, CommonClassNames.JAVA_LANG_THROWABLE);
}
else if (UastExpressionUtils.isMethodCall(newExpression)) {
String methodName = newExpression.getMethodName();
if (PsiKeyword.SUPER.equals(methodName) || PsiKeyword.THIS.equals(methodName)) {
PsiMethod ctor = newExpression.resolve();
return ctor != null &&
InheritanceUtil.isInheritor(ctor.getContainingClass(), CommonClassNames.JAVA_LANG_THROWABLE);
}
}
}
return false;
}
}
|
package system;
import api.Task;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
*
* @author Peter Cappello
*/
public interface Worker extends Remote
{
/**
* Execute Task.
* @param task
* @return Task Return object
* @throws RemoteException
*/
Return execute( Task task ) throws RemoteException;
}
|
package ifc.container;
import com.sun.star.container.XNamed;
import lib.MultiMethodTest;
import util.utils;
/**
* Testing <code>com.sun.star.container.XNamed</code>
* interface methods :
* <ul>
* <li><code> getName()</code></li>
* <li><code> setName()</code></li>
* </ul>
* This test need the following object relations :
* <ul>
* <li> <code>'setName'</code> : of <code>Boolean</code>
* type. If it exists then <code>setName</code> method
* isn't to be tested and result of this test will be
* equal to relation value.</li>
* <ul> <p>
* Test is <b> NOT </b> multithread compilant. <p>
* @see com.sun.star.container.XNamed
*/
public class _XNamed extends MultiMethodTest {
public XNamed oObj = null; // oObj filled by MultiMethodTest
/**
* Test calls the method and checks return value and that
* no exceptions were thrown. <p>
* Has <b> OK </b> status if the method returns non null value
* and no exceptions were thrown. <p>
*/
public void _getName() {
// write to log what we try next
log.println("test for getName()");
boolean result = true;
boolean loc_result = true;
String name = null;
loc_result = ((name = oObj.getName()) != null);
log.println("getting the name \"" + name + "\"");
if (loc_result) {
log.println("... getName() - OK");
} else {
log.println("... getName() - FAILED");
}
result &= loc_result;
tRes.tested("getName()", result);
}
/**
* Sets a new name for object and checks if it was properly
* set. Special cases for the following objects :
* <ul>
* <li><code>ScSheetLinkObj</code> : name must be in form of URL.</li>
* <li><code>ScDDELinkObj</code> : name must contain link to cell in
* some external Sheet.</li>
* </ul>
* Has <b> OK </b> status if new name was successfully set, or if
* object environment contains relation <code>'setName'</code> with
* value <code>true</code>. <p>
* The following method tests are to be completed successfully before :
* <ul>
* <li> <code> getName() </code> : to be sure the method works</li>
* </ul>
*/
public void _setName() {
String Oname = tEnv.getTestCase().getObjectName();
String nsn = (String) tEnv.getObjRelation("NoSetName");
if (nsn != null) {
Oname = nsn;
}
if ((Oname.indexOf("Exporter") > 0) || (nsn != null)) {
log.println("With " + Oname + " setName() doesn't work");
log.println("see idl-file for further information");
tRes.tested("setName()", true);
return;
}
requiredMethod("getName()");
log.println("testing setName() ... ");
String oldName = oObj.getName();
String NewName = (oldName == null) ? "XNamed" : oldName + "X";
String testobjname = tEnv.getTestCase().getObjectName();
if (testobjname.equals("ScSheetLinkObj")) {
// special case, here name is equals to links URL.
NewName = "file:///c:/somename/from/XNamed";
} else if (testobjname.equals("ScDDELinkObj")) {
String fileName = utils.getFullTestDocName("ScDDELinksObj.sdc");
NewName = "soffice|" + fileName + "!Sheet1.A2";
} else if (testobjname.equals("SwXAutoTextGroup")) {
//This avoids a GPF
NewName = "XNamed*1";
}
boolean result = true;
boolean loc_result = true;
Boolean sName = (Boolean) tEnv.getObjRelation("setName");
if (sName == null) {
log.println("set the name of object to \"" + NewName + "\"");
oObj.setName(NewName);
log.println("check that container has element with this name");
String name = oObj.getName();
log.println("getting the name \"" + name + "\"");
loc_result = name.equals(NewName);
if (loc_result) {
log.println("... setName() - OK");
} else {
log.println("... setName() - FAILED");
}
result &= loc_result;
oObj.setName(oldName);
} else {
log.println("The names for the object '" + testobjname +
"' are fixed.");
log.println("It is not possible to rename.");
log.println("So 'setName()' is always OK");
result = sName.booleanValue();
}
tRes.tested("setName()", result);
}
}
|
package ifc.text;
import lib.MultiPropertyTest;
import com.sun.star.text.XTextColumns;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
/**
* Testing <code>com.sun.star.text.TextSection</code>
* service properties :
* <ul>
* <li><code> Condition</code></li>
* <li><code> IsVisible</code></li>
* <li><code> IsProtected</code></li>
* <li><code> FileLink</code></li>
* <li><code> LinkRegion</code></li>
* <li><code> DDECommandType</code></li>
* <li><code> DDECommandFile</code></li>
* <li><code> DDECommandElement</code></li>
* <li><code> BackGraphicURL</code></li>
* <li><code> BackGraphicFilter</code></li>
* <li><code> BackGraphicLocation</code></li>
* <li><code> FootnoteIsCollectAtTextEnd</code></li>
* <li><code> FootnoteIsRestartNumbering</code></li>
* <li><code> FootnoteRestartNumberingAt</code></li>
* <li><code> FootnoteIsOwnNumbering</code></li>
* <li><code> FootnoteNumberingType</code></li>
* <li><code> FootnoteNumberingPrefix</code></li>
* <li><code> FootnoteNumberingSuffix</code></li>
* <li><code> EndnoteIsCollectAtTextEnd</code></li>
* <li><code> EndnoteIsRestartNumbering</code></li>
* <li><code> EndnoteRestartNumberingAt</code></li>
* <li><code> EndnoteIsOwnNumbering</code></li>
* <li><code> EndnoteNumberingType</code></li>
* <li><code> EndnoteNumberingPrefix</code></li>
* <li><code> EndnoteNumberingSuffix</code></li>
* <li><code> IsAutomaticUpdate</code></li>
* </ul> <p>
* The following predefined files needed to complete the test:
* <ul>
* <li> <code>crazy-blue.jpg, space-metal.jpg</code> : are used for
* setting 'BackGraphicURL' property. </li>
* <ul> <p>
* Properties testing is automated by <code>lib.MultiPropertyTest</code>.
* @see com.sun.star.text.TextSection
*/
public class _TextSection extends MultiPropertyTest {
/**
* Only image file URL can be used as a value.
*/
public void _BackGraphicURL() {
log.println("Testing with custom Property tester") ;
testProperty("BackGraphicURL",
util.utils.getFullTestURL("crazy-blue.jpg"),
util.utils.getFullTestURL("space-metal.jpg")) ;
}
/**
* This property can be void, so if old value is <code> null </code>
* new value must be specified.
*/
public void _FootnoteNumberingType() {
log.println("Testing with custom Property tester") ;
testProperty("FootnoteNumberingType",
new Short(com.sun.star.text.FootnoteNumbering.PER_DOCUMENT),
new Short(com.sun.star.text.FootnoteNumbering.PER_PAGE)) ;
}
/**
* Custom property tester for property <code>TextColumns</code>
*/
protected PropertyTester TextColumnsTester = new PropertyTester() {
protected Object getNewValue(String propName, Object oldValue) {
XTextColumns TC = null;
short val2set = 25;
TC = (XTextColumns) tEnv.getObjRelation("TC");
try {
val2set += ((XTextColumns) AnyConverter.toObject(
new Type(XTextColumns.class),oldValue)).getColumnCount();
} catch (com.sun.star.lang.IllegalArgumentException iae) {
log.println("Couldn't change Column count");
}
TC.setColumnCount(val2set);
return TC;
};
protected boolean compare(Object obj1, Object obj2) {
short val1 = 0;
short val2 = 1;
try {
val1 = ((XTextColumns) AnyConverter.toObject(
new Type(XTextColumns.class),obj1)).getColumnCount();
val2 = ((XTextColumns) AnyConverter.toObject(
new Type(XTextColumns.class),obj2)).getColumnCount();
} catch (com.sun.star.lang.IllegalArgumentException iae) {
log.println("comparing values failed");
}
return val1 == val2;
}
protected String toString(Object obj) {
return "XTextColumns: ColumnCount = "+
((XTextColumns) obj).getColumnCount();
}
};
public void _TextColumns() {
log.println("Testing with custom Property tester");
testProperty("TextColumns", TextColumnsTester);
}
} //finish class _TextContent
|
package sk.lovasko.trnava.renderer;
import sk.lovasko.trnava.strategy.Strategy;
import sk.lovasko.trnava.palette.Palette;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
public interface Renderer
{
/**
* Generate fractal image using custom technology.
*
* @param minx fractal top left X coordinate
* @param miny fractal top left Y coordinate
* @param maxx fractal bottom right X coordinate
* @param maxy fractal bottom right Y coordinate
* @param max_limit fractal detail
* @param strategy used strategy
* @param palette used palette
* @param size size of the whole image
* @return generated fractal image
*/
BufferedImage
render (final double minx, final double miny, final double maxx,
final double maxy, final int max_limit, final Strategy strategy,
final Palette palette, final Dimension size);
}
|
package soot.toolkits.scalar;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import soot.Local;
import soot.Timers;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.options.Options;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.UnitGraph;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.singletonList;
import static java.util.Collections.emptyList;
import static java.util.Arrays.asList;
import static java.util.Arrays.copyOf;
/**
* Analysis that provides an implementation of the LocalDefs interface.
*/
public class SmartLocalDefs implements LocalDefs {
protected static class StaticSingleAssignment implements LocalDefs {
private final Map<Local, List<Unit>> localToDefs;
protected StaticSingleAssignment(List<Unit>[] units, Local[] locals) {
assert units.length == locals.length;
localToDefs = new IdentityHashMap<Local, List<Unit>>(units.length);
for (int i = 0; i < units.length; i++) {
List<Unit> list = units[i];
if (!list.isEmpty()) {
assert list.size() == 1;
list = singletonList(list.get(0));
localToDefs.put(locals[i], list);
}
}
}
@Override
public List<Unit> getDefsOfAt(Local l, Unit s) {
for (ValueBox useBox : s.getUseBoxes()) {
if (l == useBox.getValue()) {
return getDefsOfAt(useBox);
}
}
throw new RuntimeException();
}
public List<Unit> getDefsOfAt(ValueBox valueBox) {
Value v = valueBox.getValue();
if (v instanceof Local) {
List<Unit> r = localToDefs.get(v);
if (r == null) {
return emptyList();
}
return r;
}
throw new RuntimeException();
}
}
protected class DefaultAssignment implements LocalDefs {
private final Map<ValueBox, List<Unit>> resultValueBoxes;
protected DefaultAssignment(List<Unit>[] unitList) {
// most of the units are like "a := b + c",
// or a invoke like "a := b.foo()"
resultValueBoxes = new IdentityHashMap<ValueBox, List<Unit>>(g.size() * 3 + 1);
LocalDefsAnalysis reachingAnalysis = new LocalDefsAnalysis();
Unit[] buffer = new Unit[localRange[n]];
for (Unit s : g) {
for (ValueBox useBox : s.getUseBoxes()) {
Value v = useBox.getValue();
if (v instanceof Local) {
Local l = (Local) v;
int lno = l.getNumber();
int from = localRange[lno];
int to = localRange[lno + 1];
assert from <= to;
if (from == to) {
List<Unit> list = unitList[lno];
if (!list.isEmpty()) {
list = singletonList(list.get(0));
resultValueBoxes.put(useBox, list);
}
} else {
int j = 0;
BitSet reaching = reachingAnalysis.getFlowBefore(s);
for (int i = to; (i = reaching
.previousSetBit(i - 1)) >= from;) {
buffer[j++] = units[i];
}
if (j > 0) {
List<Unit> list = (j == 1)
? singletonList(buffer[0])
: unmodifiableList(asList(copyOf(buffer, j)))
;
resultValueBoxes.put(useBox, list);
}
}
}
}
}
}
@Override
public List<Unit> getDefsOfAt(Local l, Unit s) {
for (ValueBox useBox : s.getUseBoxes()) {
if (l == useBox.getValue()) {
return getDefsOfAt(useBox);
}
}
throw new RuntimeException();
}
public List<Unit> getDefsOfAt(ValueBox valueBox) {
List<Unit> r = resultValueBoxes.get(valueBox);
if (r == null) {
Value v = valueBox.getValue();
if (v instanceof Local) {
return emptyList();
}
throw new RuntimeException();
}
return r;
}
}
private class LocalDefsAnalysis extends ForwardFlowAnalysis<Unit, BitSet> {
private LocalDefsAnalysis() {
super(g);
doAnalysis();
}
@Override
protected void flowThrough(BitSet in, Unit unit, BitSet out) {
// copy everything that is live
out.clear();
if (!in.isEmpty()) {
for (Local l : liveLocals.getLiveLocalsAfter(unit)) {
int i = l.getNumber();
int j = i + 1;
out.set(localRange[i], localRange[j]);
}
out.and(in);
}
if (unit.getDefBoxes().isEmpty()) {
return;
}
// reassign all definitions
Integer idx = indexOfUnit.get(unit);
if (idx != null) {
for (ValueBox vb : unit.getDefBoxes()) {
Value v = vb.getValue();
if (v instanceof Local) {
int lno = ((Local) v).getNumber();
int from = localRange[lno];
int to = localRange[lno + 1];
assert from <= to;
if (from < to) {
out.clear(from, to);
out.set(idx);
}
}
}
}
}
@Override
protected void mergeInto(Unit succNode, BitSet inout, BitSet in) {
inout.or(in);
}
@Override
protected void copy(BitSet source, BitSet dest) {
dest.clear();
dest.or(source);
}
@Override
protected BitSet newInitialFlow() {
return new BitSet(localRange[n]);
}
@Override
protected BitSet entryInitialFlow() {
return newInitialFlow();
}
@Override
protected void merge(BitSet in1, BitSet in2, BitSet out) {
throw new RuntimeException("should never be called");
}
}
final private DirectedGraph<Unit> g;
final int n;
private int[] localRange;
private Unit[] units;
private Map<Unit, Integer> indexOfUnit;
private LiveLocals liveLocals;
private LocalDefs localDefs;
public SmartLocalDefs(UnitGraph graph, LiveLocals live) {
this(graph, live, graph.getBody().getLocals());
}
protected SmartLocalDefs(DirectedGraph<Unit> graph, LiveLocals live, Collection<Local> locals) {
this(graph, live, locals.toArray(new Local[locals.size()]));
}
protected SmartLocalDefs(DirectedGraph<Unit> graph, LiveLocals live, Local... locals) {
if (Options.v().time())
Timers.v().defsTimer.start();
this.g = graph;
this.n = locals.length;
this.liveLocals = live;
// reassign local numbers
int[] oldNumbers = new int[n];
for (int i = 0; i < n; i++) {
oldNumbers[i] = locals[i].getNumber();
locals[i].setNumber(i);
}
init(locals);
// restore local numbering
for (int i = 0; i < n; i++) {
locals[i].setNumber(oldNumbers[i]);
}
if (Options.v().time())
Timers.v().defsTimer.end();
}
@SuppressWarnings("unchecked")
private void init(Local[] locals) {
indexOfUnit = new IdentityHashMap<Unit, Integer>(g.size());
units = new Unit[g.size()];
localRange = new int[n + 1];
List<Unit>[] unitList = (List<Unit>[]) new List[n];
for (int i = 0; i < n; i++) {
unitList[i] = new ArrayList<Unit>();
}
// collect all live def points
for (Unit unit : g) {
for (ValueBox box : unit.getDefBoxes()) {
Value v = box.getValue();
if (v instanceof Local) {
Local l = (Local) v;
int lno = l.getNumber();
// only add local if it is used
if (liveLocals.getLiveLocalsAfter(unit).contains(l)) {
unitList[lno].add(unit);
}
}
}
}
// if a variable reaches at least one head node, it can be undefined
BitSet undefinedLocals = new BitSet(n);
for (Unit unit : g.getHeads()) {
for (Local l : liveLocals.getLiveLocalsBefore(unit)) {
undefinedLocals.set(l.getNumber());
}
}
localRange[0] = 0;
for (int j = 0, i = 0; i < n; i++) {
if (unitList[i].size() >= 2 || undefinedLocals.get(i)) {
for (Unit u : unitList[i]) {
indexOfUnit.put(units[j] = u, j);
j++;
}
}
localRange[i + 1] = j;
}
localDefs = (localRange[n] == 0)
? new StaticSingleAssignment(unitList, locals)
: new DefaultAssignment(unitList)
;
}
@Override
public List<Unit> getDefsOfAt(Local l, Unit s) {
return localDefs.getDefsOfAt(l, s);
}
}
|
package org.jetbrains.yaml;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.LocalTimeCounter;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.psi.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author oleg
*/
public class YAMLUtil {
public static boolean isScalarValue(final PsiElement element) {
if (element == null){
return false;
}
//noinspection ConstantConditions
final IElementType type = element.getNode().getElementType();
return YAMLElementTypes.SCALAR_VALUES.contains(type) || type == YAMLTokenTypes.TEXT;
}
public static boolean isScalarOrEmptyCompoundValue(final PsiElement element) {
return isScalarValue(element) || (element instanceof YAMLCompoundValue && ((YAMLCompoundValue)element).getYAMLElements().isEmpty());
}
@Nullable
public static String getFullKey(final YAMLKeyValue yamlKeyValue) {
final StringBuilder builder = new StringBuilder();
YAMLKeyValue element = yamlKeyValue;
PsiElement parent;
while (element!=null &&
(parent = PsiTreeUtil.getParentOfType(element, YAMLKeyValue.class, YAMLDocument.class)) instanceof YAMLKeyValue){
if (builder.length()>0){
builder.insert(0, '.');
}
builder.insert(0, element.getKeyText());
element = (YAMLKeyValue) parent;
}
return builder.toString();
}
@Nullable
public static YAMLPsiElement getRecord(final YAMLFile file, final String[] key) {
assert key.length != 0;
final YAMLPsiElement root = file.getDocuments().get(0);
if (root != null){
YAMLPsiElement record = root;
for (int i=0;i<key.length;i++){
record = findByName(record, key[i]);
if (record == null){
return null;
}
}
return record;
}
return null;
}
@Nullable
private static YAMLKeyValue findByName(final YAMLPsiElement element, final String name){
final List<YAMLPsiElement> list;
if (element instanceof YAMLKeyValue) {
final PsiElement value = ((YAMLKeyValue)element).getValue();
list = (value instanceof YAMLCompoundValue) ? ((YAMLCompoundValue)value).getYAMLElements() : Collections.<YAMLPsiElement>emptyList();
} else {
list = element.getYAMLElements();
}
for (YAMLPsiElement child : list) {
if (child instanceof YAMLKeyValue){
final YAMLKeyValue yamlKeyValue = (YAMLKeyValue)child;
// We use null as wildcard
if (name == null || name.equals(yamlKeyValue.getKeyText())){
return yamlKeyValue;
}
}
}
return null;
}
@Nullable
public static Pair<PsiElement, String> getValue(final YAMLFile file, final String[] key) {
final YAMLPsiElement record = getRecord(file, key);
if (record instanceof YAMLKeyValue) {
final PsiElement psiValue = ((YAMLKeyValue)record).getValue();
if (YAMLUtil.isScalarValue(psiValue)){
return Pair.create(psiValue, ((YAMLKeyValue)record).getValueText());
}
}
return null;
}
public List<String> getAllKeys(final YAMLFile file){
return getAllKeys(file, ArrayUtil.EMPTY_STRING_ARRAY);
}
public List<String> getAllKeys(final YAMLFile file, final String[] key){
final YAMLPsiElement record = getRecord(file, key);
if (!(record instanceof YAMLKeyValue)){
return Collections.emptyList();
}
PsiElement psiValue = ((YAMLKeyValue)record).getValue();
final StringBuilder builder = new StringBuilder();
for (String keyPart : key) {
if (builder.length() != 0){
builder.append(".");
}
builder.append(keyPart);
}
final ArrayList<String> list = new ArrayList<String>();
addKeysRec(builder.toString(), psiValue, list);
return list;
}
private static void addKeysRec(final String prefix, final PsiElement element, final List<String> list) {
if (element instanceof YAMLCompoundValue){
for (YAMLPsiElement child : ((YAMLCompoundValue)element).getYAMLElements()) {
addKeysRec(prefix, child, list);
}
}
if (element instanceof YAMLKeyValue){
final YAMLKeyValue yamlKeyValue = (YAMLKeyValue)element;
final PsiElement psiValue = yamlKeyValue.getValue();
String key = yamlKeyValue.getKeyText();
if (prefix.length() > 0){
key = prefix + "." + key;
}
if (YAMLUtil.isScalarOrEmptyCompoundValue(psiValue)) {
list.add(key);
} else {
addKeysRec(key, psiValue, list);
}
}
}
public YAMLKeyValue createI18nRecord(final YAMLFile file, final String key, final String text) {
return createI18nRecord(file, key.split("\\."), text);
}
@Nullable
public static YAMLKeyValue createI18nRecord(final YAMLFile file, final String[] key, final String text) {
final YAMLPsiElement root = file.getDocuments().get(0);
if (root != null){
YAMLPsiElement record = root;
final int keyLength = key.length;
int i;
for (i=0;i<keyLength;i++) {
YAMLKeyValue nextRecord = findByName(record, key[i]);
if (i == 0 && nextRecord == null) {
final YAMLFile yamlFile =
(YAMLFile) PsiFileFactory.getInstance(file.getProject())
.createFileFromText("temp." + YAMLFileType.YML.getDefaultExtension(), YAMLFileType.YML,
key[i] + ":", LocalTimeCounter.currentTime(), true);
final YAMLKeyValue topKeyValue = (YAMLKeyValue) yamlFile.getDocuments().get(0).getYAMLElements().get(0);
nextRecord = (YAMLKeyValue) root.add(topKeyValue);
}
if (nextRecord != null){
record = nextRecord;
} else
if (record instanceof YAMLKeyValue){
final YAMLKeyValue keyValue = (YAMLKeyValue)record;
final PsiElement value = keyValue.getValue();
String indent = keyValue.getValueIndent();
// Generate items
final StringBuilder builder = new StringBuilder();
builder.append("foo:");
for (int j=i;j<keyLength;j++){
builder.append("\n").append(indent.length() == 0 ? " " : indent);
builder.append(key[j]).append(":");
indent += " ";
}
builder.append(" ").append(text);
final YAMLFile yamlFile =
(YAMLFile) PsiFileFactory.getInstance(file.getProject())
.createFileFromText("temp." + YAMLFileType.YML.getDefaultExtension(), YAMLFileType.YML,
builder.toString(), LocalTimeCounter.currentTime(), true);
final YAMLKeyValue topKeyValue = (YAMLKeyValue) yamlFile.getDocuments().get(0).getYAMLElements().get(0);
final ASTNode generatedNode = topKeyValue.getNode();
@SuppressWarnings({"ConstantConditions"})
final ASTNode[] generatedChildren = generatedNode.getChildren(null);
final ASTNode valueNode = value.getNode();
if (valueNode instanceof LeafElement){
return (YAMLKeyValue)value.replace(generatedChildren[3].getChildren(null)[0].getPsi());
}
//noinspection ConstantConditions
valueNode.addChild(generatedChildren[1]);
valueNode.addChild(generatedChildren[2]);
valueNode.addChild(generatedChildren[3].getChildren(null)[0]);
return (YAMLKeyValue) value.getLastChild();
}
}
// Conflict with existing value
final StringBuilder builder = new StringBuilder();
final int top = Math.min(i + 1, keyLength);
for (int j=0;j<top;j++){
if (builder.length() > 0){
builder.append('.');
}
builder.append(key[j]);
}
throw new IncorrectOperationException(YAMLBundle.message("new.name.conflicts.with", builder.toString()));
}
return null;
}
public static void removeI18nRecord(final YAMLFile file, final String[] key){
PsiElement element = getRecord(file, key);
while (element != null){
final PsiElement parent = element.getParent();
if (parent instanceof YAMLDocument) {
((YAMLKeyValue)element).getValue().delete();
return;
}
if (parent instanceof YAMLCompoundValue) {
if (((YAMLCompoundValue)parent).getYAMLElements().size() > 1) {
element.delete();
return;
}
}
element = parent;
}
}
public static PsiElement rename(final YAMLKeyValue element, final String newName) {
if (newName.contains(".")){
throw new IncorrectOperationException(YAMLBundle.message("rename.wrong.name"));
}
if (newName.equals(element.getName())){
throw new IncorrectOperationException(YAMLBundle.message("rename.same.name"));
}
final YAMLFile yamlFile =
(YAMLFile) PsiFileFactory.getInstance(element.getProject())
.createFileFromText("temp." + YAMLFileType.YML.getDefaultExtension(), YAMLFileType.YML,
newName +": Foo", LocalTimeCounter.currentTime(), true);
final YAMLKeyValue topKeyValue = (YAMLKeyValue) yamlFile.getDocuments().get(0).getYAMLElements().get(0);
element.getKey().replace(topKeyValue.getKey());
return element;
}
}
|
package net.i2p.data;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import com.nettgryppa.security.HashCash;
import net.i2p.I2PException;
import net.i2p.client.I2PClient;
import net.i2p.client.I2PClientFactory;
import net.i2p.client.I2PSession;
import net.i2p.client.I2PSessionException;
import net.i2p.crypto.DSAEngine;
/**
* This helper class reads and writes files in the
* same "eepPriv.dat" format used by the client code.
* The format is:
* - Destination (387 bytes if no certificate, otherwise longer)
* - Public key (256 bytes)
* - Signing Public key (128 bytes)
* - Cert. type (1 byte)
* - Cert. length (2 bytes)
* - Certificate if length != 0
* - Private key (256 bytes)
* - Signing Private key (20 bytes)
* Total 663 bytes
*
* @author welterde, zzz
*/
public class PrivateKeyFile {
/**
* Create a new PrivateKeyFile, or modify an existing one, with various
* types of Certificates.
*
* Changing a Certificate does not change the public or private keys.
* But it does change the Destination Hash, which effectively makes it
* a new Destination. In other words, don't change the Certificate on
* a Destination you've already registered in a hosts.txt key add form.
*
* Copied and expanded from that in Destination.java
*/
public static void main(String args[]) {
if (args.length == 0) {
System.err.println("Usage: PrivateKeyFile filename (generates if nonexistent, then prints)");
System.err.println(" PrivateKeyFile -h filename (generates if nonexistent, adds hashcash cert)");
System.err.println(" PrivateKeyFile -h effort filename (specify HashCash effort instead of default " + HASH_EFFORT + ")");
System.err.println(" PrivateKeyFile -n filename (changes to null cert)");
System.err.println(" PrivateKeyFile -s filename signwithdestfile (generates if nonexistent, adds cert signed by 2nd dest)");
System.err.println(" PrivateKeyFile -u filename (changes to unknown cert)");
System.err.println(" PrivateKeyFile -x filename (changes to hidden cert)");
return;
}
I2PClient client = I2PClientFactory.createClient();
int filearg = 0;
if (args.length > 1) {
if (args.length >= 2 && args[0].equals("-h"))
filearg = args.length - 1;
else
filearg = 1;
}
try {
File f = new File(args[filearg]);
PrivateKeyFile pkf = new PrivateKeyFile(f, client);
Destination d = pkf.createIfAbsent();
System.out.println("Original Destination:");
System.out.println(pkf);
verifySignature(d);
if (args.length == 1)
return;
if (args[0].equals("-n")) {
// Cert constructor generates a null cert
pkf.setCertType(Certificate.CERTIFICATE_TYPE_NULL);
System.out.println("New destination with null cert is:");
} else if (args[0].equals("-u")) {
pkf.setCertType(99);
System.out.println("New destination with unknown cert is:");
} else if (args[0].equals("-x")) {
pkf.setCertType(Certificate.CERTIFICATE_TYPE_HIDDEN);
System.out.println("New destination with hidden cert is:");
} else if (args[0].equals("-h")) {
int hashEffort = HASH_EFFORT;
if (args.length == 3)
hashEffort = Integer.parseInt(args[1]);
System.out.println("Estimating hashcash generation time, stand by...");
System.out.println(estimateHashCashTime(hashEffort));
pkf.setHashCashCert(hashEffort);
System.out.println("New destination with hashcash cert is:");
} else if (args.length == 3 && args[0].equals("-s")) {
// Sign dest1 with dest2's Signing Private Key
PrivateKeyFile pkf2 = new PrivateKeyFile(args[2]);
pkf.setSignedCert(pkf2);
System.out.println("New destination with signed cert is:");
}
System.out.println(pkf);
pkf.write();
verifySignature(d);
} catch (Exception e) {
e.printStackTrace();
}
}
public PrivateKeyFile(String file) {
this(new File(file), I2PClientFactory.createClient());
}
public PrivateKeyFile(File file) {
this(file, I2PClientFactory.createClient());
}
public PrivateKeyFile(File file, I2PClient client) {
this.file = file;
this.client = client;
this.dest = null;
this.privKey = null;
this.signingPrivKey = null;
}
/** Also reads in the file to get the privKey and signingPrivKey,
* which aren't available from I2PClient.
*/
public Destination createIfAbsent() throws I2PException, IOException, DataFormatException {
if(!this.file.exists()) {
FileOutputStream out = new FileOutputStream(this.file);
this.client.createDestination(out);
out.close();
}
return getDestination();
}
/** Also sets the local privKey and signingPrivKey */
public Destination getDestination() throws I2PSessionException, IOException, DataFormatException {
if (dest == null) {
I2PSession s = open();
if (s != null) {
this.dest = new VerifiedDestination(s.getMyDestination());
this.privKey = s.getDecryptionKey();
this.signingPrivKey = s.getPrivateKey();
}
}
return this.dest;
}
public void setDestination(Destination d) {
this.dest = d;
}
/** change cert type - caller must also call write() */
public Certificate setCertType(int t) {
if (this.dest == null)
throw new IllegalArgumentException("Dest is null");
Certificate c = new Certificate();
c.setCertificateType(t);
this.dest.setCertificate(c);
return c;
}
/** change to hashcash cert - caller must also call write() */
public Certificate setHashCashCert(int effort) {
Certificate c = setCertType(Certificate.CERTIFICATE_TYPE_HASHCASH);
long begin = System.currentTimeMillis();
System.out.println("Starting hashcash generation now...");
String resource = this.dest.getPublicKey().toBase64() + this.dest.getSigningPublicKey().toBase64();
HashCash hc;
try {
hc = HashCash.mintCash(resource, effort);
} catch (Exception e) {
return null;
}
System.out.println("Generation took: " + DataHelper.formatDuration(System.currentTimeMillis() - begin));
System.out.println("Full Hashcash is: " + hc);
// Take the resource out of the stamp
String hcs = hc.toString();
int end1 = 0;
for (int i = 0; i < 3; i++) {
end1 = 1 + hcs.indexOf(':', end1);
if (end1 < 0) {
System.out.println("Bad hashcash");
return null;
}
}
int start2 = hcs.indexOf(':', end1);
if (start2 < 0) {
System.out.println("Bad hashcash");
return null;
}
hcs = hcs.substring(0, end1) + hcs.substring(start2);
System.out.println("Short Hashcash is: " + hcs);
c.setPayload(hcs.getBytes());
return c;
}
/** sign this dest by dest found in pkf2 - caller must also call write() */
public Certificate setSignedCert(PrivateKeyFile pkf2) {
Certificate c = setCertType(Certificate.CERTIFICATE_TYPE_SIGNED);
Destination d2;
try {
d2 = pkf2.getDestination();
} catch (Exception e) {
return null;
}
if (d2 == null)
return null;
SigningPrivateKey spk2 = pkf2.getSigningPrivKey();
System.out.println("Signing With Dest:");
System.out.println(pkf2.toString());
int len = PublicKey.KEYSIZE_BYTES + SigningPublicKey.KEYSIZE_BYTES; // no cert
byte[] data = new byte[len];
System.arraycopy(this.dest.getPublicKey().getData(), 0, data, 0, PublicKey.KEYSIZE_BYTES);
System.arraycopy(this.dest.getSigningPublicKey().getData(), 0, data, PublicKey.KEYSIZE_BYTES, SigningPublicKey.KEYSIZE_BYTES);
byte[] payload = new byte[Hash.HASH_LENGTH + Signature.SIGNATURE_BYTES];
byte[] sig = DSAEngine.getInstance().sign(new ByteArrayInputStream(data), spk2).getData();
System.arraycopy(sig, 0, payload, 0, Signature.SIGNATURE_BYTES);
// Add dest2's Hash for reference
byte[] h2 = d2.calculateHash().getData();
System.arraycopy(h2, 0, payload, Signature.SIGNATURE_BYTES, Hash.HASH_LENGTH);
c.setCertificateType(Certificate.CERTIFICATE_TYPE_SIGNED);
c.setPayload(payload);
return c;
}
public PrivateKey getPrivKey() {
return this.privKey;
}
public SigningPrivateKey getSigningPrivKey() {
return this.signingPrivKey;
}
public I2PSession open() throws I2PSessionException, IOException {
return this.open(new Properties());
}
public I2PSession open(Properties opts) throws I2PSessionException, IOException {
// open input file
FileInputStream in = new FileInputStream(this.file);
// create sesssion
I2PSession s = this.client.createSession(in, opts);
// close file
in.close();
return s;
}
/**
* Copied from I2PClientImpl.createDestination()
*/
public void write() throws IOException, DataFormatException {
FileOutputStream out = new FileOutputStream(this.file);
this.dest.writeBytes(out);
this.privKey.writeBytes(out);
this.signingPrivKey.writeBytes(out);
out.flush();
out.close();
}
@Override
public String toString() {
StringBuilder s = new StringBuilder(128);
s.append("Dest: ");
s.append(this.dest != null ? this.dest.toBase64() : "null");
s.append("\nB32: ");
s.append(this.dest != null ? Base32.encode(this.dest.calculateHash().getData()) + ".b32.i2p" : "null");
s.append("\nContains: ");
s.append(this.dest);
s.append("\nPrivate Key: ");
s.append(this.privKey);
s.append("\nSigining Private Key: ");
s.append(this.signingPrivKey);
s.append("\n");
return s.toString();
}
public static String estimateHashCashTime(int hashEffort) {
if (hashEffort <= 0 || hashEffort > 160)
return "Bad HashCash value: " + hashEffort;
long low = Long.MAX_VALUE;
try {
low = HashCash.estimateTime(hashEffort);
} catch (Exception e) {}
// takes a lot longer than the estimate usually...
// maybe because the resource string is much longer than used in the estimate?
return "It is estimated that generating a HashCash Certificate with value " + hashEffort +
" for the Destination will take " +
((low < 1000l * 24l * 60l * 60l * 1000l)
?
"approximately " + DataHelper.formatDuration(low) +
" to " + DataHelper.formatDuration(4*low)
:
"longer than three years!"
);
}
/**
* Sample code to verify a 3rd party signature.
* This just goes through all the hosts.txt files and tries everybody.
* You need to be in the $I2P directory or have a local hosts.txt for this to work.
* Doubt this is what you want as it is super-slow, and what good is
* a signing scheme where anybody is allowed to sign?
*
* In a real application you would make a list of approved signers,
* do a naming lookup to get their Destinations, and try those only.
* Or do a netDb lookup of the Hash in the Certificate, do a reverse
* naming lookup to see if it is allowed, then verify the Signature.
*/
public static boolean verifySignature(Destination d) {
if (d.getCertificate().getCertificateType() != Certificate.CERTIFICATE_TYPE_SIGNED)
return false;
int len = PublicKey.KEYSIZE_BYTES + SigningPublicKey.KEYSIZE_BYTES; // no cert
byte[] data = new byte[len];
System.arraycopy(d.getPublicKey().getData(), 0, data, 0, PublicKey.KEYSIZE_BYTES);
System.arraycopy(d.getSigningPublicKey().getData(), 0, data, PublicKey.KEYSIZE_BYTES, SigningPublicKey.KEYSIZE_BYTES);
Signature sig = new Signature();
byte[] payload = d.getCertificate().getPayload();
Hash signerHash = null;
if (payload == null) {
System.out.println("Bad signed cert - no payload");
return false;
} else if (payload.length == Signature.SIGNATURE_BYTES) {
sig.setData(payload);
} else if (payload.length == Certificate.CERTIFICATE_LENGTH_SIGNED_WITH_HASH) {
byte[] pl = new byte[Signature.SIGNATURE_BYTES];
System.arraycopy(payload, 0, pl, 0, Signature.SIGNATURE_BYTES);
sig.setData(pl);
byte[] hash = new byte[Hash.HASH_LENGTH];
System.arraycopy(payload, Signature.SIGNATURE_BYTES, hash, 0, Hash.HASH_LENGTH);
signerHash = new Hash(hash);
System.out.println("Destination is signed by " + Base32.encode(hash) + ".b32.i2p");
} else {
System.out.println("Bad signed cert - length = " + payload.length);
return false;
}
String[] filenames = new String[] {"privatehosts.txt", "userhosts.txt", "hosts.txt"};
int tried = 0;
for (int i = 0; i < filenames.length; i++) {
Properties hosts = new Properties();
try {
File f = new File(filenames[i]);
if ( (f.exists()) && (f.canRead()) ) {
DataHelper.loadProps(hosts, f, true);
int sz = hosts.size();
if (sz > 0) {
tried += sz;
if (signerHash == null)
System.out.println("Attempting to verify using " + sz + " hosts, this may take a while");
}
for (Iterator iter = hosts.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry)iter.next();
String s = (String) entry.getValue();
Destination signer = new Destination(s);
// make it go faster if we have the signerHash hint
if (signerHash == null || signer.calculateHash().equals(signerHash)) {
if (checkSignature(sig, data, signer.getSigningPublicKey())) {
System.out.println("Good signature from: " + entry.getKey());
return true;
}
if (signerHash != null) {
System.out.println("Bad signature from: " + entry.getKey());
// could probably return false here but keep going anyway
}
}
}
}
} catch (Exception ioe) {
}
// not found, continue to the next file
}
if (tried > 0)
System.out.println("No valid signer found");
else
System.out.println("No addressbooks found to valididate signer");
return false;
}
public static boolean checkSignature(Signature s, byte[] data, SigningPublicKey spk) {
return DSAEngine.getInstance().verifySignature(s, data, spk);
}
private static final int HASH_EFFORT = VerifiedDestination.MIN_HASHCASH_EFFORT;
private File file;
private I2PClient client;
private Destination dest;
private PrivateKey privKey;
private SigningPrivateKey signingPrivKey;
}
|
package com.icarus.project;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader.FreeTypeFontLoaderParameter;
import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGeneratorLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.math.Vector2;
import java.util.ArrayList;
public class ProjectIcarus extends ApplicationAdapter implements GestureDetector.GestureListener {
//Used for drawing waypoints
private ShapeRenderer shapes;
//The currently loaded Airport
private Airport airport;
//The airplanes in the current game
private ArrayList<Airplane> airplanes;
//The font used for labels
private BitmapFont labelFont;
//Used for drawing airplanes
private SpriteBatch batch;
private Utils utils;
private OrthographicCamera camera;
private float currentZoom;
private float maxZoomIn; // Maximum possible zoomed in distance
private float maxZoomOut; // Maximum possible zoomed out distance
private float fontSize = 40;
// Pan boundaries
private float toBoundaryRight;
private float toBoundaryLeft;
private float toBoundaryTop;
private float toBoundaryBottom;
@Override
public void create () {
//initialize the AssetManager
AssetManager manager = new AssetManager();
FileHandleResolver resolver = new InternalFileHandleResolver();
manager.setLoader(Airport.class, new AirportLoader(resolver));
manager.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(resolver));
manager.setLoader(BitmapFont.class, ".ttf", new FreetypeFontLoader(resolver));
//load the airport
manager.load("airports/test.json", Airport.class);
//load the label font
FreeTypeFontLoaderParameter labelFontParams = new FreeTypeFontLoaderParameter();
labelFontParams.fontFileName = "fonts/ShareTechMono-Regular.ttf";
labelFontParams.fontParameters.size = Math.round(20.0f * Gdx.graphics.getDensity());
manager.load("fonts/ShareTechMono-Regular.ttf", BitmapFont.class, labelFontParams);
//load the airplane sprite
manager.load("sprites/airplane.png", Texture.class);
manager.finishLoading();
airport = manager.get("airports/test.json");
labelFont = manager.get("fonts/ShareTechMono-Regular.ttf");
Airplane.texture = manager.get("sprites/airplane.png");
shapes = new ShapeRenderer();
batch = new SpriteBatch();
//add a dummy airplane
airplanes = new ArrayList();
airplanes.add(new Airplane("TEST", new Vector2(10, 10), new Vector2(5, 2), 100));
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.input.setInputProcessor(new GestureDetector(this));
utils = new Utils();
// The maximum zoom level is the smallest dimension compared to the viewer
maxZoomOut = Math.min(airport.width / Gdx.graphics.getWidth(),
airport.height / Gdx.graphics.getHeight());
maxZoomIn = maxZoomOut / 100;
// Start the app in maximum zoomed out state
camera.zoom = maxZoomOut;
camera.position.set(airport.width/2, airport.height/2, 0);
camera.update();
}
private void setToBoundary(){
// Calculates the distance from the edge of the camera to the specified boundary
toBoundaryRight = (airport.width - camera.position.x
- Gdx.graphics.getWidth()/2 * camera.zoom);
toBoundaryLeft = (-camera.position.x + Gdx.graphics.getWidth()/2 * camera.zoom);
toBoundaryTop = (airport.height - camera.position.y
- Gdx.graphics.getHeight()/2 * camera.zoom);
toBoundaryBottom = (-camera.position.y + Gdx.graphics.getHeight()/2 * camera.zoom);
}
@Override
public void render () {
Gdx.gl.glClearColor(Colors.colors[0].r, Colors.colors[0].g, Colors.colors[2].b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
shapes.setProjectionMatrix(camera.combined);
//draw waypoint triangles
shapes.begin(ShapeRenderer.ShapeType.Filled);
for(Waypoint waypoint: airport.waypoints) {
waypoint.draw(shapes);
}
shapes.end();
//draw airplanes
batch.begin();
for(Airplane airplane: airplanes) {
airplane.draw(batch);
}
batch.end();
//draw waypoint labels
batch.begin();
for(Waypoint waypoint: airport.waypoints) {
waypoint.drawLabel(labelFont, batch);
}
batch.end();
}
@Override
public void dispose () {
shapes.dispose();
batch.dispose();
labelFont.dispose();
}
@Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
@Override
public boolean tap(float x, float y, int count, int button) {
return false;
}
@Override
public boolean longPress(float x, float y) {
return false;
}
@Override
public boolean fling(float velocityX, float velocityY, int button) {
return false;
}
@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
setToBoundary(); // Calculate distances to boundaries
float translateX;
float translateY;
if (-deltaX * currentZoom > 0){ // If user pans to the right
translateX = utils.absMin(-deltaX * currentZoom, toBoundaryRight);
}
else { // If user pans to the left
translateX = utils.absMin(-deltaX * currentZoom, toBoundaryLeft);
}
if (deltaY * currentZoom > 0){ // If user pans up
translateY = utils.absMin(deltaY * currentZoom, toBoundaryTop);
}
else { // If user pans down
translateY = utils.absMin(deltaY * currentZoom, toBoundaryBottom);
}
camera.translate(translateX, translateY);
camera.update();
return true;
}
@Override
public boolean panStop(float x, float y, int pointer, int button) {
currentZoom = camera.zoom;
return false;
}
@Override
public boolean zoom(float initialDistance, float distance) {
float tempZoom = camera.zoom;
camera.zoom = Math.max(Math.min((initialDistance / distance) * currentZoom, maxZoomOut),
maxZoomIn);
Waypoint.scaleWaypoint(camera.zoom / tempZoom); // Scale waypoint to retain apparent size
setToBoundary(); // Calculate distances to boundaries
// Shift the view when zooming to keep view within map
if (toBoundaryRight < 0 || toBoundaryTop < 0){
camera.translate(Math.min(0, toBoundaryRight),
Math.min(0, toBoundaryTop));
}
if (toBoundaryLeft > 0 || toBoundaryBottom > 0){
camera.translate(Math.max(0, toBoundaryLeft),
Math.max(0, toBoundaryBottom));
}
camera.update();
return true;
}
@Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1,
Vector2 pointer2) {
return false;
}
@Override
public void pinchStop() {
}
}
|
package com.icarus.project;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader.FreeTypeFontLoaderParameter;
import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGeneratorLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.math.Vector3;
import java.util.ArrayList;
public class ProjectIcarus extends ApplicationAdapter implements GestureDetector.GestureListener {
private Vector2 oldInitialFirstPointer=null, oldInitialSecondPointer=null;
private float oldScale;
//Used for drawing waypoints
private ShapeRenderer shapes;
//The currently loaded Airport
private Airport airport;
//The airplanes in the current game
private ArrayList<Airplane> airplanes;
//The font used for labels
private BitmapFont labelFont;
//Used for drawing airplanes
private SpriteBatch batch;
private Utils utils;
private OrthographicCamera camera;
// private float currentZoom;
private float maxZoomIn; // Maximum possible zoomed in distance
private float maxZoomOut; // Maximum possible zoomed out distance
private float fontSize = 40;
// Pan boundaries
private float toBoundaryRight;
private float toBoundaryLeft;
private float toBoundaryTop;
private float toBoundaryBottom;
@Override
public void create () {
//initialize the AssetManager
AssetManager manager = new AssetManager();
FileHandleResolver resolver = new InternalFileHandleResolver();
manager.setLoader(Airport.class, new AirportLoader(resolver));
manager.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(resolver));
manager.setLoader(BitmapFont.class, ".ttf", new FreetypeFontLoader(resolver));
//load the airport
manager.load("airports/test.json", Airport.class);
//load the label font
FreeTypeFontLoaderParameter labelFontParams = new FreeTypeFontLoaderParameter();
labelFontParams.fontFileName = "fonts/ShareTechMono-Regular.ttf";
labelFontParams.fontParameters.size = Math.round(20.0f * Gdx.graphics.getDensity());
manager.load("fonts/ShareTechMono-Regular.ttf", BitmapFont.class, labelFontParams);
//load the airplane sprite
manager.load("sprites/airplane.png", Texture.class);
manager.finishLoading();
airport = manager.get("airports/test.json");
labelFont = manager.get("fonts/ShareTechMono-Regular.ttf");
Airplane.texture = manager.get("sprites/airplane.png");
shapes = new ShapeRenderer();
batch = new SpriteBatch();
//add a dummy airplane
airplanes = new ArrayList();
airplanes.add(new Airplane("TEST", new Vector2(200, 200), new Vector2(-5, -5), 100));
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.input.setInputProcessor(new GestureDetector(this));
utils = new Utils();
// The maximum zoom level is the smallest dimension compared to the viewer
maxZoomOut = Math.min(airport.width / Gdx.graphics.getWidth(),
airport.height / Gdx.graphics.getHeight());
maxZoomIn = maxZoomOut / 100;
// Start the app in maximum zoomed out state
camera.zoom = maxZoomOut;
camera.position.set(airport.width/2, airport.height/2, 0);
camera.update();
}
private void setToBoundary(){
// Calculates the distance from the edge of the camera to the specified boundary
toBoundaryRight = (airport.width - camera.position.x
- Gdx.graphics.getWidth()/2 * camera.zoom);
toBoundaryLeft = (-camera.position.x + Gdx.graphics.getWidth()/2 * camera.zoom);
toBoundaryTop = (airport.height - camera.position.y
- Gdx.graphics.getHeight()/2 * camera.zoom);
toBoundaryBottom = (-camera.position.y + Gdx.graphics.getHeight()/2 * camera.zoom);
}
@Override
public void render () {
super.render();
Gdx.gl.glClearColor(Colors.colors[0].r, Colors.colors[0].g, Colors.colors[2].b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//batch.setProjectionMatrix(camera.projection);
//shapes.setProjectionMatrix(camera.projection);
//draw waypoint triangles
shapes.begin(ShapeRenderer.ShapeType.Filled);
for(Waypoint waypoint: airport.waypoints) {
waypoint.draw(shapes, camera);
}
shapes.end();
//draw waypoint labels
batch.begin();
for(Waypoint waypoint: airport.waypoints) {
waypoint.drawLabel(labelFont, batch, camera);
}
batch.end();
//draw airplanes
batch.begin();
for(Airplane airplane: airplanes) {
airplane.step(); //Move airplanes
airplane.draw(batch, camera);
}
batch.end();
}
@Override
public void dispose () {
shapes.dispose();
batch.dispose();
labelFont.dispose();
}
@Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
@Override
public boolean tap(float x, float y, int count, int button) {
return false;
}
@Override
public boolean longPress(float x, float y) {
return false;
}
@Override
public boolean fling(float velocityX, float velocityY, int button) {
return false;
}
@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
setToBoundary(); // Calculate distances to boundaries
float translateX;
float translateY;
if (deltaX > 0){ // If user pans to the left
translateX = utils.absMin(deltaX, toBoundaryLeft);
}
else { // If user pans to the right
translateX = utils.absMin(deltaX, toBoundaryRight);
}
if (deltaY > 0){ // If user pans up
translateY = utils.absMin(deltaY, toBoundaryTop);
}
else { // If user pans down
translateY = utils.absMin(deltaY, toBoundaryBottom);
}
//Shift camera by delta or by distance to boundary, whichever is closer
camera.position.add(
camera.unproject(new Vector3(0, 0, 0))
.add(camera.unproject(new Vector3(translateX, translateY, 0)).scl(-1f))
);
camera.update();
return true;
}
@Override
public boolean panStop(float x, float y, int pointer, int button) {
// currentZoom = camera.zoom;
return false;
}
@Override
public boolean zoom(float initialDistance, float distance) {
//waypoints dont change size, boundaries for zoom set, not pan
/*float tempZoom = camera.zoom;
camera.zoom = Math.max(Math.min((initialDistance / distance) * currentZoom, maxZoomOut),
maxZoomIn);
Waypoint.scaleWaypoint(camera.zoom / tempZoom); // Scale waypoint to retain apparent size
setToBoundary(); // Calculate distances to boundaries
// Shift the view when zooming to keep view within map
if (toBoundaryRight < 0 || toBoundaryTop < 0){
camera.translate(Math.min(0, toBoundaryRight),
Math.min(0, toBoundaryTop));
}
if (toBoundaryLeft > 0 || toBoundaryBottom > 0){
camera.translate(Math.max(0, toBoundaryLeft),
Math.max(0, toBoundaryBottom));
}
camera.update();*/
return false;
}
@Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1,
Vector2 pointer2)
{
if (!(initialPointer1.equals(oldInitialFirstPointer)
&& initialPointer2.equals(oldInitialSecondPointer)))
{
oldInitialFirstPointer = initialPointer1.cpy();
oldInitialSecondPointer = initialPointer2.cpy();
oldScale = camera.zoom;
}
Vector3 center = new Vector3(
(pointer1.x + initialPointer2.x) / 2,
(pointer2.y + initialPointer1.y) / 2,
0
);
zoomCamera(center,
oldScale * initialPointer1.dst(initialPointer2) / pointer1.dst(pointer2));
return true;
}
@Override
public void pinchStop() {
}
private void zoomCamera(Vector3 origin, float scale) {
float tempZoom = camera.zoom;
Vector3 oldUnprojection = camera.unproject(origin.cpy()).cpy();
camera.zoom = scale; //Larger value of zoom = small images, border view
camera.zoom = Math.min(maxZoomOut, Math.max(camera.zoom, maxZoomIn));
camera.update();
Vector3 newUnprojection = camera.unproject(origin.cpy()).cpy();
camera.position.add(oldUnprojection.cpy().add(newUnprojection.cpy().scl(-1f)));
setToBoundary(); //Calculate distances to boundaries
//Shift the view when zooming to keep view within map
if (toBoundaryRight < 0 || toBoundaryTop < 0){
camera.position.add(
camera.unproject(new Vector3(0, 0, 0))
.add(camera.unproject(new Vector3(Math.max(0, -toBoundaryRight),
Math.min(0, toBoundaryTop),
0)).scl(-1f))
);
}
if (toBoundaryLeft > 0 || toBoundaryBottom > 0){
camera.position.add(
camera.unproject(new Vector3(0, 0, 0))
.add(camera.unproject(new Vector3(Math.min(0, -toBoundaryLeft),
Math.max(0, toBoundaryBottom),
0)).scl(-1f))
);
}
camera.update();
}
}
|
package org.egordorichev.lasttry;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import org.egordorichev.lasttry.core.Version;
import org.egordorichev.lasttry.core.Crash;
import org.egordorichev.lasttry.graphics.*;
import org.egordorichev.lasttry.input.InputManager;
import org.egordorichev.lasttry.state.SplashState;
import org.egordorichev.lasttry.ui.UiManager;
import org.egordorichev.lasttry.util.Camera;
import org.egordorichev.lasttry.util.Debug;
import org.egordorichev.lasttry.language.Language;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.Locale;
/**
* Main game class
*/
public class LastTry extends Game {
/**
* LastTry version
*/
public static final Version version = new Version(0.0, 18, "alpha");
/**
* Random instance. This is not to be used in repeatable systems such as
* world generation
*/
public static final Random random = new Random();
/**
* Last Try instance
*/
public static LastTry instance;
/**
* Ui manager
*/
public static UiManager ui;
/**
* Debug helper
*/
public static Debug debug;
/**
* Shows, if this is a release
*/
public static boolean release = true;
/**
* Light disable
*/
public static boolean noLight = false;
/**
* Store relative to the game jar, instead of in the home directory.
*/
public static boolean storeRelative = true;
/**
* Intensity affects how sharp lighting gradients are.
*/
public static float gammaStrength = 1.0f;
/**
* The minimum brightness that can be made by lighting.
*/
public static float gammaMinimum = 0f;
public static String defaultWorldName = "test";
public static String defaultPlayerName = "test";
/**
* Screen dimensions
*/
public final int width;
private final int height;
public LastTry(int width, int height) {
this.width = width;
this.height = height;
}
/**
* Creates first-priority instances
*/
@Override
public void create() {
Thread.currentThread().setUncaughtExceptionHandler(Crash::report);
Globals.resolution = new Vector2(width, height);
instance = this;
Gdx.graphics.setCursor(Gdx.graphics.newCursor(new Pixmap(Gdx.files.internal("cursor.png")), 0, 0));
Camera.create(width, height);
Language.load(new Locale("en", "US"));
Gdx.input.setInputProcessor(InputManager.multiplexer);
Gdx.graphics.setTitle(this.getRandomWindowTitle());
Graphics.batch = new SpriteBatch();
debug = new Debug();
ui = new UiManager();
this.setScreen(new SplashState());
}
/**
* Handles window resize
*
* @param width new window width
* @param height new window height
*/
@Override
public void resize(int width, int height) {
super.resize(width, height);
Camera.resize(width, height);
Globals.resolution.x = width;
Globals.resolution.y = height;
}
/**
* Renders and updates the game
*/
@Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0, 0, 0, 1);
Graphics.batch.enableBlending();
Graphics.batch.begin();
super.render();
Graphics.batch.end();
}
/**
* Handles game exit
*/
@Override
public void dispose() {
Globals.dispose();
Assets.dispose();
}
/**
* Returns random title for game the window
*
* @return random title for game the window
*/
private String getRandomWindowTitle() {
String date = new SimpleDateFormat("MMdd").format(new Date());
if (date.equals("0629") || date.equals("0610")) {
return "Happy Birthday!" + " " + version.toString();
}
String[] split = Language.text.get("windowTitles").split("
return split[random.nextInt(split.length)] + " " + version.toString();
}
/**
* Returns mouse X coordinate, under the world
*
* @return mouse X coordinate, under the world
*/
public static int getMouseXInWorld() {
return (int) (Globals.getPlayer().physics.getCenterX() - Gdx.graphics.getWidth() / 2
+ InputManager.getMousePosition().x);
}
/**
* Returns mouse Y coordinate, under the world
*
* @return mouse Y coordinate, under the world
*/
public static int getMouseYInWorld() {
return (int) (Globals.getPlayer().physics.getCenterY() + Gdx.graphics.getHeight() / 2
- InputManager.getMousePosition().y);
}
/**
* Handles exception, if it is critical, exits the game
*
* @param exception exception to handle
*/
public static void handleException(Exception exception) {
Crash.report(Thread.currentThread(), exception);
}
/**
* Aborts the process
*/
public static void abort() {
System.exit(1);
}
}
|
package net.tomp2p.p2p;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import net.tomp2p.Utils2;
import net.tomp2p.connection2.Bindings;
import net.tomp2p.connection2.ChannelCreator;
import net.tomp2p.connection2.PeerConnection;
import net.tomp2p.futures.BaseFuture;
import net.tomp2p.futures.BaseFutureAdapter;
import net.tomp2p.futures.BaseFutureImpl;
import net.tomp2p.futures.FutureBootstrap;
import net.tomp2p.futures.FutureChannelCreator;
import net.tomp2p.futures.FutureDirect;
import net.tomp2p.futures.FutureDiscover;
import net.tomp2p.futures.FutureGet;
import net.tomp2p.futures.FuturePeerConnection;
import net.tomp2p.futures.FuturePut;
import net.tomp2p.futures.FutureRemove;
import net.tomp2p.futures.FutureResponse;
import net.tomp2p.futures.FutureShutdown;
import net.tomp2p.futures.FutureSuccessEvaluatorOperation;
import net.tomp2p.message.Buffer;
import net.tomp2p.p2p.builder.DHTBuilder;
import net.tomp2p.p2p.builder.PutBuilder;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.Number320;
import net.tomp2p.peers.Number480;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.peers.PeerMap;
import net.tomp2p.rpc.ObjectDataReply;
import net.tomp2p.rpc.RawDataReply;
import net.tomp2p.rpc.StorageRPC;
import net.tomp2p.storage.Data;
import net.tomp2p.storage.HashData;
import net.tomp2p.utils.Timings;
import net.tomp2p.utils.Utils;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestDHT {
final private static Random rnd = new Random(42L);
private static final Logger LOG = LoggerFactory.getLogger(TestDHT.class);
@Test
public void testPutPerforomance() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(2000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
for(int i=0;i<500;i++) {
long start = System.currentTimeMillis();
FuturePut fp = peers[444].put(Number160.createHash("1")).setData(new Data("test")).start();
fp.awaitUninterruptibly();
fp.getFutureRequests().awaitUninterruptibly();
for(FutureResponse fr:fp.getFutureRequests().getCompleted()) {
LOG.error(fr+ " / "+fr.getRequest());
}
long stop = System.currentTimeMillis();
System.err.println("Test " + fp.getFailedReason()+ " / " +(stop-start)+ "ms");
Assert.assertEquals(true, fp.isSuccess());
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPut() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(2000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fp = peers[444].put(peers[30].getPeerID())
.setData(Number160.createHash("test"),new Number160(5) , data).setRequestP2PConfiguration(pc)
.setRoutingConfiguration(rc).start();
fp.awaitUninterruptibly();
fp.getFutureRequests().awaitUninterruptibly();
System.err.println("Test " + fp.getFailedReason());
Assert.assertEquals(true, fp.isSuccess());
peers[30].getPeerBean()
.peerMap();
// search top 3
TreeMap<PeerAddress, Integer> tmp = new TreeMap<PeerAddress, Integer>(PeerMap.createComparator(peers[30].getPeerID()));
int i = 0;
for (Peer node : peers) {
tmp.put(node.getPeerAddress(), i);
i++;
}
Entry<PeerAddress, Integer> e = tmp.pollFirstEntry();
System.err.println("1 (" + e.getValue() + ")" + e.getKey());
Assert.assertEquals(peers[e.getValue()].getPeerAddress(), peers[30].getPeerAddress());
testForArray(peers[e.getValue()], peers[30].getPeerID(), true);
e = tmp.pollFirstEntry();
System.err.println("2 (" + e.getValue() + ")" + e.getKey());
testForArray(peers[e.getValue()], peers[30].getPeerID(), true);
e = tmp.pollFirstEntry();
System.err.println("3 " + e.getKey());
testForArray(peers[e.getValue()], peers[30].getPeerID(), true);
e = tmp.pollFirstEntry();
System.err.println("4 " + e.getKey());
testForArray(peers[e.getValue()], peers[30].getPeerID(), false);
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetAlone() throws Exception {
Peer master = null;
try {
master = new PeerMaker(new Number160(rnd)).ports(4001).makeAndListen();
FuturePut fdht = master.put(Number160.ONE).setData(new Data("hallo")).start();
fdht.awaitUninterruptibly();
fdht.getFutureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fdht.isSuccess());
FutureGet fdht2 = master.get(Number160.ONE).start();
fdht2.awaitUninterruptibly();
System.err.println(fdht2.getFailedReason());
Assert.assertEquals(true, fdht2.isSuccess());
Data tmp = fdht2.getData();
Assert.assertEquals("hallo", tmp.object().toString());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPut2() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(500, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(0, 0, 1);
RequestP2PConfiguration pc = new RequestP2PConfiguration(1, 0, 0);
FuturePut fdht = peers[444].put(peers[30].getPeerID()).setData(new Number160(5), data)
.setDomainKey(Number160.createHash("test")).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fdht.awaitUninterruptibly();
fdht.getFutureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fdht.isSuccess());
peers[30].getPeerBean()
.peerMap();
// search top 3
TreeMap<PeerAddress, Integer> tmp = new TreeMap<PeerAddress, Integer>(
PeerMap.createComparator(peers[30].getPeerID()));
int i = 0;
for (Peer node : peers) {
tmp.put(node.getPeerAddress(), i);
i++;
}
Entry<PeerAddress, Integer> e = tmp.pollFirstEntry();
Assert.assertEquals(peers[e.getValue()].getPeerAddress(), peers[30].getPeerAddress());
testForArray(peers[e.getValue()], peers[30].getPeerID(), true);
e = tmp.pollFirstEntry();
testForArray(peers[e.getValue()], peers[30].getPeerID(), false);
e = tmp.pollFirstEntry();
testForArray(peers[e.getValue()], peers[30].getPeerID(), false);
e = tmp.pollFirstEntry();
testForArray(peers[e.getValue()], peers[30].getPeerID(), false);
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGet() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(2000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
Data data = new Data(new byte[44444]);
FuturePut fput = peers[444].put(peers[30].getPeerID()).setData(new Number160(5), data)
.setDomainKey(Number160.createHash("test")).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.getFutureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(0, 0, 10, 1);
pc = new RequestP2PConfiguration(1, 0, 0);
FutureGet fget = peers[555].get(peers[30].getPeerID()).setDomainKey(Number160.createHash("test"))
.setContentKey(new Number160(5)).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.getRawData().size());
Assert.assertEquals(true, fget.isMinReached());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGet2() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(1000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
Data data = new Data(new byte[44444]);
FuturePut fput = peers[444].put(peers[30].getPeerID()).setData(new Number160(5), data)
.setDomainKey(Number160.createHash("test")).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.getFutureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(4, 0, 10, 1);
pc = new RequestP2PConfiguration(4, 0, 0);
FutureGet fget = peers[555].get(peers[30].getPeerID()).setDomainKey(Number160.createHash("test"))
.setContentKey(new Number160(5)).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(3, fget.getRawData().size());
Assert.assertEquals(false, fget.isMinReached());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGet3() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(2000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = peers[444].put(peers[30].getPeerID()).setData(new Number160(5), data)
.setDomainKey(Number160.createHash("test")).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.getFutureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(1, 0, 10, 1);
pc = new RequestP2PConfiguration(1, 0, 0);
for (int i = 0; i < 1000; i++) {
FutureGet fget = peers[100 + i].get(peers[30].getPeerID()).setDomainKey(Number160.createHash("test"))
.setContentKey(new Number160(5)).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.getRawData().size());
Assert.assertEquals(true, fget.isMinReached());
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetRemove() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(2000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = peers[444].put(peers[30].getPeerID()).setDomainKey(Number160.createHash("test"))
.setData(new Number160(5), data).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.getFutureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(4, 0, 10, 1);
pc = new RequestP2PConfiguration(4, 0, 0);
FutureRemove frem = peers[222].remove(peers[30].getPeerID()).setDomainKey(Number160.createHash("test"))
.setContentKey(new Number160(5)).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
Assert.assertEquals(3, frem.getRawKeys().size());
FutureGet fget = peers[555].get(peers[30].getPeerID()).setDomainKey(Number160.createHash("test"))
.setContentKey(new Number160(5)).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(false, fget.isSuccess());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetRemove2() throws Exception {
Peer master = null;
try {
// rnd.setSeed(253406013991563L);
// setup
Peer[] peers = Utils2.createNodes(2000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = peers[444].put(peers[30].getPeerID()).setData(new Number160(5), data)
.setDomainKey(Number160.createHash("test")).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.getFutureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
System.err.println("remove");
rc = new RoutingConfiguration(4, 0, 10, 1);
pc = new RequestP2PConfiguration(4, 0, 0);
FutureRemove frem = peers[222].remove(peers[30].getPeerID()).setReturnResults()
.setDomainKey(Number160.createHash("test")).setContentKey(new Number160(5))
.setRoutingConfiguration(rc).setRequestP2PConfiguration(pc).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
Assert.assertEquals(3, frem.getRawData().size());
System.err.println("get");
rc = new RoutingConfiguration(4, 0, 0, 1);
pc = new RequestP2PConfiguration(4, 0, 0);
FutureGet fget = peers[555].get(peers[30].getPeerID()).setDomainKey(Number160.createHash("test"))
.setContentKey(new Number160(5)).setRoutingConfiguration(rc)
.setRequestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(false, fget.isSuccess());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDirect() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(1000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
final AtomicInteger ai = new AtomicInteger(0);
for (int i = 0; i < peers.length; i++) {
peers[i].setObjectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
ai.incrementAndGet();
return "ja";
}
});
}
// do testing
FutureDirect fdir = peers[400].send(new Number160(rnd)).setObject("hallo").start();
fdir.awaitUninterruptibly();
System.err.println(fdir.getFailedReason());
Assert.assertEquals(true, fdir.isSuccess());
Assert.assertEquals(true, ai.get() >= 3 && ai.get() <= 6);
System.err.println("called: "+ai.get());
Assert.assertEquals("ja", fdir.getObject());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testAddListGet() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(200, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo1";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
FuturePut fput = peers[30].add(nr).setData(data1).setList(true).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).setData(data2).setList(true).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).setAll().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
// majority voting with getDataMap is not possible since we create
// random content key on the recipient
Assert.assertEquals(2, fget.getRawData().values().iterator().next().values().size());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testAddGet() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(200, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
FuturePut fput = peers[30].add(nr).setData(data1).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).setData(data2).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).setAll().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDigest() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(200, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
String toStore3 = "hallo3";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
Data data3 = new Data(toStore3.getBytes());
FuturePut fput = peers[30].add(nr).setData(data1).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).setData(data2).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
fput = peers[51].add(nr).setData(data3).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore3 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).setAll().setDigest().start();
fget.awaitUninterruptibly();
System.err.println(fget.getFailedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(3, fget.getDigest().getKeyDigest().size());
Number160 test = new Number160("0x37bb570100c9f5445b534757ebc613a32df3836d");
Set<Number160> test2 = new HashSet<Number160>();
test2.add(test);
fget = peers[67].get(nr).setDigest().setContentKeys(test2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.getDigest().getKeyDigest().size());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testData() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(200, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
ByteBuf c = Unpooled.buffer();
c.writeInt(77);
Buffer b = new Buffer(c);
peers[50].setRawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) {
System.err.println(requestBuffer.buffer().readInt());
ByteBuf c = Unpooled.buffer();
c.writeInt(88);
Buffer ret = new Buffer(c);
return ret;
}
});
FutureResponse fd = master.sendDirect(peers[50].getPeerAddress()).setBuffer(b).start();
fd.await();
if (fd.getResponse().getBuffer(0) == null) {
System.err.println("damm");
Assert.fail();
}
int read = fd.getResponse().getBuffer(0).buffer().readInt();
Assert.assertEquals(88, read);
System.err.println("done");
// for(FutureBootstrap fb:tmp)
// fb.awaitUninterruptibly();
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testData2() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(200, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
ByteBuf c = Unpooled.buffer();
c.writeInt(77);
Buffer b = new Buffer(c);
peers[50].setRawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) {
System.err.println("got it");
return requestBuffer;
}
});
FutureResponse fd = master.sendDirect(peers[50].getPeerAddress()).setBuffer(b).start();
fd.await();
System.err.println("done1");
Assert.assertEquals(true, fd.isSuccess());
Assert.assertNull(fd.getResponse().getBuffer(0));
// int read = fd.getBuffer().readInt();
// Assert.assertEquals(88, read);
System.err.println("done2");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testObjectLoop() throws Exception {
for (int i = 0; i < 1000; i++) {
System.err.println("nr: " + i);
testObject();
}
}
@Test
public void testObject() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(100, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
Data data1 = new Data(toStore1);
Data data2 = new Data(toStore2);
System.err.println("begin add : ");
FuturePut fput = peers[30].add(nr).setData(data1).start();
fput.awaitUninterruptibly();
System.err.println("stop added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).setData(data2).start();
fput.awaitUninterruptibly();
fput.getFutureRequests().awaitUninterruptibly();
System.err.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).setAll().start();
fget.awaitUninterruptibly();
fget.getFutureRequests().awaitUninterruptibly();
if (!fget.isSuccess())
System.err.println(fget.getFailedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(2, fget.getDataMap().size());
System.err.println("got it");
} finally {
if (master != null) {
master.shutdown().awaitListenersUninterruptibly();
}
}
}
@Test
public void testAddGetPermits() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(2000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
List<FuturePut> list = new ArrayList<FuturePut>();
for (int i = 0; i < peers.length; i++) {
String toStore1 = "hallo" + i;
Data data1 = new Data(toStore1.getBytes());
FuturePut fput = peers[i].add(nr).setData(data1).start();
list.add(fput);
}
for (FuturePut futureDHT : list) {
futureDHT.awaitUninterruptibly();
Assert.assertEquals(true, futureDHT.isSuccess());
}
System.err.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testhalt() throws Exception {
Peer master1 = null;
Peer master2 = null;
Peer master3 = null;
try {
master1 = new PeerMaker(new Number160(rnd)).p2pId(1).ports(4001)
.makeAndListen();
master2 = new PeerMaker(new Number160(rnd)).p2pId(1).ports(4002)
.makeAndListen();
master3 = new PeerMaker(new Number160(rnd)).p2pId(1).ports(4003)
.makeAndListen();
// perfect routing
master1.getPeerBean().peerMap().peerFound(master2.getPeerAddress(), null);
master1.getPeerBean().peerMap().peerFound(master3.getPeerAddress(), null);
master2.getPeerBean().peerMap().peerFound(master1.getPeerAddress(), null);
master2.getPeerBean().peerMap().peerFound(master3.getPeerAddress(), null);
master3.getPeerBean().peerMap().peerFound(master1.getPeerAddress(), null);
master3.getPeerBean().peerMap().peerFound(master2.getPeerAddress(), null);
Number160 id = master2.getPeerID();
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = master1.put(id).setData(new Number160(5), data)
.setDomainKey(Number160.createHash("test")).setRequestP2PConfiguration(pc)
.setRoutingConfiguration(rc).start();
fput.awaitUninterruptibly();
fput.getFutureRequests().awaitUninterruptibly();
//Collection<Number160> tmp = new ArrayList<Number160>();
//tmp.add(new Number160(5));
Assert.assertEquals(true, fput.isSuccess());
// search top 3
master2.shutdown().await();
FutureGet fget = master1.get(id).setRoutingConfiguration(rc).setRequestP2PConfiguration(pc)
.setDomainKey(Number160.createHash("test")).setContentKey(new Number160(5))
.start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
master1.getPeerBean().peerMap().peerFailed(master2.getPeerAddress(), true);
master3.getPeerBean().peerMap().peerFailed(master2.getPeerAddress(), true);
master2 = new PeerMaker(new Number160(rnd)).p2pId(1).ports(4002)
.makeAndListen();
master1.getPeerBean().peerMap().peerFound(master2.getPeerAddress(), null);
master3.getPeerBean().peerMap().peerFound(master2.getPeerAddress(), null);
master2.getPeerBean().peerMap().peerFound(master1.getPeerAddress(), null);
master2.getPeerBean().peerMap().peerFound(master3.getPeerAddress(), null);
System.err.println("no more exceptions here!!");
fget = master1.get(id).setRoutingConfiguration(rc).setRequestP2PConfiguration(pc)
.setDomainKey(Number160.createHash("test")).setContentKey(new Number160(5))
.start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
} finally {
if (master1 != null) {
master1.shutdown().await();
}
if (master2 != null) {
master2.shutdown().await();
}
if (master3 != null) {
master3.shutdown().await();
}
}
}
@Test
public void testObjectSendExample() throws Exception {
Peer p1 = null;
Peer p2 = null;
try {
p1 = new PeerMaker(new Number160(rnd)).ports(4001).makeAndListen();
p2 = new PeerMaker(new Number160(rnd)).ports(4002).makeAndListen();
// attach reply handler
p2.setObjectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
System.out.println("request [" + request + "]");
return "world";
}
});
FutureResponse futureData = p1.sendDirect(p2.getPeerAddress()).setObject("hello").start();
futureData.awaitUninterruptibly();
System.out.println("reply [" + futureData.getResponse().getBuffer(0).object() + "]");
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testObjectSend() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(500, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
for (int i = 0; i < peers.length; i++) {
System.err.println("node " + i);
peers[i].setObjectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
return request;
}
});
peers[i].setRawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete)
throws Exception {
return requestBuffer;
}
});
}
// do testing
System.err.println("round start");
Random rnd = new Random(42L);
byte[] toStore1 = new byte[10 * 1024];
for (int j = 0; j < 5; j++) {
System.err.println("round " + j);
for (int i = 0; i < peers.length - 1; i++) {
send1(peers[rnd.nextInt(peers.length)], peers[rnd.nextInt(peers.length)], toStore1, 100);
send2(peers[rnd.nextInt(peers.length)], peers[rnd.nextInt(peers.length)],
Unpooled.wrappedBuffer(toStore1), 100);
System.err.println("round1 " + i);
}
}
System.err.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testKeys() throws Exception {
final Random rnd = new Random(42L);
Peer p1 = null;
Peer p2 = null;
try {
Number160 n1 = new Number160(rnd);
Data d1 = new Data("hello");
Data d2 = new Data("world!");
// setup (step 1)
p1 = new PeerMaker(new Number160(rnd)).ports(4001).makeAndListen();
FuturePut fput = p1.add(n1).setData(d1).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
p2 = new PeerMaker(new Number160(rnd)).ports(4002).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
// test (step 2)
fput = p1.add(n1).setData(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
FutureGet fget = p2.get(n1).setAll().start();
fget.awaitUninterruptibly();
Assert.assertEquals(2, fget.getDataMap().size());
// test (step 3)
FutureRemove frem = p1.remove(n1).setContentKey(d2.hash()).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
fget = p2.get(n1).setAll().start();
fget.awaitUninterruptibly();
Assert.assertEquals(1, fget.getDataMap().size());
// test (step 4)
fput = p1.add(n1).setData(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
fget = p2.get(n1).setAll().start();
fget.awaitUninterruptibly();
Assert.assertEquals(2, fget.getDataMap().size());
// test (remove all)
frem = p1.remove(n1).setContentKey(d1.hash()).start();
frem.awaitUninterruptibly();
frem = p1.remove(n1).setContentKey(d2.hash()).start();
frem.awaitUninterruptibly();
fget = p2.get(n1).setAll().start();
fget.awaitUninterruptibly();
Assert.assertEquals(0, fget.getDataMap().size());
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testKeys2() throws Exception {
final Random rnd = new Random(42L);
Peer p1 = null;
Peer p2 = null;
try {
Number160 n1 = new Number160(rnd);
Number160 n2 = new Number160(rnd);
Data d1 = new Data("hello");
Data d2 = new Data("world!");
// setup (step 1)
p1 = new PeerMaker(new Number160(rnd)).ports(4001).makeAndListen();
FuturePut fput = p1.put(n1).setData(d1).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
p2 = new PeerMaker(new Number160(rnd)).ports(4002).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
// test (step 2)
fput = p1.put(n2).setData(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
FutureGet fget = p2.get(n2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(1, fget.getDataMap().size());
// test (step 3)
FutureRemove frem = p1.remove(n2).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
fget = p2.get(n2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(0, fget.getDataMap().size());
// test (step 4)
fput = p1.put(n2).setData(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
fget = p2.get(n2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(1, fget.getDataMap().size());
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testPutGetAll() throws Exception {
final AtomicBoolean running = new AtomicBoolean(true);
Peer master = null;
try {
// setup
final Peer[] peers = Utils2.createNodes(100, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
final Number160 key = Number160.createHash("test");
final Data data1 = new Data("test1");
data1.ttlSeconds(3);
final Data data2 = new Data("test2");
data2.ttlSeconds(3);
// add every second a two values
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (running.get()) {
peers[10].add(key).setData(data1).start().awaitUninterruptibly();
peers[10].add(key).setData(data2).start().awaitUninterruptibly();
Timings.sleepUninterruptibly(1000);
}
}
});
t.start();
// wait until the first data is stored.
Timings.sleep(1000);
for (int i = 0; i < 30; i++) {
FutureGet fget = peers[20 + i].get(key).setAll().start();
fget.awaitUninterruptibly();
Assert.assertEquals(2, fget.getDataMap().size());
Timings.sleep(1000);
}
} finally {
running.set(false);
if (master != null) {
master.shutdown().await();
}
}
}
/**
* This will probably fail on your machine since you have to have eth0 configured. This testcase is suited for
* running on the tomp2p.net server
*
* @throws Exception
*/
@Test
public void testBindings() throws Exception {
final Random rnd = new Random(42L);
Peer p1 = null;
Peer p2 = null;
try {
// setup (step 1)
Bindings b = new Bindings();
b.addInterface("eth0");
p1 = new PeerMaker(new Number160(rnd)).ports(4001).bindings(b).makeAndListen();
p2 = new PeerMaker(new Number160(rnd)).ports(4002).bindings(b).makeAndListen();
FutureBootstrap fb = p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start();
fb.awaitUninterruptibly();
Assert.assertEquals(true, fb.isSuccess());
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
//TODO: make this work
@Test
public void testBroadcast() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(1000, rnd, 4001);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
master.broadcast(Number160.createHash("blub")).start();
DefaultBroadcastHandler d = (DefaultBroadcastHandler) master.getBroadcastRPC()
.broadcastHandler();
int counter = 0;
while (d.getBroadcastCounter() < 900) {
Thread.sleep(200);
counter++;
if (counter > 100) {
System.err.println("did not broadcast to 1000 peers, but to " + d.getBroadcastCounter());
Assert.fail("did not broadcast to 1000 peers, but to " + d.getBroadcastCounter());
}
}
System.err.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
/**
* Test the quit messages if they set a peer as offline.
*
* @throws Exception .
*/
@Test
public void testQuit() throws Exception {
Peer master = null;
try {
// setup
final int nrPeers = 200;
final int port = 4001;
Peer[] peers = Utils2.createNodes(nrPeers, rnd, port);
master = peers[0];
Utils2.perfectRouting(peers);
// do testing
final int peerTest = 10;
System.err.println("counter: " + countOnline(peers, peers[peerTest].getPeerAddress()));
FutureShutdown futureShutdown = peers[peerTest].announceShutdown().start();
futureShutdown.awaitUninterruptibly();
// we need to wait a bit, since the quit RPC is a fire and forget and we return immediately
Thread.sleep(2000);
int counter = countOnline(peers, peers[peerTest].getPeerAddress());
System.err.println("counter: " + counter);
Assert.assertEquals(180, nrPeers - 20);
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
//TODO: make this work
@Test
public void testTooManyOpenFilesInSystem() throws Exception {
Peer master = null;
Peer slave = null;
try {
// since we have two peers, we need to reduce the connections -> we
// will have 300 * 2 (peer connection)
// plus 100 * 2 * 2. The last multiplication is due to discover,
// where the recipient creates a connection
// with its own limit. Since the limit is 1024 and we stop at 1000
// only for the connection, we may run into
// too many open files
PeerMaker masterMaker = new PeerMaker(new Number160(rnd)).ports(4001);
master = masterMaker.makeAndListen();
PeerMaker slaveMaker = new PeerMaker(new Number160(rnd)).ports(4002);
slave = slaveMaker.makeAndListen();
System.err.println("peers up and running");
slave.setRawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean last) throws Exception {
final byte[] b1 = new byte[10000];
int i = requestBuffer.buffer().getInt(0);
ByteBuf buf = Unpooled.wrappedBuffer(b1);
buf.setInt(0, i);
return new Buffer(buf);
}
});
List<BaseFuture> list1 = new ArrayList<BaseFuture>();
List<BaseFuture> list2 = new ArrayList<BaseFuture>();
List<FuturePeerConnection> list3 = new ArrayList<FuturePeerConnection>();
for (int i = 0; i < 250; i++) {
final byte[] b = new byte[10000];
FuturePeerConnection pc = master.createPeerConnection(slave.getPeerAddress());
list1.add(master.sendDirect(pc).setBuffer(new Buffer(Unpooled.wrappedBuffer(b))).start());
list3.add(pc);
// pc.close();
}
for (int i = 0; i < 20000; i++) {
list2.add(master.discover().setPeerAddress(slave.getPeerAddress()).start());
final byte[] b = new byte[10000];
byte[] me = Utils.intToByteArray(i);
System.arraycopy(me, 0, b, 0, 4);
list2.add(master.sendDirect(slave.getPeerAddress())
.setBuffer(new Buffer(Unpooled.wrappedBuffer(b))).start());
}
for (BaseFuture bf : list1) {
bf.awaitListenersUninterruptibly();
if (bf.isFailed()) {
System.err.println("WTF " + bf.getFailedReason());
} else {
System.err.print(".");
}
Assert.assertEquals(true, bf.isSuccess());
}
for (FuturePeerConnection pc : list3) {
pc.close().awaitListenersUninterruptibly();
}
for (BaseFuture bf : list2) {
bf.awaitListenersUninterruptibly();
if (bf.isFailed()) {
System.err.println("WTF " + bf.getFailedReason());
} else {
System.err.print(".");
}
Assert.assertEquals(true, bf.isSuccess());
}
System.err.println("done!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.err.println("done!1!");
if (master != null) {
master.shutdown().await();
}
if (slave != null) {
slave.shutdown().await();
}
}
}
/*@Test
public void testActiveReplicationRefresh() throws Exception {
Peer master = null;
try {
// setup
Peer[] peers = Utils2.createNodes(100, rnd, 4001, 5 * 1000, true);
master = peers[0];
Number160 locationKey = master.getPeerID().xor(new Number160(77));
// store
Data data = new Data("Test");
FutureDHT futureDHT = master.put(locationKey).setData(data).start();
futureDHT.awaitUninterruptibly();
futureDHT.getFutureRequests().awaitUninterruptibly();
Assert.assertEquals(true, futureDHT.isSuccess());
// bootstrap
List<FutureBootstrap> tmp2 = new ArrayList<FutureBootstrap>();
for (int i = 0; i < peers.length; i++) {
if (peers[i] != master) {
tmp2.add(peers[i].bootstrap().setPeerAddress(master.getPeerAddress()).start());
}
}
for (FutureBootstrap fm : tmp2) {
fm.awaitUninterruptibly();
Assert.assertEquals(true, fm.isSuccess());
}
for (int i = 0; i < peers.length; i++) {
for (BaseFuture baseFuture : peers[i].getPendingFutures().keySet())
baseFuture.awaitUninterruptibly();
}
// wait for refresh
Thread.sleep(6000);
//
TreeSet<PeerAddress> tmp = new TreeSet<PeerAddress>(master.getPeerBean().getPeerMap()
.createPeerComparator(locationKey));
tmp.add(master.getPeerAddress());
for (int i = 0; i < peers.length; i++)
tmp.add(peers[i].getPeerAddress());
int i = 0;
for (PeerAddress closest : tmp) {
final FutureChannelCreator fcc = master.getConnectionBean().getConnectionReservation()
.reserve(1);
fcc.awaitUninterruptibly();
ChannelCreator cc = fcc.getChannelCreator();
FutureResponse futureResponse = master.getStoreRPC().get(closest, locationKey,
DHTBuilder.DEFAULT_DOMAIN, null, null, null, false, false, false, false, cc, false);
futureResponse.awaitUninterruptibly();
master.getConnectionBean().getConnectionReservation().release(cc);
Assert.assertEquals(true, futureResponse.isSuccess());
Assert.assertEquals(1, futureResponse.getResponse().getDataMap().size());
i++;
if (i >= 5)
break;
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}*/
private static int countOnline(Peer[] peers, PeerAddress peerAddress) {
int counter = 0;
for (Peer peer : peers) {
if (peer.getPeerBean().peerMap().contains(peerAddress)) {
counter++;
}
}
return counter;
}
private void setData(Peer peer, String location, String domain, String content, Data data)
throws IOException {
final Number160 locationKey = Number160.createHash(location);
final Number160 domainKey = Number160.createHash(domain);
final Number160 contentKey = Number160.createHash(content);
peer.getPeerBean().storage().put(locationKey, domainKey, contentKey, data, null, false, false);
}
private void send2(final Peer p1, final Peer p2, final ByteBuf toStore1, final int count)
throws IOException {
if (count == 0) {
System.err.println("failed miserably");
return;
}
Buffer b = new Buffer(toStore1);
FutureResponse fd = p1.sendDirect(p2.getPeerAddress()).setBuffer(b).start();
fd.addListener(new BaseFutureAdapter<FutureResponse>() {
@Override
public void operationComplete(FutureResponse future) throws Exception {
if (future.isFailed()) {
// System.err.println(future.getFailedReason());
send2(p1, p2, toStore1, count - 1);
}
}
});
}
private void send1(final Peer p1, final Peer p2, final byte[] toStore1, final int count)
throws IOException {
if (count == 0) {
System.err.println("failed miserably");
return;
}
FutureResponse fd = p1.sendDirect(p2.getPeerAddress()).setObject(toStore1).start();
fd.addListener(new BaseFutureAdapter<FutureResponse>() {
@Override
public void operationComplete(FutureResponse future) throws Exception {
if (future.isFailed()) {
// System.err.println(future.getFailedReason());
send1(p1, p2, toStore1, count - 1);
}
}
});
}
private void testForArray(Peer peer, Number160 locationKey, boolean find) {
Collection<Number160> tmp = new ArrayList<Number160>();
tmp.add(new Number160(5));
Map<Number480, Data> test = peer.getPeerBean().storage()
.subMap(locationKey, Number160.createHash("test"), Number160.ZERO, Number160.MAX_VALUE);
if (find) {
Assert.assertEquals(1, test.size());
Assert.assertEquals(
44444,
test.get(
new Number480(new Number320(locationKey, Number160.createHash("test")),
new Number160(5))).length());
} else
Assert.assertEquals(0, test.size());
}
private Peer[] createNodes(Peer master, int nr, Random rnd) throws Exception {
Peer[] peers = new Peer[nr];
for (int i = 0; i < nr; i++) {
peers[i] = new PeerMaker(new Number160(rnd)).p2pId(1).masterPeer(master).makeAndListen();
}
return peers;
}
private Peer[] createNodes(Peer master, int nr) throws Exception {
return createNodes(master, nr, rnd);
}
}
|
package ed.lang.ruby;
import org.jruby.runtime.builtin.IRubyObject;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import ed.js.*;
import ed.js.engine.Scope;
@Test(groups = {"ruby", "ruby.jxpsource"})
public class RubyJxpSourceTest extends SourceRunner {
@BeforeMethod(groups={"ruby", "ruby.jxpsource"})
public void setUp() {
super.setUp();
runJS("add_seven = function(i) { return i + 7; };" +
"two_args = function(a, b) { return a + b; };" +
"data = {};" +
"data.count = 1;" +
"data.subobj = {};" +
"data.subobj.subvar = 99;" +
"data.subobj.add_seven = add_seven;" +
"data.add_seven = add_seven;" +
"array = [100, \"test string\", null, add_seven];");
}
public void testContent() {
assertRubyEquals("puts 1 + 1", "2");
}
public void testGlobalsAreDefined() {
runRuby("puts \"#{$data == nil ? 'oops: global $data is not defined' : 'ok'}\"");
assertEquals(rubyOutput, "ok");
}
public void testNewGlobalsGetCreated() {
runRuby("$foo = $data.count");
assertEquals(s.get("foo").toString(), "1"); // proves $data exists and $foo is created
}
public void testScopeToVar() {
assertRubyEquals("puts $data.count;", "1");
}
public void testCallFuncInVar() {
assertRubyEquals("puts $data.add_seven(35)", "42");
}
public void testCallTopLevelFunc() {
assertRubyEquals("puts add_seven(35)", "42");
}
public void testCallTopLevelFuncInsideFunc() {
assertRubyEquals("def foo; puts add_seven(35); end; foo()", "42");
}
public void testCallTopLevelFuncInsideMethod() {
assertRubyEquals("class Foo; def foo; puts add_seven(35); end; end; Foo.new.foo()", "42");
}
public void testGet() {
assertRubyEquals("puts $data.get('count')", "1");
}
public void testGetUsingHashSyntax() {
assertRubyEquals("puts $data['count']", "1");
}
public void testRubyModifiesJS() {
runRuby("$data.count = 42");
assertEquals(s.eval("data.count").toString(), "42");
}
public void testModifyUsingSet() {
runRuby("$data.set('count', 42)");
assertEquals(s.eval("data.count").toString(), "42");
}
public void testModifyUsingHash() {
runRuby("$data['count'] = 42");
assertEquals(s.eval("data.count").toString(), "42");
}
public void testCreateNew() {
runRuby("$data['vint'] = 3; $data.vfloat = 4.2; $data.varray = [1, 2, 'three']; $data.vhash = {'a' => 1, 'b' => 2}");
JSObject data = (JSObject)s.get("data");
assertEquals(data.get("vint").toString(), "3");
assertEquals(data.get("vfloat").toString(), "4.2");
assertEquals(data.get("varray").toString(), "1,2,three");
JSObject vhash = (JSObject)data.get("vhash");
assertEquals(vhash.get("a").toString(), "1");
assertEquals(vhash.get("b").toString(), "2");
}
public void testBuiltIn() {
assertRubyEquals("puts $data.keySet.sort", "add_seven\ncount\nsubobj");
}
public void testSubObject() {
assertRubyEquals("puts $data.subobj.subvar", "99");
assertRubyEquals("puts $data.subobj.add_seven(35)", "42");
}
public void testReadScope() {
assertRubyEquals("puts $scope.get('array')[1]", "test string");
}
public void testWriteScope() {
runRuby("$scope.set('new_thing', 57)");
assertNotNull(s.get("new_thing"), "'new_thing' not defined in scope");
assertEquals(s.get("new_thing").toString(), "57");
}
public void testWriteScopeUsingHashSyntax() {
runRuby("$scope['new_thing'] = 57");
assertNotNull(s.get("new_thing"), "'new_thing' not defined in scope");
assertEquals(s.get("new_thing").toString(), "57");
}
public void testArrayModsAreExported() {
runRuby("$array[0] = 99");
runJS("print(array[0]);");
assertEquals(jsOutput, "99");
}
public void testInnerArrayModsAreExported() {
runJS("data.array = [1, 2, 3];");
runRuby("$data.array[0] = 99");
runJS("print(data.array[0]);");
assertEquals(jsOutput, "99");
}
public void testHashModsAreExported() {
JSMap map = new JSMap();
map.set(new JSString("a"), new Integer(1));
map.set(new Long(42), new JSString("test string"));
s.set("hash", map);
// sanity test
runRuby("puts \"#{$hash == nil ? 'oops: global $hash is not defined' : 'ok'}\"");
assertEquals(rubyOutput, "ok");
runRuby("puts \"#{$hash['a'].to_s == '1' ? 'ok' : 'oops: $hash[\"a\"] is not defined properly'}\"");
assertEquals(rubyOutput, "ok");
runRuby("$hash['a'] = 99");
runJS("print(hash['a']);");
assertEquals(jsOutput, "99");
}
public void testInnerHashModsAreExported() {
JSMap map = new JSMap();
map.set(new JSString("a"), new Integer(1));
map.set(new Long(42), new JSString("test string"));
((JSObject)s.get("data")).set("hash", map);
// sanity test
runRuby("puts \"#{$data.hash == nil ? 'oops: global $data.hash is not defined' : 'ok'}\"");
assertEquals(rubyOutput, "ok");
runRuby("s = $data.hash['a'].to_s; if s == '1'; puts 'ok'; else; puts \"oops: $data.hash['a'] is not defined properly; it is #{s}\"; end");
assertEquals(rubyOutput, "ok");
Object o = ((JSObject)s.get("data")).get("hash");
assertTrue(o instanceof JSMap, "oops: JS hash is " + o.getClass().getName() + ", not a JSMap");
runRuby("$data.hash['a'] = 99");
runJS("print(data.hash['a']);");
assertEquals(jsOutput, "99");
}
public void testIncludeParentScopes() {
s.put("adult", new Integer(555));
Scope child = new Scope("child", s);
child.put("kiddie", new Integer(666));
s = child;
assertRubyEquals("puts $adult; puts $kiddie", "555\n666");
}
}
|
import java.lang.IllegalArgumentException;
import java.util.Random;
public class FederalTax {
private float grossIncome;
private float withheld;
private float[] bracket;
private float[] percentage;
private float standardDeductible;
private float personalExemption;
private float deductible;
private float childCredit;
private float amtThres;
private float adjustedGrossIncome;
private int headCount = 3;
public FederalTax(int year, float income, float withheld, float exemptAGI) {
this.grossIncome = income;
this.adjustedGrossIncome = this.grossIncome - exemptAGI;
this.withheld = withheld;
switch (year) {
case 2014:
this.bracket = new float[]{0f, 18150f, 73800f, 148850f, 226850f, 405100f, 457600f, Float.MAX_VALUE};
this.percentage = new float[]{0f, .1f, .15f, .25f, .28f, .33f, .35f, .396f};
this.standardDeductible = 12400f;
this.personalExemption = 3950f;
this.childCredit = 1000f;
this.amtThres = 82100f;
break;
case 2013:
this.bracket = new float[]{0f, 17850f, 72500f, 146400f, 223050f, 398350f, 450000f, Float.MAX_VALUE};
this.percentage = new float[]{0f, .1f, .15f, .25f, .28f, .33f, .35f, .396f};
this.standardDeductible = 12200f;
this.personalExemption = 3900f;
this.childCredit = 1000f;
this.amtThres = 80800f;
break;
default:
throw new IllegalArgumentException("invalid year for tax bracket");
}
this.deductible = standardDeductible + headCount * personalExemption;
}
private float getTax(float taxable) {
if (taxable <= 0f) throw new IllegalArgumentException("taxable amount must be positive");
float taxDue = 0f;
for (int i = 1; i < bracket.length; i++) {
if (this.bracket[i] < taxable) taxDue += this.percentage[i] * (this.bracket[i] - this.bracket[i - 1]);
else {
taxDue += this.percentage[i] * (taxable - this.bracket[i - 1]);
break;
}
}
return taxDue;
}
private float getAMT(float agi, float tax) {
float amt = 0f;
if (agi > this.amtThres) {
float line30 = agi - this.amtThres;
if (line30 <= 179500f) {
amt = line30 * .26f;
} else {
amt = line30 * .28f - 3590f;
}
}
return (amt > tax) ? (amt - tax) : 0f;
}
public float addDeductible(float value) {
this.deductible += value;
return this.deductible;
}
public float run() {
float taxable = adjustedGrossIncome - deductible;
float tax = getTax(taxable);
tax += getAMT(adjustedGrossIncome, tax);
tax -= childCredit;
return withheld - tax;
}
private static float run2014(float ws401k, boolean iraDeductible) {
float income = 80867.01f; // + 22534.25f;
float withheld = 14807.61f;
float taxablePerPay = 4916.66f - 110.37f - 31.95f - 28.58f - 37.5f;
float totalIRA = 6 * ws401k * 4916.66f;
float wsIncome= 6 * taxablePerPay - totalIRA + 75f;
income += wsIncome;
withheld += 0.165f * wsIncome;
float iraDeduction;
iraDeduction = iraDeductible ? 5500f : 0f;
totalIRA += iraDeduction;
FederalTax taxPayer = new FederalTax(2014, income, withheld, iraDeduction);
System.out.printf("Gross Income: $%.2f\tTaxable Income: $%.2f\tIRA: $%.2f ", income, taxPayer.grossIncome - taxPayer.deductible, totalIRA);
return taxPayer.run();
}
public static void main(String[] args) {
float income = 91571f;
float withheld = 16226.56f;
float iraDeduction = 5500f;
FederalTax taxPayer = new FederalTax(2013, income, withheld, iraDeduction);
System.out.printf("2013 Gross Income: $%.2f, Taxable Income: $%.2f, Tax Return: $%.2f\n", income, taxPayer.grossIncome - taxPayer.deductible, taxPayer.run());
System.out.printf("2014\n");
for (float ws401k = 0f; ws401k <= 0.15f; ws401k = ws401k + 0.01f) {
System.out.printf("\tReturn: $%.2f\n", run2014(ws401k, false));
}
System.out.println("
for (float ws401k = 0f; ws401k <= 0.15f; ws401k = ws401k + 0.01f) {
System.out.printf("\tReturn: $%.2f\n", run2014(ws401k, true));
}
}
}
|
package com.imgix.test;
import static org.junit.Assert.*;
import com.imgix.URLBuilder;
import java.util.*;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class TestReadMe {
@Test
public void testReadMeWidthTolerance() {
URLBuilder ub = new URLBuilder("demo.imgix.net", true, "", false);
HashMap<String, String> params = new HashMap<String, String>();
String actual = ub.createSrcSet("image.jpg", params, 100, 384, 0.20);
String expected =
"https://demo.imgix.net/image.jpg?w=100 100w,\n"
+ "https://demo.imgix.net/image.jpg?w=140 140w,\n"
+ "https://demo.imgix.net/image.jpg?w=196 196w,\n"
+ "https://demo.imgix.net/image.jpg?w=274 274w,\n"
+ "https://demo.imgix.net/image.jpg?w=384 384w";
assertEquals(expected, actual);
}
@Test
public void testReadMeMinMaxWidthRanges() {
URLBuilder ub = new URLBuilder("demo.imgix.net", true, "", false);
HashMap<String, String> params = new HashMap<String, String>();
String actual = ub.createSrcSet("image.jpg", params, 500, 2000);
String expected =
"https://demo.imgix.net/image.jpg?w=500 500w,\n"
+ "https://demo.imgix.net/image.jpg?w=580 580w,\n"
+ "https://demo.imgix.net/image.jpg?w=673 673w,\n"
+ "https://demo.imgix.net/image.jpg?w=780 780w,\n"
+ "https://demo.imgix.net/image.jpg?w=905 905w,\n"
+ "https://demo.imgix.net/image.jpg?w=1050 1050w,\n"
+ "https://demo.imgix.net/image.jpg?w=1218 1218w,\n"
+ "https://demo.imgix.net/image.jpg?w=1413 1413w,\n"
+ "https://demo.imgix.net/image.jpg?w=1639 1639w,\n"
+ "https://demo.imgix.net/image.jpg?w=1901 1901w,\n"
+ "https://demo.imgix.net/image.jpg?w=2000 2000w";
assertEquals(expected, actual);
}
@Test
public void testReadMeCustomWidths() {
URLBuilder ub = new URLBuilder("demo.imgix.net", true, "", false);
HashMap<String, String> params = new HashMap<String, String>();
String actual = ub.createSrcSet("image.jpg", params, new Integer[] {144, 240, 320, 446, 640});
String expected =
"https://demo.imgix.net/image.jpg?w=144 144w,\n"
+ "https://demo.imgix.net/image.jpg?w=240 240w,\n"
+ "https://demo.imgix.net/image.jpg?w=320 320w,\n"
+ "https://demo.imgix.net/image.jpg?w=446 446w,\n"
+ "https://demo.imgix.net/image.jpg?w=640 640w";
assertEquals(expected, actual);
}
@Test
public void testReadMeVariableQuality() {
URLBuilder ub = new URLBuilder("demo.imgix.net", true, "", false);
HashMap<String, String> params = new HashMap<String, String>();
params.put("w", "100");
String actual = ub.createSrcSet("image.jpg", params, false);
String expected =
"https://demo.imgix.net/image.jpg?dpr=1&q=75&w=100 1x,\n"
+ "https://demo.imgix.net/image.jpg?dpr=2&q=50&w=100 2x,\n"
+ "https://demo.imgix.net/image.jpg?dpr=3&q=35&w=100 3x,\n"
+ "https://demo.imgix.net/image.jpg?dpr=4&q=23&w=100 4x,\n"
+ "https://demo.imgix.net/image.jpg?dpr=5&q=20&w=100 5x";
assertEquals(expected, actual);
}
@Test
public void testReadMeFixedWidthImages() {
URLBuilder ub = new URLBuilder("demo.imgix.net", true, "", false);
HashMap<String, String> params = new HashMap<String, String>();
params.put("h", "800");
params.put("ar", "3:2");
params.put("fit", "crop");
String actual = ub.createSrcSet("image.jpg", params, false);
String expected =
"https://demo.imgix.net/image.jpg?ar=3%3A2&dpr=1&fit=crop&h=800&q=75 1x,\n"
+ "https://demo.imgix.net/image.jpg?ar=3%3A2&dpr=2&fit=crop&h=800&q=50 2x,\n"
+ "https://demo.imgix.net/image.jpg?ar=3%3A2&dpr=3&fit=crop&h=800&q=35 3x,\n"
+ "https://demo.imgix.net/image.jpg?ar=3%3A2&dpr=4&fit=crop&h=800&q=23 4x,\n"
+ "https://demo.imgix.net/image.jpg?ar=3%3A2&dpr=5&fit=crop&h=800&q=20 5x";
assertEquals(expected, actual);
}
}
|
package com.scarytom;
import junit.framework.Assert;
import org.junit.Test;
public class PrintoutTest {
@Test
public void testCanDescribeEmptyNetwork() {
String result = new Network().printout();
String header = "Programmer\tSkills\tRecommends";
Assert.assertEquals(header, result);
}
@Test
public void testCanDescribeSingleNodeNetwork() {
String result = new Network().printout();
String header = "Programmer\tSkills\tRecommends";
Assert.assertEquals(header, result);
}
}
|
package guitests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ClearCommandTest extends TaskManagerGuiTest {
@Test
public void clear() {
//verify a non-empty list can be cleared
assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
assertClearCommandSuccess("all");
//verify other commands can work after a clear command
commandBox.runCommand(td.hoon.getAddCommand());
assertTrue(taskListPanel.isListMatching(td.hoon));
commandBox.runCommand("delete 1");
assertListSize(0);
//verify clear command works when the list is empty
assertClearCommandSuccess("all");
}
@Test
public void clearDone() {
//prepare test
commandBox.runCommand("mark 1");
commandBox.runCommand("mark 2");
commandBox.runCommand("mark 3");
//verify done tasks can be cleared
assertClearCommandSuccess("done");
assertListSize(4);
}
private void assertClearCommandSuccess(String parameter) {
commandBox.runCommand("clear " + parameter);
if ("all".equals(parameter)) {
assertListSize(0);
} else {
assertListSize(4);
}
assertResultMessage("Task Manager has been cleared!");
}
}
|
package objektwerks;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class RecursionTest {
int product(int[] xs, int acc) {
if (xs.length == 0) return acc;
else {
var from = 1;
var to = xs.length;
var head = xs[0];
var tail = Arrays.copyOfRange(xs, from, to);
System.out.println("from: " + from);
System.out.println("to: " + to);
System.out.println("head: " + head);
System.out.println("tail: " + Arrays.toString(tail));
return product(tail, acc * head);
}
}
@Test void productTest() {
int[] xs = {1, 2, 3};
var product = product( xs, 1);
System.out.println("product: " + product);
assert(product == 6);
}
int sum(int[] xs, int acc) {
if (xs.length == 0) return acc;
else {
var from = 1;
var to = xs.length;
var head = xs[0];
var tail = Arrays.copyOfRange(xs, from, to);
System.out.println("from: " + from);
System.out.println("to: " + to);
System.out.println("head: " + head);
System.out.println("tail: " + Arrays.toString(tail));
return sum(tail, acc + head);
}
}
@Test void sumTest() {
int[] xs = {1, 2, 3};
var sum = sum( xs, 0);
System.out.println("sum: " + sum);
assert(sum == 6);
}
List<String> reverse(List<String> values, List<String> acc) {
if (values.isEmpty()) return acc;
else {
var from = 1;
var to = values.size();
var head = values.get(0);
var tail = values.subList(from, to);
System.out.println("from: " + from);
System.out.println("to: " + to);
System.out.println("head: " + head);
System.out.println("tail: " + tail);
acc.add(0, head);
return reverse(tail, acc);
}
}
@Test void reverseTest() {
var values = new ArrayList<String>();
values.add("a");
values.add("b");
values.add("c");
var acc = new ArrayList<String>();
var reversed = reverse(values, acc);
System.out.println("reversed: " + reversed);
assert(reversed.equals(List.of("c", "b", "a")));
}
int factorial(int n, int acc) {
if (n < 1) return acc;
else return factorial(n - 1, acc * n);
}
@Test void factorialTest() {
assert(factorial(3, 1) == 6);
}
}
|
package org.c4sg;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.c4sg.entity.Organization;
import org.c4sg.entity.Project;
import org.c4sg.entity.User;
import org.c4sg.service.AsyncEmailService;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {C4SgApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EmailServiceTest {
private String from = "info@code4socialgood.org";
private String message = "You received an application from Code for Social Good. \" \n" +
" + \"Please login to the dashboard to review the application.";
private GreenMail mailer;
@Autowired
private AsyncEmailService mailService;
@Before
public void setUp() {
mailer = new GreenMail(new ServerSetup(8825, null, "smtp"));
mailer.start();
}
@After
public void tearDown() {
mailer.stop();
}
@Test
public void testSendVolunteerApplicationEmail() throws MessagingException {
List<String> skills = Arrays.asList("Tester", "Coder", "Cop");
User user = new User();
user.setEmail("rogwara@nimworks.com");
user.setFirstName("Rowland");
user.setLastName("Ogwara");
user.setTitle("Coolio Developer");
user.setChatUsername("rogwara");
user.setIntroduction("Something very interesting about this person");
Project project = new Project();
project.setName("Test Project");
Map<String, Object> mailContext = new HashMap<String, Object>();
mailContext.put("user", user);
mailContext.put("skills", skills);
mailContext.put("project", project);
mailContext.put("message", message);
mailService.sendWithContext(from, user.getEmail(), "Test Email", "volunteer-application", mailContext);
// received message
MimeMessage[] receivedMessages = mailer.getReceivedMessages();
assertEquals(1, receivedMessages.length);
MimeMessage msg = receivedMessages[0];
assertThat(from, is(msg.getFrom()[0].toString()));
assertThat("Test Email", is(msg.getSubject()));
}
@Test
public void testSendVolunteerApplicantEmail() throws MessagingException {
Organization org = new Organization();
org.setName("Test Organization");
org.setContactEmail("test@c4sg.org");
org.setContactName("John Sloan");
org.setContactPhone("9898989899");
User user = new User();
user.setEmail("test@c4sg.org");
user.setFirstName("John");
user.setLastName("Sloan");
user.setChatUsername("jsloan");
Project project = new Project();
project.setId(110);
project.setName("Test Project");
Map<String, Object> mailContext = new HashMap<String, Object>();
mailContext.put("org", org);
mailContext.put("user", user);
mailContext.put("projectLink", "http://codeforsocialgood.org");
mailContext.put("project", project);
mailService.sendWithContext(from, user.getEmail(), "Test Email", "applicant-application", mailContext);
// received message
MimeMessage[] receivedMessages = mailer.getReceivedMessages();
assertEquals(1, receivedMessages.length);
MimeMessage msg = receivedMessages[0];
assertThat(from, is(msg.getFrom()[0].toString()));
assertThat("Test Email", is(msg.getSubject()));
}
}
|
package org.mapdb;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import static org.junit.Assert.*;
public class StoreAppendTest<E extends StoreAppend> extends EngineTest<E>{
File f = UtilsTest.tempDbFile();
@Override
protected E openEngine() {
return (E) new StoreAppend(f);
}
@Test @Ignore
public void compact_file_deleted(){
File f = UtilsTest.tempDbFile();
StoreAppend engine = new StoreAppend(f);
File f1 = engine.getFileFromNum(0);
File f2 = engine.getFileFromNum(1);
long recid = engine.put(111L, Serializer.LONG);
Long i=0L;
for(;i< StoreAppend.FILE_MASK+1000; i+=8){
engine.update(recid, i, Serializer.LONG);
}
i-=8;
assertTrue(f1.exists());
assertTrue(f2.exists());
assertEquals(i, engine.get(recid, Serializer.LONG));
engine.commit();
assertTrue(f1.exists());
assertTrue(f2.exists());
assertEquals(i, engine.get(recid, Serializer.LONG));
engine.compact();
assertFalse(f1.exists());
assertTrue(f2.exists());
assertEquals(i, engine.get(recid, Serializer.LONG));
f1.delete();
f2.delete();
engine.close();
}
@Test public void delete_files_after_close(){
File f = UtilsTest.tempDbFile();
File f2 = new File(f.getPath()+".0");
DB db = DBMaker.newAppendFileDB(f).deleteFilesAfterClose().make();
db.getHashMap("test").put("aa","bb");
db.commit();
assertTrue(f2.exists());
db.close();
assertFalse(f2.exists());
}
@Test public void header_created() throws IOException {
//check offset
assertEquals(StoreAppend.LAST_RESERVED_RECID, e.maxRecid);
assertEquals(1+8+2*StoreAppend.LAST_RESERVED_RECID, e.currPos);
RandomAccessFile raf = new RandomAccessFile(e.getFileFromNum(0),"r");
//check header
raf.seek(0);
assertEquals(StoreAppend.HEADER, raf.readLong());
//check reserved recids
for(int recid=1;recid<=StoreAppend.LAST_RESERVED_RECID;recid++){
assertEquals(0, e.index.getLong(recid*8));
assertEquals(recid+StoreAppend.RECIDP,raf.read()); //packed long
assertEquals(0+StoreAppend.SIZEP,raf.read()); //packed long
}
assertEquals(StoreAppend.END+StoreAppend.RECIDP,raf.read()); //packed long
//check recid iteration
assertFalse(e.getFreeRecids().hasNext());
}
@Test public void put(){
long oldPos = e.currPos;
Volume vol = e.currVolume;
assertEquals(0, vol.getUnsignedByte(oldPos));
long maxRecid = e.maxRecid;
long value = 11111111111111L;
long recid = e.put(value,Serializer.LONG);
assertEquals(maxRecid+1, recid);
assertEquals(e.maxRecid, recid);
assertEquals(recid+StoreAppend.RECIDP, vol.getPackedLong(oldPos));
assertEquals(8+StoreAppend.SIZEP, vol.getPackedLong(oldPos+1));
assertEquals(value, vol.getLong(oldPos+2));
assertEquals(Long.valueOf(oldPos+1), e.indexInTx.get(recid));
e.commit();
assertEquals(oldPos+1, e.index.getLong(recid*8));
}
@Override public void large_record_larger(){
//TODO ignored test
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.